Serial RS232 connections in Python
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.



Send file between two modules
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
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 !
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
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,
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
Sounds interesting, do you have any link to docs/examples?
Impossibility to listen the device
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
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
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
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.
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
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
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
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.
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()
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
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!
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
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
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
You're ser.write has an incorrect line-ending.
Thanks Cameron for your
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
Hi Fablo,
may i ask why you put input=1?
thanks
jaro
Hi Jaro, thanks for
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:)
enjoy weekend.o0
non-ascii issues
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 ..
Maybe I did not understand .. but have you tried with
print int(x.slit("/x"), 16)getty problems
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
I personally never had this problem but I understand it can occurs.
Thanks for your contribution.
Serial RS232 connections in Python
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
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
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
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