Python 中的 OnSerialData() 事件?
OnSerialData() Event in Python?
我正在使用 pyserial python 库从 Arduino 读取串行数据。轮询新数据需要我实现一个 update()
方法,我必须每秒调用几次。这会很慢并且 CPU 密集,即使没有通信发生也是如此。
有没有我可以使用的 OnSerialData()
事件?每次新串行数据到达缓冲区时都会执行的例程?我使用过的大多数其他语言都有等效项。
我对 threading
比较陌生,但有一种感觉。
标准方法是为此使用线程。
像这样的东西应该可以工作:
import threading
import serial
import io
import sys
exit_loop = False
def reader_thread(ser):
while not exit_loop:
ch = ser.read(1)
do_something(ch)
def do_something(ch):
print "got a character:", ch
ser = serial.serial_for_url(...)
thr = threading.Thread(target = reader_thread, args=[ser])
thr.start()
# when ready to shutdown...
exit_loop = True
if hasattr(ser, 'cancel_read'):
ser.cancel_read()
thr.join()
另见 serial.threaded
模块(也包含在 pyserial 库中。)
我正在使用 pyserial python 库从 Arduino 读取串行数据。轮询新数据需要我实现一个 update()
方法,我必须每秒调用几次。这会很慢并且 CPU 密集,即使没有通信发生也是如此。
有没有我可以使用的 OnSerialData()
事件?每次新串行数据到达缓冲区时都会执行的例程?我使用过的大多数其他语言都有等效项。
我对 threading
比较陌生,但有一种感觉。
标准方法是为此使用线程。
像这样的东西应该可以工作:
import threading
import serial
import io
import sys
exit_loop = False
def reader_thread(ser):
while not exit_loop:
ch = ser.read(1)
do_something(ch)
def do_something(ch):
print "got a character:", ch
ser = serial.serial_for_url(...)
thr = threading.Thread(target = reader_thread, args=[ser])
thr.start()
# when ready to shutdown...
exit_loop = True
if hasattr(ser, 'cancel_read'):
ser.cancel_read()
thr.join()
另见 serial.threaded
模块(也包含在 pyserial 库中。)