Read from Serial Port

Grant Edwards grante at visi.com
Fri Jan 20 22:41:43 EST 2006


On 2006-01-21, Casey Bralla <Nobody at Nowhere.com> wrote:

> I'd like to read ASCII data from a serial port, but (once
> again) I'm having trouble getting started.  (Can't seem to
> find the basic level of docs to get going <sigh>)
>
> I'd like to use only standard "built-in" modules if possible.

Then there aren't going to be any "basic level docs" because
it's just not an easy thing to do.  You pretty much have to do
exactly what you would do in C. So, for Linux/Unix, study up on
http://www.easysw.com/~mike/serial/serial.html. Then do the
exact same thing in python using the "os" module stuff that
deals with file descriptors and termios. And you'll probably to
use select to impliment a timeout when there's no data:

http://www.python.org/doc/2.4.2/lib/os-fd-ops.html
http://www.python.org/doc/2.4.2/lib/module-termios.html
http://www.python.org/doc/2.4.2/lib/module-select.html

For Win32, you'll have to do all of the nasty Win32
CreateFile() calls and such-like. IMO, It's even uglier than
the Posix termios stuff (though not by much).  For example,
CreateFile() takes seven parameters, and none of them default
to useful values (it's places like that where Win32's VMS
heritage comes shining through in a manner that instead of
illumnating anything temporarily blinds you and causes you to
run into a tree).

> Could somebody offer a simple code-snippet to get me started
> reading from a serial port?

Not using just the built-in modules.  There is no such simple
code-snippet.  If you want simple use pyserial which handles
all of the tricky bits for you:

http://pyserial.sourceforge.net/

It's not a "built-in" module, but it's what you want to use
unless you already know all the contortions require to do
serial port stuff using Posix or Win32 system calls.  

Really.

If you truly, madly, deeply want to use just built-in modules,
then your best bet is to download pyserial and copy the
appropriate platform-specific code.  I'll be happy to answer
questions about the Posix parts of it, but I had the portion of
my brain containing Win32 knowledge cauterized.

-- 
Grant Edwards                   grante             Yow!  I'm losing my
                                  at               hair...did it go to
                               visi.com            ATLANTIC CITY??



More information about the Python-list mailing list