2013-07-09 288 views
15

我读的串行数据是这样的:PySerial非阻塞读循环

connected = False 
port = 'COM4' 
baud = 9600 

ser = serial.Serial(port, baud, timeout=0) 

while not connected: 
    #serin = ser.read() 
    connected = True 

    while True: 
     print("test") 
     reading = ser.readline().decode() 

的问题是,它可以防止任何从执行包括瓶PY Web框架别的。添加sleep()将无济于事。

更改“而真正的””来‘而ser.readline():’不打印‘测试’,这是奇怪的,因为它在Python 2.7工作的任何想法可能是错误的

理想?我应该能够读取串行数据,只有当它的可用数据被每1000毫秒发送

+3

难道你创建一个线程,并添加该代码读它? –

+1

串行通讯正在阻止...您应该使用线程 –

+0

您可以用示例发布答案吗? – DominicM

回答

28

把它放在一个单独的线程,例如:。

import threading 
import serial 

connected = False 
port = 'COM4' 
baud = 9600 

serial_port = serial.Serial(port, baud, timeout=0) 

def handle_data(data): 
    print(data) 

def read_from_port(ser): 
    while not connected: 
     #serin = ser.read() 
     connected = True 

     while True: 
      print("test") 
      reading = ser.readline().decode() 
      handle_data(reading) 

thread = threading.Thread(target=read_from_port, args=(serial_port,)) 
thread.start() 

http://docs.python.org/3/library/threading

21

使用单独的线程是完全没有必要的。只是这样做你的无限while循环,而不是(在Python 3.2.3测试):

while (True): 
    if (ser.inWaiting()>0): #if incoming bytes are waiting to be read from the serial input buffer 
     data_str = ser.read(ser.inWaiting()).decode('ascii') #read the bytes and convert from binary array to ASCII 
     print(data_str, end='') #print the incoming string without putting a new-line ('\n') automatically after every print() 
    #Put the rest of your code you want here 

这样,你只能阅读和打印,如果事情是存在的。你说,“理想情况下,我应该只能在串行数据可用时才能读取。”这正是上面的代码所做的。如果没有可读的内容,它跳转到while循环中的其余代码。完全无阻塞。

(这个答案最初发布&这里调试:Python 3 non-blocking read with pySerial (Cannot get pySerial's "in_waiting" property to work)

pySerial文档:http://pyserial.readthedocs.io/en/latest/pyserial_api.html

+1

谢谢!这个解决方案让我今天走出困境。我真的觉得这应该是在这种情况下被接受的答案。 –

+2

而不是while(True)我建议使用while(ser.isOpen()) – Johnny

+1

PySerial版本> 3,您需要使用ser.is_open – Johnny