Accessing Serial ports in Python

For projects on iDigi platform

Accessing Serial ports in Python

Postby kakanakov » Tue Apr 27, 2010 11:04 am

About using the termios package, initializing com ports, changing port attributes, sending and receiving data.
User avatar
Posts: 28
Joined: Fri Mar 06, 2009 4:36 pm
Location: Lab 2204a, campus 2, TU - Plovdiv

Re: Accessing Serial ports in Python

Postby Dimitar_Genov » Mon Jan 17, 2011 5:49 pm

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:
Posts: 1
Joined: Thu Apr 01, 2010 1:51 pm

Return to iDigi

Who is online

Users browsing this forum: No registered users and 1 guest