How to enforce 250 millisecond delay between writes on a serial port?
I have a device (digital indicator) that I am communicating with using the SerialPort class. The device documentation states that I need to have a 250 millisecond delay between writes. Is there a way to enforce this without putting extra delay into the system? I know this probably sounds like I'm worrying too much about something that's really small, but there are three of these indicators and it is reading them quite often, but not all the time. Basically, is there a good way to enforce that you don't send again in less than 250 milliseconds, but if it's been 5 seconds and I try to send, I don't want to delay an additional 2开发者_如何学JAVA50 milliseconds for no reason.
Thoughts?
You should have some sort of class for the purpose of writing to the serial port, perhaps a single point of writing (a WriteToPort function or something).
In that, you could save the current time every time you write, then use logic on the delay for that. SO:
DateTime lastWritten;
TimeSpan timeBetweenWrites = new Timespan(0,0,0,0,250);
void WriteToDevice(string data)
{
TimeSpan sinceLastWrite=DateTime.Now-lastWritten;
if(sinceLastWrite<timeBetweenWrites)
Thread.Sleep(timeBetweenWrites-sinceLastWrite);
SerialPort.Write(data);
lastWritten=DateTime.Now;
}
Suspending the thread should work for you:
System.Threading.Thread.Sleep(250);
However, this can be a little inaccurate since you can't guarantee the next time your thread is going to be scheduled. If you need precise timings, you'd better use spin waits.
Fetch a timestamp before each transmission. Sleep for the 250-(now - then) milliseconds (clamped at zero, obviously). That seems to be what you're asking for.
If, instead, you're worried about things like OS scheduling issues making times that are not 250ms on average, or more than a tiny bit off from 250ms exactly, then you have a harder problem on our hand and you will need to read up on hard real time techniques (and perhaps purchase some extra hardware).
精彩评论