PySerial 非阻塞读取循环 [英] PySerial non-blocking read loop
问题描述
我正在读取这样的串行数据:
I am reading serial data like this:
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()
问题是它阻止了其他任何东西的执行,包括 Bottle py Web 框架.添加 sleep()
无济于事.
The problem is that it prevents anything else from executing including bottle py web framework. Adding sleep()
won't help.
将 "while True"" 更改为 "while ser.readline():" 不会打印 "test",这很奇怪,因为它在 Python 2.7 中工作.任何想法可能是错误的?
Changing "while True"" to "while ser.readline():" doesn't print "test", which is strange since it worked in Python 2.7. Any ideas what could be wrong?
理想情况下,我应该能够仅在可用时读取串行数据.每 1000 毫秒发送一次数据.
Ideally I should be able to read serial data only when it's available. Data is being sent every 1,000 ms.
推荐答案
放在单独的线程中,例如:
Put it in a separate thread, for example:
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
这篇关于PySerial 非阻塞读取循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!