Using PySerial is it possible to wait for data?

前端 未结 3 1959
萌比男神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: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

提交回复
热议问题