Python中的OnSerialData()事件?

2024-10-02 18:19:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用pyserialpython库从Arduino读取串行数据。轮询新数据需要我实现一个update()方法,我必须一秒钟调用几次。这将是缓慢的,CPU密集型,即使没有通信发生。你知道吗

有我可以使用的OnSerialData()事件吗?每次新的串行数据到达缓冲区时都要执行的例程?我用过的大多数其他语言都有一个等价的。你知道吗

我对threading相当陌生,但有一种感觉,它牵涉其中。你知道吗


Tags: 数据方法语言事件updatecpu例程arduino
1条回答
网友
1楼 · 发布于 2024-10-02 18:19:56

一个标准的方法是使用一个线程。你知道吗

这样的方法应该有用:

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库中)

相关问题 更多 >