首页 > 解决方案 > python - 读取stm发送的串行数据

问题描述

我已经创建了与 python 到 stm32 usb 端口的连接,并希望在按下某个按钮时执行一些操作。(一个发送“1”,另一个发送“0”)。为什么这个解决方案不能按我的意愿工作?

def read():
while True:
    if ser.read(1) == 0:
            print "Zero received" 
            report.send(SET_LEFT())
    if ser.read(1) == 1:
            report.send(SET_RIGHT())
t = threading.Thread(target = read, name = 'thread1')
t.start()

这是关闭端口连接的串行初始化和 signal_handler 函数。

ser = serial.Serial(
    port='COM7',
    baudrate=9600,
    parity=serial.PARITY_EVEN,
    stopbits=serial.STOPBITS_ONE,
    bytesize=serial.EIGHTBITS,
    timeout=0)


def signal_handler(signal, frame):
       ser.close()
       sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)

当我关闭与“crtl + c”的连接时收到的错误是

Exception in thread thread1:
Traceback (most recent call last):
File "C:\Python27\lib\threading.py", line 801, in __bootstrap_inner
self.run()
File "C:\Python27\lib\threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
File "C:\usbpy\usb_send.py", line 27, in read
if ser.read() == 0:
File "C:\Python27\lib\site-packages\serial\serialwin32.py", line 269, in 
read
win32.ResetEvent(self._overlapped_read.hEvent)
AttributeError: 'NoneType' object has no attribute 'hEvent'

似乎在执行主程序期间未检测到该按钮,当我检查我与另一个 python 程序收到的连接和数据时,结果是:link

最好的祝福

标签: pythonserial-port

解决方案


如果没有其他问题,您的读取功能需要修复。ser.read(1) 值必须存储在一个变量中,因为您需要对该调用中接收到的数据进行多次比较 - 正如您编写的那样,如果第一次与 1 比较为假,则另一个 ser.read(1 ) (即不同的 dat)被制作并与 0 进行比较,并且没有将输入存储在变量中意味着您无法通过例如打印接收到的值来调试它。不明白为什么尝试调试它并没有让您将 ser.read(1) 返回值存储在变量中以便您可以打印它。

抱歉,无法测试此代码,但它应该如下所示:

def read() while True: Thisinput = ser.read(1) print “received”,Thisinput if Thisinput == ‘0’: ... elif Thisinput == ‘1’: ... else: print ‘Input not recognized:%s’%(input) raise Exception(“Invalid input %s”%(Thisinput) )


推荐阅读