以下代码(运行 on Raspberry Pi 4, Raspbian OS)串口连接有什么问题?

What's the problem with serial connection in the following code (running on Raspberry Pi 4, Raspbian OS)?

RPi 上的这个串行连接问题不应该这么具有挑战性,尽管现在我正面临着一些非常奇怪的事情

这是代码:

   .
   .
   import serial
   .
   .
   ser=serial.Serial(
       port='/dev/ttyUSB0',
       baudrate=115200,
       parity=serial.PARITY_NONE,
       stopbits=serial.STOPBITS_ONE,
       bytesize=serial.EIGHTBITS,
       timeout=1
   )
   .
   .

错误是:

Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/serial/serialposix.py", line 265, in open
    self.fd = os.open(self.portstr, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
FileNotFoundError: [Errno 2] No such file or directory: '/dev/ttyUSB0'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/pi/Desktop/rtu-v4/dnp3/rtu.py", line 27, in <module>
    timeout=1
  File "/usr/lib/python3/dist-packages/serial/serialutil.py", line 240, in __init__
    self.open()
  File "/usr/lib/python3/dist-packages/serial/serialposix.py", line 268, in open
    raise SerialException(msg.errno, "could not open port {}: {}".format(self._port, msg))
serial.serialutil.SerialException: [Errno 2] could not open port /dev/ttyUSB0: [Errno 2] No such file or directory: '/dev/ttyUSB0'

我已经签出:

https://www.raspberrypi.org/forums/viewtopic.php?t=224369

https://github.com/brendan-w/python-OBD/issues/137

和运行终端中的以下命令: sudo pip3 uninstall serial sudo pip3 install pyserial

设备是 Raspberry Pi 4

任何帮助将不胜感激。 谢谢。

消息"No such file or directory: '/dev/ttyUSB0'"表示您没有连接到USB0的设备。

您可以使用命令:

lsusb

找出哪些端口可用,然后更改您的代码 USB 名称以连接正确的设备。

由于您正在尝试与 USB 转串口适配器通信(我假设),您可以使用 dmesg 获取连接到 ttyUSB0 的设备。 在终端中键入此命令:

dmesg|grep ttyUSB*

它将打印出连接到所有 ttyUSB 的所有设备。 在我的例子中,结果是:

[ 5072.316991] usb 3-1: ch341-uart converter now attached to ttyUSB0

如果连接的设备更多,结果会列出 ttyUSB1/2..等等

如果您断开设备,运行终端中的相同命令将显示断开消息:

dmesg|grep ttyUSB*

[ 5361.353142] ch341-uart ttyUSB0: ch341-uart converter now disconnected from ttyUSB0