Question regarding serial port communication with python.
jackxh at my-deja.com
jackxh at my-deja.com
Thu Nov 2 13:02:24 EST 2000
More information about the Python-list mailing list
Thu Nov 2 13:02:24 EST 2000
- Previous message (by thread): popen2.popen2,3,4 from Python 2.0 on NT 4.0 SP5
- Next message (by thread): Fatal Python error: PyThreadState_Get: no current thread
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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.
- Previous message (by thread): popen2.popen2,3,4 from Python 2.0 on NT 4.0 SP5
- Next message (by thread): Fatal Python error: PyThreadState_Get: no current thread
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list