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
kakanakov
 
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
try:
serfd = os.open( '/com/0', os.O_RDWR | os.O_NONBLOCK)
except:
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
try:
termios.tcsetattr(serfd, termios.TCSADRAIN, old)
except:
print "port not accepting your settings ... "
print 'termios =', termios.tcgetattr( serfd)
try:
os.close( serfd)
except:
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:

os.read(serfd, 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
ser_port.read(5) #read 5 symbols
ser.close() #close the port


For more information about the python package termios and serial:
http://docs.python.org/library/termios.html
http://pyserial.sourceforge.net/shortintro.html
Dimitar_Genov
 
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

cron