Reputation: 4578
I have a device (GT511C3 fingerprint scanner) that I am connecting to Raspberry Pi and programming it using Python Serial module. The GT511 device has a default baud rate of 9600, and there is capability of changing the it. Once you change the GT511 baudrate, it keeps this setting until next restart.
The question is if there is a way for me to check the current baud rate of the connected device (in case the device was already programmed, and connected by a different host). I know it is possible to do it using stty
:
$> stty < /dev/ttyAMA0
speed 57600 bud; line = 0
...
Is there a way to do it using Python serial or any other module, or do I have to write an iterative checking procedure to find it out?
UPDATE 1: Current solution I use to find the accepted baud rate:
ser = serial.Serial('/dev/ttyAMA0')
ser.timeout = 0.5
for baudrate in ser.BAUDRATES:
if 9600 <= baudrate <= 115200:
ser.baudrate = baudrate
ser.write(packet)
resp = ser.read()
if resp != '':
break
if ser.baudrate > 115200:
raise RuntimeError("Couldn't find appropriate baud rate!")
UPDATE 2:
Please, stop suggesting serial.baudrate
- this is NOT what I am asking.
Upvotes: 2
Views: 11078
Reputation: 23
Found your question while searching, and this is working great for me:
import serial
def baud_rate_test(serial_port, packet = b' '):
ser = serial.Serial(serial_port)
ser.timeout = 0.5
for baudrate in ser.BAUDRATES:
if 300 <= baudrate <= 57600:
ser.baudrate = baudrate
ser.write(packet)
resp = ser.readall()
if resp == packet:
return baudrate
return 'Unknown'
a = baud_rate_test('/dev/ttyUSB1')
print(a)
The devices I have checked it with to this point echo back the "b' '" with no issue. I do plan on testing it on more devices as time goes on, and I'm thinking I may need to change the "test packet" and the response criteria. The resp != '': line didn't work for me -- because different "weird" characters are returned at different baud rates.
Upvotes: 2
Reputation: 71
Maybe you shoul use stty
until you find a better alternative.
You can call it from Python code and parse the result to obtain what you need.
Here is a basic example (not tested):
import subprocess
import shlex
def get_baudrate(device):
command = 'stty < {0}'.format(device)
proc_retval = subprocess.check_output(shlex.split(command))
baudrate = int(proc_retval.split()[1])
return baudrate
Upvotes: 3