首页 > 解决方案 > 串行端口 - 无法读取数据,我只是写了

问题描述

我正在尝试通过串口对两个设备之间的通信进行简单的模拟(在 linux 上要清楚)。我想出了从串口读取数据到不同线程的想法,但问题是这个线程给我一个这样的错误:

Is open?  True
Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/lib/python3.7/threading.py", line 926, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.7/threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "client.py", line 18, in func
    if len(ser.readline()) > 0:
  File "/home/bartosz/PycharmProjects/socket-serial-comm/venv/lib/python3.7/site-packages/serial/serialposix.py", line 478, in read
    raise portNotOpenError
serial.serialutil.SerialException: Attempting to use a port that is not open

所以似乎我试图使用的端口没有打开,但是当我从这个线程打印时 print("Is open? ", ser.is_open) 它给了我 True,因此我无法在线程中打开端口。

这是我的代码:

import serial
import threading
import time


ser = serial.Serial('/dev/pts/0', timeout=1)


def func():
    print("Is open? ", ser.is_open)
    while True:
        if len(ser.readline()) > 0:
            print(ser.readline())


x = threading.Thread(target=func, args=ser)
x.start()
time.sleep(1)
ser.write(b'some text\n')

time.sleep(1)
ser.close()

有什么想法为什么会这样?

标签: pythonmultithreadingserial-portpyserial

解决方案


这与您编写的代码完全相同。

正在读取串行端口的进程永远在无限循环中运行While True:,但端口本身ser.close()在处理线程启动后大约 2 秒。
由于ser.readline()即使在之后执行ser.close(),也会出现问题错误。

在调用之前ser.close(),您需要安装一个机制来终止def func():线程处理。

顺便说一句,用len(ser.readline())inif语句判断print(ser.readline())有数据的过程需要输入两行,但是第一行不显示,只打印下一行会很奇怪。

您应该审查该过程。


推荐阅读