Page 1 of 1

Accessing Serial ports in Python

PostPosted: Tue Apr 27, 2010 11:04 am
by kakanakov
About using the termios package, initializing com ports, changing port attributes, sending and receiving data.

Re: Accessing Serial ports in Python

PostPosted: Mon Jan 17, 2011 5:49 pm
by Dimitar_Genov
The usage of the termios package is described as following:

import termios
serfd = '/com/0', os.O_RDWR | os.O_NONBLOCK)
print "port in use or invalid name"

print 'termios =', termios.tcgetattr( serfd)
old = termios.tcgetattr( serfd)
old[4] = 9600 #19200 # ispeed
old[5] = 9600 #19200 # ospeed
termios.tcsetattr(serfd, termios.TCSADRAIN, old)
print "port not accepting your settings ... "
print 'termios =', termios.tcgetattr( serfd)
os.close( serfd)
pass # ignore errors here

First file descriptor should be assigned as an argument of the function tcgetattr( serfd) which returns list containing port attributes.
In order to set some of the attributes of the descriptor we use the function tcsetattr(serfd, termios.TCSADRAIN, old). The second parameter defines how the attributes are changed. In this case TCSADRAIN changes the attributes after transmitting all queud output.

To send data to the descriptor this code could be used:

os.write(serfd, data)

For reading data the following is used:, data)

Besides termios package there is another package called serial. Here it is an example:

import serial
ser_port = serial.Serial(0) # open first serial port
print ser_port.portstr # check the name of the port in use
ser_port.write("hello") # write data #read 5 symbols
ser.close() #close the port

For more information about the python package termios and serial: