0

I'm reading data from USB serial with:

s = serial.Serial(port="COM1", baudrate=115200, write_timeout=0.010, timeout=0.010)
while polling:
    r = s.readline().decode("ascii")
    if r != '':
        v = float(r)
        print('new value', v)
    time.sleep(0.005)

I'm expecting data at a rate of 50 values per second, but in order to not miss anything, I'm only waiting 5 ms (200 Hz). This works but it is not optimal.

Is there a way to make readline() blocking? i.e. it should't return anything until new data comes. This way I could totally avoid the time.sleep(...) with the arbitrary 0.005 duration.

Problem: it seems that the hardware returns an empty string (or an empty string with newline) each time I do readline() when there is no new data.

Basj
  • 41,386
  • 99
  • 383
  • 673
  • 1
    I think `readline()`is already block. I had a similar problem when I used `readline` on Linux to read data from pipe. I changed readline from blocking to non-blocking by `fcntl`. It may help for you [How to get stdout from subprocess.Popen elegantly with timeout check?](https://stackoverflow.com/questions/71644398/how-to-get-stdout-from-subprocess-popen-elegantly-with-timeout-check) – Lanbao Jun 16 '22 at 05:33
  • @CN-LanBao Thank you. Do you think the problem might come from the fact the hardware always answer an empty string (or an empty string + newline) even if there is no new data? – Basj Jun 16 '22 at 06:05
  • Yeah, that's very possible, maybe you can use param like `.read(size=1)` to set the bytes read at a time? @Basj – Lanbao Jun 16 '22 at 06:53
  • Isn't it good to judge whether [in_waiting](https://pyserial.readthedocs.io/en/latest/pyserial_api.html#serial.Serial.in_waiting) is 1 or more and [readline()](https://pyserial.readthedocs.io/en/latest/pyserial_api.html#serial.Serial.readline) only then? – kunif Jun 16 '22 at 12:07

0 Answers0