Pyserial与虚拟端口

时间:2016-01-16 19:24:25

标签: python serial-port pyserial socat virtual-serial-port

动机

我想开始学习如何使用python库Pyserial。它似乎是一个非常好的图书馆,适用于很多人。我想将它用于即将开展的项目,我必须自动进行串行通信。

环境

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

设置虚拟端口

我目前没有可以通过串口与之通信的设备。我正在使用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说他在使用python 2.6时取得了成功。我无法让Pyserial使用2.6。

This guy遇到麻烦是波特率。我用命令$stty -F /dev/pts/2仔细检查我的波特率,并确认它实际上是波特率为9600.

This guy也声称有波特率问题并将其归因于他的内核。那是在2012年,所以我认为它不再相关了。

我的问题

如何让我的serialtest.py脚本无误地运行?

2 个答案:

答案 0 :(得分:15)

要使此Q&amp; A完整,这是一个解决方案(如Austin Philips链接中所示):

#!/usr/bin/env python
import serial

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

有关详细说明,请参阅此PySerial Github issue

答案 1 :(得分:2)

根据Sebastian提到的问题,此问题自Pyserial 3.1版本开始解决。

this

  

zsquareplusc于5月29日发表评论

     

发布了3.1错误设置   open()中的控制行被忽略(但在以后的调用中不会被忽略)。

通过pip,github或下载页面进行更新:https://github.com/pyserial/pyserial/issues/59