Pyserial 不能很好地与虚拟端口配合使用

2024-03-31

动机

我想开始学习如何使用python库Pyserial https://github.com/pyserial/pyserial。这似乎是一个非常好的图书馆,适合很多人。我想将它用于即将进行的项目,在该项目中我必须自动化串行通信。

环境

我运行的是 Ubuntu 15.04。我正在使用Python 2.7。

设置虚拟端口

我目前没有可以通过串行端口进行通信的设备。我正在使用socat http://www.dest-unreach.org/socat/应用程序创建两个以 9600 波特率相互连接的虚拟端口。

$ socat -d -d pty,raw,echo=0,b9600 pty,raw,echo=0,b9600
2016/01/16 12:57:51 socat[18255] N PTY is /dev/pts/2
2016/01/16 12:57:51 socat[18255] N PTY is /dev/pts/4
2016/01/16 12:57:51 socat[18255] N starting data transfer loop with FDs [5,5] and [7,7]
$ echo "hello" > /dev/pts/2
$ cat /dev/pts/4
hello

伟大的!看来端口工作正常!

一个简单的pyserial脚本

我使用 pip 安装 pyserial

$ sudo pip install pyserial

然后我写了一些serialtest.py

#!/usr/bin/env python
import serial

ser = serial.Serial('/dev/pts/2', 9600)

这就是整个serialtest.py

运行脚本并遇到错误

$ python serialtest.py 
Traceback (most recent call last):
  File "serialtest.py", line 4, in <module>
    ser = serial.Serial('/dev/pts/2')
  File "/home/sbl/.local/lib/python2.7/site-packages/serial/serialutil.py", line 180, in __init__
    self.open()
  File "/home/sbl/.local/lib/python2.7/site-packages/serial/serialposix.py", line 311, in open
    self._update_dtr_state()
  File "/home/sbl/.local/lib/python2.7/site-packages/serial/serialposix.py", line 605, in _update_dtr_state
    fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_DTR_str)
IOError: [Errno 22] Invalid argument

那是怎么回事?

尝试调试失败

This guy https://stackoverflow.com/a/5498780/1113637说他在使用python 2.6时取得了成功。我无法让 Pyserial 与 2.6 一起工作。

This guy https://github.com/foosel/OctoPrint/issues/230波特率有问题。我用命令仔细检查我的波特率$stty -F /dev/pts/2并确认它的波特率实际上是 9600。

This guy https://github.com/daid/Cura/issues/20还声称波特率有问题并将其归因于他的内核。那是2012年的事了,所以我认为它不再相关了。

我的问题

如何让我的serialtest.py脚本运行而不出错?


为了使此问答完整,这是一个解决方案(如 Austin Philips 的链接中所示):

#!/usr/bin/env python
import serial

ser = serial.Serial('/dev/pts/2', 9600, rtscts=True,dsrdtr=True)

看到这个PySerial Github 问题 https://github.com/pyserial/pyserial/issues/59以获得更多解释。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Pyserial 不能很好地与虚拟端口配合使用 的相关文章

随机推荐