python - 读取stm发送的串行数据

标签 python serial-port

我已经使用 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

最诚挚的问候

最佳答案

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

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

def read() 而真实: 此输入 = ser.read(1) 打印“已收到”,此输入 如果此输入 == ‘0’: ... elif 这个输入 == ‘1’: ... 别的: print ‘输入无法识别:%s’%(输入) 引发异常(“无效输入%s”%(Thisinput))

关于python - 读取stm发送的串行数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52474217/

相关文章:

c - 从这个缓冲区读取 'safest' 的方法是什么?

c# - 当传入串口的数据是异步的时,如何通过 Web 服务存储数据?

objective-c - Opticon F31 无法进入 VCP/串行模式

python - 在 Next.js 中运行 python 脚本

python - Pandas 使用 .resample() 返回关联属性

batch-file - 如何使用 Windows 批处理文件从 COM 端口发送一系列十六进制命令?

无法在 C 代码中模仿 `echo` 命令的 Action

python - Boost.Python 并导入一个 dll, "The specified module could not be found"

python - 如何扩大数据框 - Pandas

python - 在 Python 中使用 urllib2。被服务器检测并拒绝