Using PySerial is it possible to wait for data?

前端 未结 3 1957
萌比男神i
萌比男神i 2020-12-08 08:00

I\'ve got a Python program which is reading data from a serial port via the PySerial module. The two conditions I need to keep in mind are: I don\'t know ho

相关标签:
3条回答
  • 2020-12-08 08:30
    def cmd(cmd,serial):
        out='';prev='101001011'
        serial.flushInput();serial.flushOutput()
        serial.write(cmd+'\r');
        while True:
            out+= str(serial.read(1))
            if prev == out: return out
            prev=out
        return out
    

    call it like this:

    cmd('ATZ',serial.Serial('/dev/ttyUSB0', timeout=1, baudrate=115000))
    
    0 讨论(0)
  • 2020-12-08 08:46

    Ok, I actually got something together that I like for this. Using a combination of read() with no timeout and the inWaiting() method:

    #Modified code from main loop: 
    s = serial.Serial(5)
    
    #Modified code from thread reading the serial port
    while 1:
      tdata = s.read()           # Wait forever for anything
      time.sleep(1)              # Sleep (or inWaiting() doesn't give the correct value)
      data_left = s.inWaiting()  # Get the number of characters ready to be read
      tdata += s.read(data_left) # Do the read and combine it with the first character
    
      ... #Rest of the code
    

    This seems to give the results I wanted, I guess this type of functionality doesn't exist as a single method in Python

    0 讨论(0)
  • 2020-12-08 08:48

    You can set timeout = None, then the read call will block until the requested number of bytes are there. If you want to wait until data arrives, just do a read(1) with timeout None. If you want to check data without blocking, do a read(1) with timeout zero, and check if it returns any data.

    (see documentation https://pyserial.readthedocs.io/en/latest/)

    0 讨论(0)
提交回复
热议问题