Python Serial Tutorial

Install Python serial

Assumes Python has already been installed. This tutorial uses Python 2.7.12 and was created for Windows OS - in this case Windows 7. Download Python serial from https://github.com/pyserial/pyserial Extract the downloaded files and then from the command prompt cd into the extracted folder where setup.py is and enter the command:

python setup.py install

This will install python serial. To check that it has installed properly a python serial command listing the com ports can be entered

python -m serial.tools.list_ports - this will list the available serial ports

Arduino test sketch

An arduino test sketch is shown below. The wiper of a potentiometer is connected to Arduino A0 pin with the other potentiometer terminals separately connected to 5V and GND. The sketch reads in the voltage on A0 and sends it along with sample time to the PC over the serial link. Ths data will then be used to test how the serial interface is handled using the python serial library.

Python Code

The main Python Serial functions deal with setting up the computer's com port and the serial read and write operations. To set up the serial port on Windows OS the Python script imports the serial library and configures the particluar serial port. To do this, at the start of the Python script insert the code:

import serial

- and then initialising the com ports by including the following code:

ser = serial.Serial('COM3',9600) - Note the com port and baud rate will be setup to match the particular computer's com port settings.


An example code snippet to allow a write over the serial interface is shown below. In this example the variable sample time is an integer which is then converted to a string and concatenated with a carriage return and line feed symbols prior to be sent over the serial link

ser.write(str(sampletime).encode('ascii')+'\r\n')


The code for a serial read is shown below but in order to check there is serial data available the in_waiting function can be used. This is a non-blocking function that returns the number of bytes in the serial buffer. Once bytes have been detected the serial information can be read with the redline command:

if (ser.in_waiting > 0):

value = ser.readline()

The code listing for a simple Python serial script is shown below. This requires the previously mentioned Arduino sketch to be loaded to an Arduino board and the serial port within the Python script configured to match that used by the Arduino. The Arduino code reads in an analogue voltage on pin A0 and sends the ADC count over the serial interface to the computer. The time between samples is configured by the user by writing an integer value to the Arduino. Both the sample time and the ADC count are sent by the Arduino to the computer. The sketch and Python script can be downloaded at the end of this page.

Downloads