Serial RS232 connections in Python

Last updated on Sun, 2010-03-28 19:10. Originally submitted by fabio on 2008-05-08 14:18.

Here at ULPGC I'm following a Robotics course. In the practical part of the exam we have to write some applications to operating some didactics robots we have (Rhino XR-4 and SCARA Robots).

Each robot is connected to a Controller (Rhino Mark-4) which can be connected to a PC to send commands to the Controller in order to let the robots do things.

The PC to Controller connection is a serial RS-232 connection.

So.. for the practical parts of the exams we need to write applications which, using the RS-232 communication channels, controls the movements of the robots.

The professor here suggested to use Java to implement the applications: unfortunately I found the API comm pretty complex in installation and configuration.

So.. I looked for different solutions.

Surprisingly I found that Python with the pySerial module is a pretty intelligent solution!

I've been able to install and use them (in both Linux and Windows) without problems at all (while my classmates had lot of problems with java and comm apis...). Just follow any guide on the web to install Python on your system and then follow the pySerial installation guide.

Using the pySerial apis is pretty simple: just have a look at the project website to have an idea of the apis it gives you.

A simple application

I give you here a simple application which should let you understand how python serial apis are easy to use. The application is a simple serial terminal which you can use to send commands (and receive output) to a serial connected device.

This is the application code:

import time
import serial

# configure the serial connections (the parameters differs on the device you are connecting to)
ser = serial.Serial(
	port='/dev/ttyUSB1',
	baudrate=9600,
	parity=serial.PARITY_ODD,
	stopbits=serial.STOPBITS_TWO,
	bytesize=serial.SEVENBITS
)

ser.open()
ser.isOpen()

print 'Enter your commands below.\r\nInsert "exit" to leave the application.'

input=1
while 1 :
	# get keyboard input
	input = raw_input(">> ")
        # Python 3 users
        # input = input(">> ")
	if input == 'exit':
		ser.close()
		exit()
	else:
		# send the character to the device
		# (note that I happend a \r\n carriage return and line feed to the characters - this is requested by my device)
		ser.write(input + '\r\n')
		out = ''
		# let's wait one second before reading output (let's give device time to answer)
		time.sleep(1)
		while ser.inWaiting() > 0:
			out += ser.read(1)
			
		if out != '':
			print ">>" + out

NOTE for Python 3 users: The code above has been written for Python 2 and I'm no more able to test RS232 connections with Python 3. As some users commented below the raw_input() function has been removed so you should just use the new Python 3 function input(). If you use Python 3 and find other issues with the code please leave a comment. Thanks!

As you can see the code is pretty simple and self documenting. This should demonstrate you the power of this solution.

Really important is the serial port configuration: if you configure it incorrectly you probably will end in problems during communications (check the manual of the device you are connecting to get the correct connections parameters).

Also remember to point the port parameter to the device file you are using (under windows you can simply use COMMX, where X is the COMM instance number 1,2,3,4,etc. )

Conclusions

I consider Python and pySerial one of the simplest and faster ways to develop an application to use a serial connection.

You will also be able to use the huge amounts of other native apis and additional modules Python has to add all kind of features to you applications!

If you need a graphical interface I strongly encourage you to have a look at the pyGTK project and the Glade interface designer.

Posted in:

Pysthon serial and web page

Submitted by Anonymous (not verified) on Wed, 2013-08-07 14:12.

After a lot of trying I got this to working

#!c:\Python27\Python.exe
import sys, serial

sys.stderr = sys.stdout
ser = serial.Serial('COM27', 9600)
print "Content-type:text/html\n\n"
print "Real Time Temperature"
print "Real Time Temperature:"
print ""
print "%s" % (ser.readline())
print ""
#""" % ser.readline() # should be cgi.escape(ser.readline())!
ser.close()
sys.exit(0)

But this is refreshing the whole page. I want the latest value in my web page only.
Secondly using
print """
HTML CODE
"""

is giving me error 500 in my webpage (internal error) can you say why?

Send file between two modules

Submitted by lekaleka (not verified) on Thu, 2012-12-13 16:35.

Hi Fabio,
Thanks for this great script, that helped me really alot.
I sill have one question though; how can i stream or send files (images etc..) between two modules? I am using telegesis zigbee kit. And how do i prepare a transmitter (coordinator) and receiver (node)?

I would appreciate any help,

thanks in advance
lekaleka

Using your example, the port

Submitted by Anonymous (not verified) on Tue, 2012-09-25 00:21.

Using your example, the port was opened for communication. When I send some input commands, I get the same as output

The same port is opened twice !

Submitted by WinCrazy (not verified) on Thu, 2012-08-09 02:00.

The sample code shouldn't work because the same port is opened twice: first with [ ser = serial.Serial( port='/dev/ttyUSB1', ... ] then again with the statement [ ser.open() ].

i want to build a sms app

Submitted by Qaunsah Patrick (not verified) on Sat, 2012-06-09 18:00.

hi
am new to python and i want to build a sms app that can receive and send
feed back to user. I need a help to build my app
thanks

Knowing this is an old post,

Submitted by para hsu (not verified) on Sat, 2012-05-26 01:06.

Knowing this is an old post, but an useful tip:
We can use the 'cmd' module to implement a command line interface with many commands. Easy to use and fun ^_^

Sounds interesting, do you

Submitted by fabio on Sat, 2012-05-26 08:50.

Sounds interesting, do you have any link to docs/examples?

Impossibility to listen the device

Submitted by Olivier (not verified) on Fri, 2012-05-04 14:45.

Hello,
Thank you for your handy topic, it helps me to create a conection between my computer and a AC/DC alimentation.
One of your function doesn't work with my programm. I can't catch message/error from my device.
ser.inWaiting() always return 0.
Is there a way to configure the parameters of the device output register ?
Thanks for your help.

Olivier.

The problem is solved. My

Submitted by Olivier (not verified) on Thu, 2012-05-10 13:06.

The problem is solved. My device can communicate with me if i ask specific question. But it don't send automaticaly error message througt the RS232 connection.

Thanx.

Help needed in Sms sending in Python 2.6

Submitted by Salina (not verified) on Wed, 2012-04-11 06:32.

hello. i am also working in python 2.6 and i want to send SMS to a mobile while my cell phone i.e. Nokia E-72 is connected to PC via Data Cable. the mobile is connected through the serial port and the code prompts the correct port as well and there is no error in the code but still the message is not being sent... please help me.
My code is as follows:

import serial
import time

phone = serial.Serial()
phone.baudrate = 38400
phone.bytesize = 8
phone.stopbits = 1
phone.xonxoff = 0
phone.rtscts = 0
phone.timeout = 0
phone.port = 4 #try different ports here, if this doesn't work.
phone.parity=serial.PARITY_NONE
phone.open()
print phone.portstr

recipient = "+923219409998"

message = "We did it!"
try:
time.sleep(0.5)
phone.write(b'ATZ\r')
time.sleep(0.5)

phone.write(b'AT+CMGF=1\r')
time.sleep(0.5)
phone.write(b'AT+CMGS="' + recipient.encode() + b'"\r')
time.sleep(0.5)
phone.write(message.encode() + b"\r")
time.sleep(0.5)
phone.write(bytes([26]))
time.sleep(0.5)
phone.readall()

# print phone.readall(str)

finally:
phone.close()

Python

Submitted by Rain (not verified) on Sat, 2010-07-24 17:13.

It was very clever of you to use python. I like it a lot. It is quite simple. When I learned it tthis book helped me a lot: http://www.pdfok.com/watch/Python-Programming-on-Win32.pdf-20458046.html . You can download it from here. Well, whenever I had any question I always look in it for the answer. I'm sure it can be of some help to you too.

NO it doesn't work.

Submitted by Michael Jackson (not verified) on Fri, 2010-02-19 18:32.

I downloaded the latest and the greatest pyserial and pywin32 for windows. I installed and re-installed. Nothing is working for me. Every time I go to install, pywin32 complains that it can't find the right version, when in fact I verified that the correct version is installed.

Every time I compile my code with
import serial

I get importerror: module named serialwin32 not found....

any idea.....

The last version of pywin32 extension I can find is 2.6

Any idea?

Thanks for your help.

I'm not that experienced on

Submitted by fabio on Sat, 2010-02-20 12:52.

I'm not that experienced on the Windows version of pyserial.. You should ask for help to the pyserial developers by submitting a support request at http://sourceforge.net/projects/pyserial/support

Found solution to my program PySerial

Submitted by Michael Jacksin (not verified) on Thu, 2010-02-25 14:47.

All of my problems with PySerial has to do with the release candidate of pyserial-2.5-rc2.win32.exe, which is supposed to be the recent release. This file definitely has problem locating the installed python and thus never lets you run it. Apparently, you need to run this or you can't do crap with serial communication. Well, I downloaded previous version of this file - pyserial-py3k-2.5-rc1.win32.exe - and it works. It must have registered all the files. Now, I can open my serial ports.

I am using Python 3.1.1 on Windows XP with Pyserial 2.5.

It took me all day. Finally!!!

Cool dude. Thanks for sharing

Submitted by fabio on Thu, 2010-02-25 17:18.

Cool dude. Thanks for sharing the informations!

You might also want to try using python on a linux distribution. You could try using it on Ubuntu for example. Using python under Linux is usually really easier as it is its best environment.

I like Linux too.

Submitted by Michael Jackson (not verified) on Thu, 2010-02-25 20:56.

My Python effort is really for my work. We are currently looking to migrate our system using completely different
programming language that we can run on many different platform. I already migrated the system from Windows to Linux using Lazarus compiler. It runs on Fedora, Mandriva, Linux Mint and others. We have been hearing a lot of great things about Python programming language. So, we want to see if we can migrate the system using Python to different platforms easily. So far, based on my effort it is going to take very long time compared to Lazarus complier. :)

By the way, I am dual booting Linux Mint at home. :)

raw_input()

Submitted by Michael Jackson (not verified) on Thu, 2010-02-25 21:00.

I meant to ask you in the last reply. Where is the raw_input function defined? I try to run your example and it complained about it. if it is something you wrote, could you please email it to me or simply reply to this message with the definition. Thank you.

raw_input replaced in Python3

Submitted by Danny Milosavljevic (not verified) on Sat, 2010-03-27 09:25.

Hi,

Python3 is a new major distribution. Most programmers are used to Python2.

In Python3, "raw_input2 has been removed. "input" still exists (and exists in both Python2 and Python3):

http://www.wellho.net/resources/ex.php4?item=y300/input_3.py

Thanks for your contribution!

Submitted by fabio on Sun, 2010-03-28 19:02.

Thanks for your contribution! I didn't know about the raw_input() removing in Python 3.. Actually I'm still using Python 2.6 here.. but I'll soon have to study some Python 3 new stuff!

Thanks again!

That's a Python built-in

Submitted by fabio on Fri, 2010-02-26 12:53.

That's a Python built-in function:
http://docs.python.org/library/functions.html#raw_input

I don't have an idea on why you are having problems with it..

AT commands with PySerial

Submitted by Anonymous (not verified) on Wed, 2009-12-30 20:12.

Hi everybody!

I am with a problem when I trying to communicate a bluetooth device using Pyserial and AT commands. I can´t connect a bluetooth device with serial module from Python, my script is very simple and it works directly on hyperterminal by windows. I posted my code below if someone has any hit I would appreciate. Thanks in advance.

import serial
ser = serial.Serial(2) # open first serial port
print ser
print ser.portstr # check which port was really used
ser.write("atd000195079CEA\n\r") # write a string

ser.write("123test")

\r\n, not \n\r

Submitted by Cameron Kerr (not verified) on Thu, 2010-04-01 23:05.

You're ser.write has an incorrect line-ending.

Thanks Cameron for your

Submitted by fabio on Thu, 2010-04-01 23:57.

Thanks Cameron for your contribution! I didn't noticed that \n\r was incorrect! I simply overlooked that!

I wrote an email to the commenter you replyed so he'll be able to read your comment.

Thanks for your help!

input=1

Submitted by Anonymous (not verified) on Wed, 2009-09-30 12:58.

Hi Fablo,

may i ask why you put input=1?

thanks

jaro

Hi Jaro, thanks for

Submitted by fabio on Wed, 2009-09-30 20:53.

Hi Jaro, thanks for commenting.

I think that the input=1 statement is useless and can be safely removed.

My background is C and Java so sometimes I found myself initializing variables even if that its useless with Python.

Take Care.

FV

thanks a lot for fast response:)

Submitted by jaro stancik (not verified) on Fri, 2009-10-02 13:05.

enjoy weekend.o0

non-ascii issues

Submitted by stacey (not verified) on Wed, 2009-09-16 19:49.

Hi!

I'm trying to do a very similar thing to what you demonstrate here, except I'd like to print out the numerical value of the char instead of the ascii equivilent. Whenever I send a char from the dsPIC33 to my pc through serial,

print x

works fine,

but print int(x, 16)

gives me an error because the input has a /x in front (/xFF for example) and the python doesn't like that. Any ideas how I print out the actual int instead of the ascii?

Thanks!
Stace

Maybe I did not understand ..

Submitted by fabio on Wed, 2009-09-16 23:27.

Maybe I did not understand .. but have you tried with

print int(x.slit("/x"), 16)

getty problems

Submitted by joost witteveen (not verified) on Wed, 2009-08-26 12:11.

One note:
If the communication mostly works, but after a few seconds fails again, it may be that there is a getty (terminal) server listening on the serial port, eating part of your communications.

To test this, run as root:
# fuser -v /dev/ttyS0

USER PID ACCESS COMMAND
/dev/ttyS0: root 3576 F.... getty

(with /dev/ttyS0 the port you are using). If getty is running, remove from /etc/inittab a line looking like this:
T0:2345:respawn:/sbin/getty -L ttyS0 115200 vt100

and reboot server (just 'kill -SIGHUP 0' doesn't seem to work)

I personally never had this

Submitted by fabio on Wed, 2009-08-26 14:02.

I personally never had this problem but I understand it can occurs.

Thanks for your contribution.

Serial RS232 connections in Python

Submitted by Pedro (not verified) on Thu, 2009-03-26 13:37.

Hello Fabio,

I've used your Python code to monitor a device I have. I'm a very inexperient Python user, in fact I have no experience at all. This might seem a silly question but I just want to know I do alter the code to supress the need of entering the ENTER key over and over. I think don't need the sleep function because my device already enters in sleep mode and I'm looking for a continuos reading, so I intend to press ENTER only one time and let the readings flow. Is that possible? Can you tell me how?

Thanks in advance,
Pedro.

Well, if you have a close

Submitted by fabio on Fri, 2009-03-27 00:47.

Well, if you have a close look at the code you will see these lines:

while ser.inWaiting() > 0:
out += ser.read(1)

if out != '':
print ">>" + out

That code does exactly what you are trying to achieve. You can use it just like that.

So.. if you want to just use the code in the article just remove the line:

ser.write(input + '\r\n')

(you can put a # at the beginning of it)

And no more input will be read from the keyboard.. the program will just read from the device.

Let me know if it worked.

Pythoscope

Submitted by Peter Nemeth (not verified) on Mon, 2009-01-26 08:20.

Thank You! It is really awesome! I could resuscitates and gain control over my telescope mount with pyserial. It is the power of Python.

That's awesome!!! I was

Submitted by Al (not verified) on Tue, 2008-07-22 04:59.

That's awesome!!! I was sooooo close to getting mine working, and this helped me get serial comms working. I'm communicating with a propeller chip. Thank you!

Post new comment

The content of this field is kept private and will not be shown publicly.
If you have a personal or company website insert its address in the form http://www.example.com/ .
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <pre> <small> <del> <img> <h2> <h3> <h4> <b> <video> <sub> <sup>
  • Lines and paragraphs break automatically.
  • Images can be added to this post.
  • You may use [inline:xx] tags to display uploaded files or images inline.
  • You may insert videos with [video:URL]
  • Each email address will be obfuscated in a human readable fashion or (if JavaScript is enabled) replaced with a spamproof clickable link.

More information about formatting options