Reputation: 77
I have written the following bit of code to test various baud rates of a serial connection to a router. Essentially, bit-banging until I hopefully find the write one.
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)
The result when running this script is the first baud rate is tested and returns output from the remote side. When the next baud rate is tested, an Input/Output execution is raised. I have combed through the pyserial documentation and do not believe I am doing anything wrong. Is there a different method I should look at to close the serial connection before moving onto the next one?
Here is the output:
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
Upvotes: 2
Views: 2119
Reputation: 1762
I run your code succeed. But you can try this:
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()
Upvotes: 2