Accurate timing of serial breakstate

freddyokel

New member
Joined
Feb 25, 2014
Messages
4
Location
Bristol, England
Programming Experience
10+
Hi,
I'm writing a bit of code to talk to an external serial device (via USB-Serial converter).
This device requires the data line to be pulled low for 25ms and then high for 25ms before serial transmission starts.
Luckily, the SerialPort control has the Breakstate property to facilitate this kind of thing.
However, my problem is accurately timing the break state.

Here's a code fragment:

serPort.BreakState = True
Thread.Sleep(25)
serPort.BreakState = False
Thread.Sleep(25)

However, what the output trace on the logic analyser says is that the low state is 29ms long
and the high state is 30ms.

The 4-5ms which .net seems to be taking to flip the pin state is quite frankly an eternity which
is causing my remote device to go back to sleep again.
Obviously I can't just subtract 5ms from the wait time as this may be different on another machine.

Any ideas?

Ta,

Fredd
 
As you can read in documentation Sleep is for thread scheduling, it will suspend the thread for at least that time, but it can take longer for the thread to resume, it is not really meant for thread synchronization like that.
Try to use AutoResetEvent class and its WaitOne method for waiting (timeout).
 
Tried, but the timing is still very off. Exactly the same as Thread.Sleep.
With either method, any time value I try seems to get rounded to around the nearest 14-15ms.

I'm guessing that what I really need is an accurate method of just burning time instead of suspending the thread.
 
Although it sounds like a really dirty method of doing it,
this works much better.

Dim sw as Stopwatch

sw = Stopwatch.StartNew

sw.Reset
sw.Start
serPort.BreakState = True
While sw.ElapsedSeconds < 25

End While

sw.Reset
sw.Start
serPort.BreakState = False
While sw.ElapsedSeconds < 25

End While

 
Tried, but the timing is still very off. Exactly the same as Thread.Sleep.
I get weird results too when doing this in UI thread, when using a background thread I consistently get accuracy around +0.4 ms.
Although it sounds like a really dirty method of doing it,
this works much better.
That seems to work much better for this use, yes.
 

Latest posts

Back
Top