pySerial inWaiting returns incorrect number of bytes

后端 未结 2 1988
陌清茗
陌清茗 2020-12-19 18:34

I\'ve got a simple program to test serial functionality. My serial device reacts to two inputs. If the user enters \'a\', it responds with \'fg\'. If the user enters anythin

2条回答
  •  庸人自扰
    2020-12-19 19:01

    it could be because the baudrate is really slow. You are processing the inwaiting() call before the second byte gets to the buffer. When you do ser.read(2) it waits(blocks) until 2 bytes have been received thus why it works. Try setting a timeout of 1 second, that should fix your problem.

    ser = serial.Serial(
        port = '/dev/ttyUSB0',
        baudrate = 9600,
        parity = serial.PARITY_NONE,
        stopbits = serial.STOPBITS_ONE,
        bytesize = serial.EIGHTBITS,
        timeout=1 # add this
        )
    ser.write('a')
    byteData = ser.read(1) # read one, blocking
    byteData += ser.read(ser.inWaiting())
    
    print byteData
    
    ser.close()
    

提交回复
热议问题