我编写了以下代码来测试与路由器串行连接的各种波特率。从本质上讲,直到有希望找到写一个的位置。
import serial
from time import sleep
baud_dict = [2400, 4800, 9600, 14400, 19200, 2800, 38400, 57600, 76800, 115200, 230400]
for baud_rate in baud_dict:
print("Trying baud rate of: " + str(baud_rate))
ser = serial.Serial('/dev/ttyUSB0', baud_rate, timeout=1)
print(ser)
ser.write('\r'.encode())
sleep(3)
read_val = ser.read(size=64)
ser.close()
print(read_val)
sleep(5)
运行此脚本时的结果是第一个波特率被测试并返回远程端的输出。测试下一个波特率时,会引发输入/输出执行。我已经梳理了pyserial文档,并且不相信我做错了什么。在进入下一个连接之前,我应该看一下不同的方法来关闭串行连接吗?
这是输出:
Trying baud rate of: 2400
Serial<id=0x7fb080c6f358, open=True>(port='/dev/ttyUSB0', baudrate=2400, bytesize=8, parity='N', stopbits=1, timeout=1, xonxoff=False, rtscts=False, dsrdtr=False)
b''
Trying baud rate of: 4800
Traceback (most recent call last):
File "bitbang.py", line 8, in <module>
ser = serial.Serial('/dev/ttyUSB0', baud_rate, timeout=1)
File "/home/kris/Desktop/serial_bitbang/lib/python3.5/site-packages/serial/serialutil.py", line 240, in __init__
self.open()
File "/home/kris/Desktop/serial_bitbang/lib/python3.5/site-packages/serial/serialposix.py", line 286, in open
self._update_dtr_state()
File "/home/kris/Desktop/serial_bitbang/lib/python3.5/site-packages/serial/serialposix.py", line 634, in _update_dtr_state
fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_DTR_str)
OSError: [Errno 5] Input/output error
答案 0 :(得分:0)
我运行您的代码成功。 但你可以试试这个:
import serial
from time import sleep
baud_dict = [2400, 4800, 9600, 14400, 19200, 2800, 38400, 57600, 76800, 115200, 230400]
ser = serial.Serial('/dev/ttyS0', timeout=1)
for baud_rate in baud_dict:
print("Trying baud rate of: " + str(baud_rate))
ser.baudrate = baud_rate
print(ser)
ser.write('\r'.encode())
sleep(3)
read_val = ser.read(size=64)
print(read_val)
sleep(5)
ser.close()