Skip to content

Instantly share code, notes, and snippets.

@jboecker
Created March 10, 2019 15:54
Show Gist options
  • Save jboecker/969b085533cbd705f378322fa27e80c2 to your computer and use it in GitHub Desktop.
Save jboecker/969b085533cbd705f378322fa27e80c2 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
# set nonstandard baudrate.
# based on http://unix.stackexchange.com/a/327366/119298
# this version takes the device file and baudrate as arguments
# and prints an error message if the device file could not be opened.
import sys,os,array,fcntl,argparse
parser = argparse.ArgumentParser()
parser.add_argument("device", metavar="DEVICE", type=str, help="the serial device (e.g. /dev/ttyUSB0 or /dev/ttyACM0)")
parser.add_argument("bps", metavar="BITS_PER_SECOND", type=int, help="speed in bits per second, e.g. 9600 or 250000")
args = parser.parse_args(sys.argv[1:])
# from /usr/lib/python2.7/site-packages/serial/serialposix.py
# /usr/include/asm-generic/termbits.h for struct termios2
# [2]c_cflag [9]c_ispeed [10]c_ospeed
def set_special_baudrate(fd, baudrate):
TCGETS2 = 0x802C542A
TCSETS2 = 0x402C542B
BOTHER = 0o010000
CBAUD = 0o010017
buf = array.array('i', [0] * 64) # is 44 really
fcntl.ioctl(fd, TCGETS2, buf)
buf[2] &= ~CBAUD
buf[2] |= BOTHER
buf[9] = buf[10] = baudrate
assert(fcntl.ioctl(fd, TCSETS2, buf)==0)
fcntl.ioctl(fd, TCGETS2, buf)
if buf[9]!=baudrate or buf[10]!=baudrate:
print("failed. speed is %d %d" % (buf[9],buf[10]))
sys.exit(1)
try:
with open(args.device) as f:
set_special_baudrate(f.fileno(), args.bps)
except IOError as e:
sys.stderr.write("could not open %s: error %d: %s\n" % (e.filename, e.errno, e.strerror))
sys.exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment