Question regarding serial port communication with python.

jackxh at my-deja.com jackxh at my-deja.com
Thu Nov 2 19:02:24 CET 2000


Hi everyone:
I got following piece code from newsgroup and made some small
modification. It runs, but in order to determine how many bye to read,
the script has to search for '\n'. I don't like this because a lot of
times the serial port give you back a lot of "\n" in the data. I was
wondering if there is an function that is simular to os.read() but
doesn't require you to input a number for the byte to read.  In stead,
it will through back the data or message back like a telnet session.

Thanks a lot.

Jack Xie

#	Actual Code --------------------------
import os, termios
import FCNTL, TERMIOS

class SerialPort:
    """Basic serial port class.

    This simply encapsulates a file descriptor for the desired serial
port.
    """

    def __init__(self, dev):
        print dev
        fd = self.fd = os.open(dev, FCNTL.O_RDWR)

        self.original_state = termios.tcgetattr(fd)

        L = termios.tcgetattr(fd)
        iflag, oflag, cflag, lflag, ispeed, ospeed, chars = L
        ispeed = ospeed = TERMIOS.B9600
        cflag = (cflag & ~TERMIOS.CSIZE) | TERMIOS.CS8 | TERMIOS.CSTOP
        cflag = (cflag | TERMIOS.CLOCAL | TERMIOS.CREAD) &
~TERMIOS.CRTSCTS
        iflag = TERMIOS.IGNBRK
        lflag = 0
        oflag = 0
        chars[ TERMIOS.VMIN ] = 1
        chars[ TERMIOS.VTIME ] = 5
        iflag = iflag & ~(TERMIOS.IXON | TERMIOS.IXOFF | TERMIOS.IXANY)
        cflag = cflag & ~(TERMIOS.PARENB | TERMIOS.PARODD)
        L = [iflag, oflag, cflag, lflag, ispeed, ospeed, chars]
        termios.tcsetattr(fd, TERMIOS.TCSANOW, L)
        L = termios.tcgetattr(fd)

    def write(self, string):
        "Write a string to the port"
        os.write(self.fd, string)
#        termios.tcdrain(self.fd)
#        termios.tcflush(self.fd, TERMIOS.TCOFLUSH)

    def read(self, N=1):
        "Read a string from the port"
        return os.read(self.fd, N)


    def close(self):
        termios.tcsetattr(self.fd, TERMIOS.TCSANOW, self.original_state)
        if self.fd is None: return
        os.close( self.fd )
        self.fd = None

def test(args = None):
    x.write('ls\n')
    while 1:
        c = x.read(5)
        print c
        if c == '\n': break

    x.close()

if __name__ == '__main__':
    test()


Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list