Cross Platform serial communication using Python (PySerial)

Pinterest icon

Tutorial on programming the serial port using python and pyserial on Linux,windows and mac os X

Python is an open source, cross platform ,interpreted language that is easy to learn for beginners. One of the many advantages of Python is the sheer number of contributed modules for performing a wide variety of tasks.

One problem with developing code that uses serial port is portability, you can't use the same code in both Windows and Linux. For each operating system (Windows/Linux) you have to write custom codes using the native API's as we have done here and here.

Python provides an easy way to do cross platform serial communication using pySerial module. The modules hides all the OS specific peculiarities and presents a uniform simple interface for programming the serial port. The code written with pySerial can run unmodified on Windows and Linux systems

As of writing this tutorial there are two versions of Python in use, Python 2.7 and Python 3.0. pySerial is available for both 2.7 version as well as 3.0 version.

Sourcecodes

link to xanthium enterprises repo on Github containing code for cross platform serial communication using Python and Pyserial  

All the Python source files used in this tutorial can be downloaded from our GitHub Page.Both Python 2.7.x and Python 3.x.x version codes (Windows/Linux) are available in the Repo.

If you are new to Github or want to download the code in a Ziped Format, Please ​Check this short tutorial .

 

Hardware Used 

Buy USB to RS485 converter online from here   Buy USB to RS485 converter online from here (made in India )

USB2SERIAL - Any easy to use multi protocol converter that can convert from USB to RS485/RS232/Serial.The Board comes with selectable voltage levels for interfacing with 5V and 3.3V logic families.

Python in Windows

In Windows, Python is not installed by default, you can find python binary installers from either python.org or from ActiveState software.Here I am using Community edition of Active Python (Python3.0) from Active State Software. Just download the executable and install the software on your Windows PC.

After completing the installation you can type “python” on your command prompt to enter the python shell. (use CTRL + Z to exit from the shell).

python 3.0 running on windows7

or use GUI based shell IDLE.

python IDLE running on windows 7

Installing PySerial on Windows 

After you have installed the python interpreter, You can install PySerial using pip installer.Earlier Pyserial Homepage used to provide Windows Executable file which can be installed using point and click method .Now they are providing source and wheels package only.

Here we will be installing the PySerial Package using pip installer.So open up your Windows Command prompt and type in the following command.

C:\ python -m pip install pyserial

as shown below 

installing pyserial using pip on Windows 7
After installing pySerial, open the python shell and type “import serial”.

If you are not getting any error messages, pySerial is installed properly.

Python on Linux
On most Linux distro's python is installed by default(usually python2.7). Here I am using Ubuntu 14.04 LTS version and pySerial is installed by default in my system.

pyserial in ubuntu/linux python interpretor

Writing to Serial Port

Now lets open a serial port and write some values to it. The code in python is quite straight forward, you can just read it like plain English. Open a text editor and type the following lines of code into it .Save the file with a ” .py” extension like “Serial_Write_Win32.py”.The Below code writes character 'A' to the serial port.

import serial           # import the module
ComPort = serial.Serial('COM24') # open COM24
ComPort.baudrate = 9600 # set Baud rate to 9600
ComPort.bytesize = 8    # Number of data bits = 8
ComPort.parity   = 'N'  # No parity
ComPort.stopbits = 1    # Number of Stop bits = 1
# Write character 'A' to serial port
data = bytearray(b'A')
No = ComPort.write(data)

ComPort.close()         # Close the Com port

Please note that this code will work with both Python 2.7 and Python 3.0

The first line import serial imports the pySerial module so that your program can use it.

ComPort = serial.Serial('COM24') opens the serial port named COM24.

In Windows,
Please give the COM number corresponding to your Serial port or USB to Serial Converter instead of COM24.

finding the COM port number in windows

In Linux,
In Linux there is no concept of COM number, instead the serial ports are numbered as ttyS0,ttyS1 etc and USB to Serial Converters as ttyUSB0,ttyUSB1 etc. You can know more about finding the serial port number here.

For USB to Serial converters like USB2SERIAL, You can connect them to your USB port and issue a “ dmesg | tail” command at the terminal.

finding out the serial port number for usb to serial converters in Linux

So in Linux change the second line to

ComPort = serial.Serial('/dev/ttyUSB0')#USB to Serial
or
ComPort = serial.Serial('/dev/ttyS0')#Hardware Serial port

After the connection to the port is opened, the character A is transmitted by the serial port.The character array is first converted to individual bytes by the bytearray() function

data = bytearray(b'A')

and then transmitted using

No = ComPort.write(data))

Directly transmitting the Character A like this ComPort.write('A') is creating errors in Python 3.0.

Running the Code

In Windows,
You can either run the code from command line,

running the python serial communication code on windows 7

or by using IDLE
From IDLE use “File → Open” to open your code file and from “Run → Run Module”.

using IDLE to run python serial communication programs on windows

In Linux,
For accessing the Serial port you should have super user/root access.In linux open up a terminal and type

sudo python Serial_Write_Linux.py

running a python script to communicate with serial port as root using sudo

give the password and you are done.Before running the python script make sure that you have connected your USB to Serial Converter and correctly identified the name of the concerned port. You can check this article for finding out the name of your serial port.

Connecting a Micro controller to your PC 's Serial port
For an embedded system developer serial ports are the easiest and most versatile interface to program. Most PC's nowadays lack a traditional RS232 based serial ports but this small problem can be easily solved by using a variety of USB to Serial converters available in the market.Some of them like USB2SERIAL can also be used to do USB to RS485 conversion,so that you can hook up your PC to a remote sensor or robot.

Some times you want to hook your microcontroller based data logger serially to your PC so that you can log the data and present it on an excel sheet.In this example I will show you how to hook up a microcontroller to PC using a USB to Serial converter like FT232.

Here I am using a MSP430 controller (MSP430G2553) that is connected to the PC via a USB to Serial Converter(USB2SERIAL).The Controller is connected to the FT232's Serial port using a null modem cable as shown in the below figure.You can also check this short tutorial on how to configure MSP430 UART.

block diagram showing connection between MSP430 UART and PC serial port or USB to serial converter

Here the TXD of the serial port is connected to the RXD of the microcontroller UART and vice versa. Ground lines are made common to both PC and microcontroller.

null modem connection between msp430 launchpad and usb2serial

 

msp430 interfaced with PC using a FT232 usb to serial converter
If you run “Serial_Write_Win32.py”  file or the Linux version “Serial_Write_Linux.py” the PC will send a character to MSP430.The code and  the IAR workspace for microcontroller are in the zip file. 

Reading from Serial port
In this section we will send a string of text from the microcontroller to the PC via the serial link. The Python script running on the computer will read and display it on console .
Please note that this code will work with both Python 2.7 and Python 3.0.

Here is the script for reading.

import serial                    # import pySerial module
ComPort = serial.Serial('COM24') # open the COM Port
ComPort.baudrate = 9600          # set Baud rate
ComPort.bytesize = 8             # Number of data bits = 8
ComPort.parity   = 'N'           # No parity
ComPort.stopbits = 1             # Number of Stop bits = 1
data = ComPort.readline()        # Wait and read data
print(data)                      # print the received data
ComPort.close()                  # Close the COM Port

in Linux
change the second line to either

ComPort = serial.Serial('/dev/ttyUSB0')#USB to Serial

or
ComPort = serial.Serial('/dev/ttyS0')#Hardware Serial port

assuming that ttyUSB0 is the name of your USB to Serial Converter or ttyS0 is the name of your hardware serial port.

The script opens a connection to the serial port and configures the baud rate, data format, no of start /stop bits and parity. It then waits at the line

data = ComPort.readline()

for the string send from the connected microcontroller(here MSP430).

python script waiting for data to be transmitted by MSP430 micro controller

On receiving the string, print() displays the string on the terminal/command line and the port is closed.

python script displaying the string received by PC serial port from MSP430

Controlling RTS and DTR Pins in Python

RTS and DTR pins can be controlled by using setRTS() and setDTR() functions available in the pySerial module. The functions can be used to SET and CLEAR the RTS and DTR pins.

Here is a code snippet illustrating the use of setRTS() function.

import serial                    # import pySerial module
ComPort = serial.Serial('COM25') # open the COM Port

ComPort.setRTS(0)                # Make RTS pin low
#put some delay, or ask for input

ComPort.setRTS(1)                # Make RTS pin high

ComPort.setDTR(0)                # Make DTR pin low
#put some delay, or ask for input
ComPort.setDTR(1)                # Make DTR pin high

ComPort.close()                  # Close the COM Port

in Linux,change the second line to either

ComPort = serial.Serial('/dev/ttyUSB0')#USB to Serial
or
ComPort = serial.Serial('/dev/ttyS0')#Hardware Serial port

assuming that ttyUSB0 is the name of your USB to Serial Converter or ttyS0 is the name of your hardware serial port.

Between ComPort.setRTS(0) and ComPort.setRTS(1) put some delay or ask the user to press any key to continue, other wise you may not be able to see the change in pin status.

Like this for Python 3.0

ComPort.setRTS(0) # Make RTS pin low
input('Press any Key to continue')
ComPort.setRTS(1) # Make RTS pin high

or Like this for Python 2.7

ComPort.setRTS(0) # Make RTS pin low
raw_input('Press any Key to continue')
ComPort.setRTS(1) # Make RTS pin high

in order to control the DTR pin you can replace ComPort.setRTS() with ComPort.setDTR().

Screen shot on Windows system which uses Python 3.0

pyserial python code for controlling the RTS and DTR pins of PC serial port running on Windows 7

Screen shot on Ubuntu which uses Python 2.7

pyserial python code for controlling the RTS and DTR pins of PC serial port running on Linux (ubuntu/mint linux)

If you are using a FT232 based USB to Serial Converter like USB2SERIAL,the RTS and DTR pins are inverted internally. So setting the RTS/DTR pin would make it low and vice versa.

Photo of USB2SERIAL connected to LED's through 1K resistors.Ground is taken from USB2SERIAL connector (P4)

python code controlling RTS and DTR pins of FT232 serial port

One use of controlling the DTR and RTS pin is to create a USB to RS485 network converter for controlling a remote sensor or robot.

 

Back to Serial Programming Tutorials 

 

 

Comments

Thnak you for providing source codes. I have just started learning python and I feel very difficulties in devoloping a code. Colud you please give some advise or reference?

Presently, I works for custom essay writing service.