我正在尝试编写一个 python 程序,它可以使用 PySerial 模块通过串行接口(interface)进行通信,如下所示:
import serial
if __name__ == '__main__':
port = "/dev/tnt0"
ser = serial.Serial(port, 38400)
print ser.name
print ser.isOpen()
x = ser.write('hello')
ser.close()
print "Done!"
但是如果我执行上面的命令,我会得到以下错误:
/dev/tnt0
True
Traceback (most recent call last):
File "/home/root/nested/test.py", line 15, in <module>
x = ser.write('hello')
File "/usr/local/lib/python2.7/dist-packages/serial/serialposix.py", line 518, in write
raise SerialException('write failed: %s' % (v,))
serial.serialutil.SerialException: write failed: [Errno 22] Invalid argument
我引用了 pyserial 文档,根据该文档,这应该可以正常工作。请让我知道我在这方面做错了什么。
TIA!
最佳答案
由于某些原因,为了使用模块tty0tty
,您需要同时打开/dev/tnt0
和/dev/tnt1
,或任何其他对(例如 /dev/tnt2
和 /dev/tnt3
)。
下面的代码有效:
import time
import serial
def main():
vserial0 = serial.Serial(port='/dev/tnt0', baudrate=9600, bytesize=8, parity=serial.PARITY_EVEN, stopbits=1)
vserial1 = serial.Serial(port='/dev/tnt1', baudrate=9600, bytesize=8, parity=serial.PARITY_EVEN, stopbits=1)
n_bytes = 0
while n_bytes == 0:
vserial0.write('test')
n_bytes = vserial1.inWaiting()
time.sleep(0.05)
print vserial1.read(n_bytes)
if __name__ == '__main__':
main()
关于python - PySerial 客户端无法写入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30999468/