Search code examples
.net-3.5serial-communication

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 250 milliseconds for no reason.

Thoughts?


Solution

  • 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;
    }