Read from serial port

Fredrik Lundh fredrik at pythonware.com
Thu Aug 14 11:13:17 CEST 2008


mmrasheed at gmail.com wrote:

> I need a promt/terminal when the device is connected to PC. If user
> enters a command by serial port and press "Enter" then the data is
> read by the device and work on the command. This is similar to
> readline() function. Unfortunately there is no readline() function for
> GM862 device. The following functions are available for serial port
> data receive-
> 
> SER.read() - reads whole string at a time from buffer
> SER.receive(timeout) - reads  if there is any input in the buffer
> andwait for the input upto timeout
> SER.receivebyte(timeout) - reads  if there is any byte sent in the
> buffer and wait for the input upto timeout

Unless I'm missing something, a simple loop should be all you need:

     import SER

     def readline(timeout=36000):
         line = ""
         while 1:
             ch = SER.receivebyte(timeout)
             if ch < 0:
                 raise IOError("timeout")
             if ch == 10:
                 break # stop collecting when we get LF
             if ch == 13:
                 continue # ignore CR, in case we get CR+LF
             line = line + chr(ch)
         return line

Tweak as necessary.

(and before anyone pops up with a "better" way to do that, keep in mind 
that the GM862 device uses a custom version of Python 1.5.2.)

</F>




More information about the Python-list mailing list