de-vri-es / serial2-rs

Cross platform serial ports for Rust
Other
48 stars 11 forks source link

I need an algorithm to calculate how long write() takes. #35

Closed wc7086 closed 4 months ago

wc7086 commented 4 months ago

I have not tested this further, and so far have found that even sending two bytes of data in a row has a very high chance of losing the second byte.

I've found that at high enough baud rates, it only takes a theoretical value of one bit (1s / rate) to send a byte (write()), whereas at very low baud rates (e.g. 9600 bps), the theoretical value doesn't take enough time to complete a byte.

wc7086 commented 4 months ago

My current solution is to add a 50 microsecond delay after each write.

wc7086 commented 4 months ago

I have found that it has to do with the baud rate and when I use the 460800 baud rate I can set the delay to 1 microsecond.

de-vri-es commented 4 months ago

You may run into the problem that to transfer one byte, you have to transfer more than one bit: there's also the start condition, optional parity bit and the stop bit(s). You have to take those into account too.

But then there's also potential scheduling overhead in the kernel. And if you sleep in your own process, you also don't have any guarantee about the exact length of your sleep.

What is your end goal exactly? Do you want to calculate a good value for a read/write timeout?

wc7086 commented 4 months ago

What is your end goal exactly? Do you want to calculate a good value for a read/write timeout?

I need to transfer data continuously, so I want to calculate the time between each wire() interval at the current baud rate to ensure that data is not overwritten.

After multiple attempts, I gave up. With a baud rate of approximately 500,000 bps, only a few tens of nanoseconds of delay are needed. According to the theoretical calculation of 1s / rate * 10, the system scheduling overhead at this time reaches a few microseconds, and the differences between systems should be significant. Therefore, calculating the required time is impossible.