Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serial programming: measuring time between characters

I am sending/receiving data over a serial line in Linux and I would like to find the delay between characters.

Modbus uses a 3.5 character delay to detect message frame boundaries. If there is more than a 1.5 character delay, the message frame is declared incomplete.

I'm writing a quick program in C which is basically

fd = open(MODEMDEVICE, O_RDWR | O_NOCTTY | O_NONBLOCK);
// setup newtio
....
tcsetattr(fd, TCSANOW, &newtio);
for(;;) {
    res = read(fs, buf, 1);
    if (res > 0) {
        // store time in milliseconds?
        //do stuff
    }
}

Is there some way of measuring the time here? Or do I need to look at retrieving data from the serial line in a different way?

I've also tried hooking into SIGIO to get a signal whenever there is data but I seem to get data 8 bytes at a time.

(yes, I know there exist some modbus libraries but I want to use this in other applications)

like image 254
Nick Sonneveld Avatar asked Aug 24 '26 09:08

Nick Sonneveld


1 Answers

The simple answer is... you cannot (not without writing you own serial driver)!

If you are writing a MODBUS master there is some hope: You can either detect the end of a slave response by waiting any amount of time (provided its longer than 3.5 chars) without receiving anything (select(2) can help you here), or by parsing the response on the fly, as you read it (the second method wastes much less time). You must also be careful to wait at least 3.5 characters-time before staring to transmit a new request, after receiving the response to the previous request. "At least" is operative here! Waiting more doesn't matter. Waiting less does.

If you a writing a MODBUS slave then you' re out of luck. You simply cannot do it reliably from userspace Linux. You have to write you own serial driver.

BTW, this is not Linux's fault. This is due to the unbelievable stupidity of MODBUS's framing method.

like image 194
npat Avatar answered Aug 26 '26 23:08

npat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!