Python Serial Timeout Example

Open named port at “19200,8,N,1”, 1s timeout: with serial.Serial('/dev/ttyS1', 19200, timeout=1) as ser. X = ser.read # read one byte. S = ser.read(10) # read up to ten bytes (timeout). Line = ser.readline # read a ' ' terminated line. Open port at “38400,8,E,1”, non blocking HW handshaking. API¶ class periphery.Serial (devpath, baudrate, databits=8, parity='none', stopbits=1, xonxoff=False, rtscts=False) source ¶. Bases: object Instantiate a Serial object and open the tty device at the specified path with the specified baudrate, and the defaults of 8 data bits, no parity, 1 stop bit, no software flow control (xonxoff), and no hardware flow control (rtscts).

For anyone who would like to interface with their car, here is a guide to do so.


For this you need a few things:

Python Readline Timeout

Serial
  • A car supporting OBD2 (most cars since 1996 have this).
  • A laptop/computer running Python 2.7.3
  • An OBD connector (available online – I have an ELM327 bluetooth one which cost under €10)

So now that you have those, lets get started:

Connecting to the OBD2 connector:
Whether you are using a Bluetooth or USB OBD2 connection, it is a serial connection. To talk to it through python you can use pyserial.

You can list all serial ports on OSX or Linux by typing the following in the terminal:

ls /dev/tty*

(“ls” above is short for “list the following with file name” and the “/dev/tty” is the start of the file path of any serial port).

Python serial disable timeout

Take note of the serial device you are using – you will need it below.

  1. Download pyserial and install on your machine.
  2. Open the terminal (command prompt on Windows).
  3. Type python to start Python.
  4. Type import serial to make use of Pyserial
  5. Now connect to the serial device. To do this you will need the name of the serial device you are using (see above). Type the following: ser = serial.Serial('NAME_OF_SERIAL_DEVICE', 38400, timeout=1)
  6. Now you’ve connected to the OBD so you can start sending commands. For example, to measure speed type: ser.write('01 0D r') A full list of OBD commands can be obtained here.
  7. The elm327 device returns values in HEX. To read the value you just requested in Python type speed_hex = ser.readline().split(' ')
  8. Convert the HEX to decimal by using: speed = float(int('0x'+speed_hex[3], 0 ))
  9. Finally output to the screen: print 'Speed: ', speed, 'km/h'
Example

Now you should see the speed of your vehicle appear on screen.

Any issues/questions shout below in the comments and I will try to help out!

Python Serial Timeout Example

Python Serial Timeout Example Sheet

My next project is to get all of this onto a Raspberry Pi so I can monitor the car’s ECU on the go.