Serial port programming in Python is done using a module called ‘serial’. A few basics of serial port programming is listed below:

How to open a port:

First we have to import the module ‘serial’. Create an instance of class ‘Serial’ of the module ‘serial’.

>>> import serial

>>> ser = serial.Serial(0)

This will open port number 0. To write into the port we can simply use ‘ser.write()’.

>>> ser.write(“hello”)

We have not set any value to the port. We can set them manually. Default values are:

port – /dev/ttyS0

baudrate – 9600

byte size – 8

parity – None

stop bit – 1

Configuring the Port:

We can configure the port by adjusting the baudrate, byte size, parity etc.

>>> ser = serial.Serial()

>>> ser.baudrate = 19200

>>> ser.port = 0

Reading from a Port:

>>> x = #reads a byte

>>> s = #reads up to 100 bytes

>>> line = ser.readline() #reads up to the ‘\n’

We must be careful while using. Readline must be given a timeout. Otherwise the port can get blocked for ever if a new line character never appear. If we provide a timeout the port will close after that particular time interval.

Closing an Opened Port:

We can test whether a port is opened or closed.

>>> ser.isOpen() #returns true if then port is open else it will return false.

>>> ser.close() #closes an opened port


About Odol Shinu

I've completed my B Tech in Information Technology in 2010 from Government Engineering College Sreekrishnapuram Palakkad under Calicut University.

Posted on September 4, 2010, in Python. Bookmark the permalink. 2 Comments.

  1. default baud 9200 or 9600?

  2. its 9600…. it was a typing mistake

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: