pySerial buffer won't flush

匿名 (未验证) 提交于 2019-12-03 02:56:01

问题:

I'm having a problem with serial IO under both Windows and Linux using pySerial. With this code the device never receives the command and the read times out:

import serial ser = serial.Serial('/dev/ttyUSB0',9600,timeout=5) ser.write("get") ser.flush() print ser.read() 

This code times out the first time through, but subsequent iterations succeed:

import serial ser = serial.Serial('/dev/ttyUSB0',9600,timeout=5) while True:     ser.write("get")     ser.flush()     print ser.read() 

Can anyone tell what's going on? I tried to add a call to sync() but it wouldn't take a serial object as it's argument.

Thanks, Robert

回答1:

Put some delay in between write and read e.g.

import serial ser = serial.Serial('/dev/ttyUSB0',9600,timeout=5) ser.flushInput() ser.flushOutput() ser.write("get")   # sleep(1) for 100 millisecond delay # 100ms dely sleep(.1) print ser.read() 


回答2:

This is because pyserial returns from opening the port before it is actually ready. I've noticed that things like flushInput() don't actually clear the input buffer, for example, if called immediately after the open(). Following is code to demonstrate:

import unittest import serial import time """ 1) create a virtual or real connection between COM12 and COM13 2) in a terminal connected to COM12 (at 9600, N81), enter some junk text (e.g.'sdgfdsgasdg') 3) then execute this unit test """  class Test_test1(unittest.TestCase):     def test_A(self):         with serial.Serial(port='COM13', baudrate=9600) as s:   # open serial port             print("Read ASAP:  {}".format(s.read(s.in_waiting)))             time.sleep(0.1)     # wait fro 100 ms for pyserial port to actually be ready             print("Read after delay:  {}".format(s.read(s.in_waiting)))  if __name__ == '__main__':     unittest.main()  """ output will be: Read ASAP:  b'' Read after delay:  b'sdgfdsgasdg' . ---------------------------------------------------------------------- Ran 1 test in 0.101s """ 

My workaround has been to implement a 100ms delay after opening before doing anything.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!