Serial Port Communication in Python

pyserial is a python module that allows one to access serial port. It’s easy to use and one can start test serial port communication in minutes.

1. Install pyserial

If your machine doesn’t have pyserial module installed, you can install the module using easy_install.

sudo easy_install pyserial

In case you don’t have easy_install installed, you can install it by entering the following command,

sudo apt-get install python-setuptools

Then you can run the command above to install pyserial.

2. A Sample Program

The sample program use pyserial to communicate with a modem device with its serial port interface at /dev/ttyUSB0 in Ubuntu Linux.

#!/usr/bin/python
import serial, time
#initialization and open the port
#possible timeout values:
#    1. None: wait forever, block call
#    2. 0: non-blocking mode, return immediately
#    3. x, x is bigger than 0, float allowed, timeout block call
ser = serial.Serial()
ser.port = "/dev/ttyUSB0"
#ser.port = "/dev/ttyS2"
ser.baudrate = 9600
ser.bytesize = serial.EIGHTBITS #number of bits per bytes
ser.parity = serial.PARITY_NONE #set parity check: no parity
ser.stopbits = serial.STOPBITS_ONE #number of stop bits
#ser.timeout = None          #block read
ser.timeout = 0             #non-block read
#ser.timeout = 2              #timeout block read
ser.xonxoff = False     #disable software flow control
ser.rtscts = False     #disable hardware (RTS/CTS) flow control
ser.dsrdtr = False       #disable hardware (DSR/DTR) flow control
ser.writeTimeout = 2     #timeout for write
try: 
    ser.open()
except Exception, e:
    print "error open serial port: " + str(e)
    exit()
if ser.isOpen():
    try:
        ser.flushInput() #flush input buffer, discarding all its contents
        ser.flushOutput()#flush output buffer, aborting current output 
                     #and discard all that is in buffer
        #write data
        ser.write("AT+CSQ=?x0D")
        print("write data: AT+CSQ=?x0D")
        time.sleep(0.5)  #give the serial port sometime to receive the data
        numOfLines = 0
        while True:
            response = ser.readline()
            print("read data: " + response)
            numOfLines = numOfLines + 1
            if (numOfLines >= 5):
                break
        ser.close()
    except Exception, e1:
        print "error communicating...: " + str(e1)
else:
    print "cannot open serial port "

 

The program send out AT commands to query modem signal strength. If you want to know more about modem AT commands, refer to post here.

If you set the timeout as 2, the readline() method is blocking call with timeout, the output will be as below,

write data: AT+CSQ=?
read data: AT+CSQ=?

read data: +CSQ: (0-31,99),(99)

read data: 

read data: OK

read data: 

If you set the timeout as None, the readline() method is non-blocking call, the output is,

write data: AT+CSQ=?
read data: AT+CSQ=?

read data: +CSQ: (0-31,99),(99)

read data: 

read data: OK


Note that there is less lines of output, program hangs and cannot exit.

If you set the timeout as 0, the readline() method will return immediately, the output is,

write data: AT+CSQ=?
read data: AT+CSQ=?

read data: +CSQ: (0-31,99),(99)

read data: 

read data: OK

read data: 

 

Reference:

pyserial documentation: http://pyserial.sourceforge.net/pyserial.html

0 thoughts on “Serial Port Communication in Python”

  1. Thanks a lot for your post! I m working with a similar solution but with Nagios calling the serial port.

    Implementing Exception on my serial port help me to find out that I had a [Errno 13] Permission denied error.

    My code was working well with the python shell but not in Nagios. All I had to do is to add the nagios user in the dialout group.

Leave a Reply

Your email address will not be published. Required fields are marked *