Python Tutorial to serial programming

Python Tutorial

Edit Jan 29 2013: This site has gained some significant traffic, according to google. If you search “pyserial tutorial” this page is 3rd up. So hence I will edit and make it a bit more understandable, seems like there is actually a need for this!

This tutorial describes the process of connecting to a spectrometer over serial port, and writing a python program to automate collection of data. Normally we would need to enter in the wavelength and acquire the (transmittance/absorbency/concentration) result manually. Since the spectrometer has a serial port, we can write a program that automates this process. In order for python to be able to talk to the spectrometer, we need to get pySerial, which extends Python’s capabilities to include interacting with a serial port.

In this python tutorial, I will explain how to:

  1. How to configure Python and pySerial
  2. Verify serial port communication, with a spectrometer device
  3. Write some functioning code in Python and use the spectrometer

Part 1: Setup Python and pySerial

This part mostly involves installing Python and pySerial, which the latest versions can be downloaded from their respective google searches.

The installation process for both of these tools are relatively trivial. Especially Python.

For pySerial, you’re looking for a file that’s something like pyserial-2.6.tar.gz. That can be grabbed from here. So after you’ve downloaded and extracted the folder to C:\Python32\Lib\site-packages, go to the folder with cmd.exe to where setup.py is located, and type python setup.py install. That’s it. If I manage to lose you on the way, see their official documentation here.

My spectrometer setup
My spectrometer setup

Part 2: Communicating with your device via serial port.

Obviously I’m assuming you have some sort of a USB to serial device, or a serial port built in. The USB to serial device I used was from Texas Instrument, and it requires their proprietary driver to setup. I’ll assume you can figure the driver installation part on your own.

Now you need to know two things:

  1. What kind of commands your serial device supports. This depends on what device you’re using, so I’ll assume you can find proper documentation – for something among the line of a bunch of commands and their operands. Oh and make sure you know what the baud rate is! Otherwise you can’t establish communication no matter what.
  2. What kind of API calls can accomplish that.  All the API interface documentation for pySerial can be located here.

Now we need verify communication works. I will post one code example from my programming below, in part 3. It is what I used to verify that my setup works correctly. There is additional code examples here on the official pySerial documentation page.

Part 3: Code in Python

Picture of my python develop environment in eclipse.

This code is not available on my github. I was not using version control when I developed this. Though I should have. I will do a step by step analysis of my code and guide you through what each part is doing. This is the code I have written (with thanks to Christophe Biocca for his help!):

## API calls ##
import serial
import io
import time
## Creates an object, Spectrometer ##
class Spectrometer():
# Parameters
baud = 1200
byte = 17 # 17 bytes ## potential problem here##
def __init__( self, port = 2 ):
self.port = port
self.isOpen = False
return
## Open and initize the serial port ##
def start( self ):
if not self.isOpen :
self.ser = serial.Serial()
self.ser.baudrate = self.baud
self.ser.port = self.port
self.ser.timeout = 2
self.ser.open()
print( "Opened port." )
self.sio = io.TextIOWrapper( io.BufferedRWPair( self.ser, self.ser ) ) # TextWrapper
self.isOpen = True
return
# Loop readings to a list
def aquire ( self, start, jump, end, progress = None ):
try:
print( "{0} to {1} with jump {2}".format ( start, jump, end ) )
result = []
self.w( "GTO {0}".format( start ) )
time.sleep( 4 )
for wavelength in range( start, end + jump, jump ):
current_pos = ( wavelength - start ) / ( end - start )
if progress:
progress.set( current_pos )
command = "GTO {0}".format( wavelength )
self.w( command )
self.w( "SND" )
output = self.r( 17 )
while output == b"":
self.w( "SND" )
output = self.r( 17 )
result.append( output.decode( 'ascii' ).strip().split( ' ' ) )
print()
self.w( "BEP" )
finally:
self.close()
return result
## Write ##
def w( self, command ):
self.start()
time.sleep( 0.1 )
self.sio.write( command + str( "\n" ) )
self.sio.flush()
print( "{0:10}{1}".format( "Sent:", command ) )
return
## Read ##
def r( self, byte ):
self.start()
read = self.ser.read( byte )
print( "{0:10}{1}".format( "Read:", read ) )
return read
## Helper function for make_reading to call the wavelength ##
def measure ( self, wavelength ):
command = "GTO " + str( wavelength )
self.w( command )
string = self.r( 17 )
return string
## Unused. Spectrometer has mode of Absorbance, Concentration, Transmittance. ##
def set_mode( self, mode ):
self.w( mode )
return
## Close the serial port ##
def close( self ):
self.ser.close()
self.isOpen = False
print( "Closed port." )
return

This is more or less the main object code that you’d need to interact with a spectrometer and all its functions. Very poorly documented, I apologize. Anyhow, hopefully you see enough from this Python and pySerial tutorial to get started.

Oh and by the way, I wrote a GUI with TKInter that simply is a box which prompts the user for a starting, jump amount, and ending wavelength. Actual range is 350 to 900 nm. I won’t be posting this code for sake of relevancy to the topic on hand.

But here’s what the simple interface looks like:

 

It also outputs the measurements to a CSV file which can then be imported to a data analysis software package like Excel or R to analyze.

Thank you for reading and I hope you have found it useful.

Jason Sun

6 thoughts on “Python Tutorial to serial programming”

  1. i want to do serial communication between a device, which the code has written in Embedded c.This device is a master. Now i am taking Raspberry pi as a slave with python installed in this raspberry pi. Now i want the serial communication to be done between these two devices (master with embedded c programing and slave as raspberrypi with python programing). here the master will display some data on the screen, and that data should be replicated on the slave by serial communication.
    plz help me out to write a code for serial communication.
    Thanks in advance.

  2. – in RS232 there is no master and slave(i2c has)
    -you can use any microcontroller(pic18f2550 i use),you can program ic with embedded c or assembely language(i use)
    -set both devices baud rate, and all the rs232 protocol parameter same.
    -you can program raspberrypi with python serial
    if you have any question plesae mail me

    Thanking you
    learn new,live strong

  3. Hi,

    Great tutorial indeed! I am personally using PyVISA for communicating with a spectrum analyzer through GPIB-over-ethernet.

    I was wondering if there is a way to create a GUI over which the spectrum can be seen. This will totally remove any necessity of being near the instrument while collecting data.

    If you have any ideas, do let me know.

Leave a Reply

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