Return to site

Python Serial Read Timeout Example

broken image


  1. Python Serial Read Time Out Examples
  2. Python Timeout Example
  3. Python Serial Read Timeout

To read single byte from serial device. Data = ser.read to read given number of bytes from the serial device. Data = ser.read(size=5) to read one line from serial device. Data = ser.readline to read the data from serial device while something is being written over it. #for python2.7 data = ser.read(ser.inWaiting) #for python3 ser.read(ser. Project: spi-flash-programmer Author: nfd File: spiflashprogrammerclient.py License: Creative. If a timeout is set it may return less characters as requested. Now I am trying to achieve the same thing using Python serial connector. Import serial ser = Serial ('COM5',timeout=2) ser.write(' x0C') # equivalent to ctrl+L. Usage examples can be found in the examples where two TCP/IP - serial converters are shown, one using threads (the single port server) and an other using select (the multi port server). Note Each new client connection must create a new instance as this object (and the RFC 2217 protocol) has internal state. Buffer += ser.read(ser.inWaiting) if ' ' in buffer: lastreceived, buffer = buffer.split(' ')-2: if name 'main': ser = Serial( port=None, baudrate=9600, bytesize=EIGHTBITS, parity=PARITYNONE, stopbits=STOPBITSONE, timeout=0.1, xonxoff=0, rtscts=0, interCharTimeout=None ) Thread(target=receiving, args=(ser,)).start.

Read
Simple python script to read two serial ports at the same time. Good for snooping on bidirectional comms!

Python Serial Read Time Out Examples

read_serial.py
#!/usr/bin/python3
importserial, time, sys, threading
fromcoloramaimportFore, Style, initascolorama_init
colorama_init()
# lock to serialize console output
lock=threading.Lock()
classHighlight:
def__init__(self, clazz, color):
self.color=color
self.clazz=clazz
def__enter__(self):
print(self.color, end=')
def__exit__(self, type, value, traceback):
ifself.clazzFore:
print(Fore.RESET, end=')
else:
assertself.clazzStyle
print(Style.RESET_ALL, end=')
sys.stdout.flush()
iflen(sys.argv) !=3andlen(sys.argv) !=4:
sys.stderr.write('Usage: %s []n'% (sys.argv[0]))
exit(1)
defread_serial(port, baud, color):
ser=serial.Serial()
ser.port=port
ser.baudrate=baud
ser.bytesize=serial.EIGHTBITS#number of bits per bytes
ser.parity=serial.PARITY_NONE#set parity check: no parity
ser.stopbits=serial.STOPBITS_ONE#number of stop bits
#ser.timeout = None #block read
ser.timeout=0# non blocking read
ser.xonxoff=False#disable software flow control
ser.rtscts=False#disable hardware (RTS/CTS) flow control
ser.dsrdtr=False#disable hardware (DSR/DTR) flow control
ser.writeTimeout=2#timeout for write
try:
ser.open()
exceptExceptionase:
print('error open serial port: '+str(e))
exit()
ifser.isOpen():
try:
whileTrue:
c=ser.read(size=1024)
withlock:
iflen(c) >0:
print(color)
sys.stdout.buffer.write(c)
ser.close()
exceptExceptionase1:
print ('error communicating...: '+str(e1))
else:
print('cannot open serial port ')
exit()
# Create two threads as follows
try:
t=threading.Thread(target=read_serial, args=(sys.argv[2], sys.argv[1], Fore.GREEN ))
t.daemon=True# thread dies when main thread (only non-daemon thread) exits.
t.start()
iflen(sys.argv) 4:
t=threading.Thread(target=read_serial, args=(sys.argv[3], sys.argv[1], Fore.RED ))
t.daemon=True# thread dies when main thread (only non-daemon thread) exits.
t.start()
except:
print('Error: unable to start thread')
try:
whileTrue:
pass
exceptKeyboardInterrupt:
exit()

commented Jun 5, 2018

Python pyserial read example
Simple python script to read two serial ports at the same time. Good for snooping on bidirectional comms!

Python Serial Read Time Out Examples

read_serial.py
#!/usr/bin/python3
importserial, time, sys, threading
fromcoloramaimportFore, Style, initascolorama_init
colorama_init()
# lock to serialize console output
lock=threading.Lock()
classHighlight:
def__init__(self, clazz, color):
self.color=color
self.clazz=clazz
def__enter__(self):
print(self.color, end=')
def__exit__(self, type, value, traceback):
ifself.clazzFore:
print(Fore.RESET, end=')
else:
assertself.clazzStyle
print(Style.RESET_ALL, end=')
sys.stdout.flush()
iflen(sys.argv) !=3andlen(sys.argv) !=4:
sys.stderr.write('Usage: %s []n'% (sys.argv[0]))
exit(1)
defread_serial(port, baud, color):
ser=serial.Serial()
ser.port=port
ser.baudrate=baud
ser.bytesize=serial.EIGHTBITS#number of bits per bytes
ser.parity=serial.PARITY_NONE#set parity check: no parity
ser.stopbits=serial.STOPBITS_ONE#number of stop bits
#ser.timeout = None #block read
ser.timeout=0# non blocking read
ser.xonxoff=False#disable software flow control
ser.rtscts=False#disable hardware (RTS/CTS) flow control
ser.dsrdtr=False#disable hardware (DSR/DTR) flow control
ser.writeTimeout=2#timeout for write
try:
ser.open()
exceptExceptionase:
print('error open serial port: '+str(e))
exit()
ifser.isOpen():
try:
whileTrue:
c=ser.read(size=1024)
withlock:
iflen(c) >0:
print(color)
sys.stdout.buffer.write(c)
ser.close()
exceptExceptionase1:
print ('error communicating...: '+str(e1))
else:
print('cannot open serial port ')
exit()
# Create two threads as follows
try:
t=threading.Thread(target=read_serial, args=(sys.argv[2], sys.argv[1], Fore.GREEN ))
t.daemon=True# thread dies when main thread (only non-daemon thread) exits.
t.start()
iflen(sys.argv) 4:
t=threading.Thread(target=read_serial, args=(sys.argv[3], sys.argv[1], Fore.RED ))
t.daemon=True# thread dies when main thread (only non-daemon thread) exits.
t.start()
except:
print('Error: unable to start thread')
try:
whileTrue:
pass
exceptKeyboardInterrupt:
exit()

commented Jun 5, 2018

commented Jun 25, 2018

Python Timeout Example

when I run this code on spyder IDE . i got this error:

runfile('C:/Users/iit/readserial.py', wdir='C:/Users/iit')
Usage: C:/Users/iit/readserial.py []
Error: unable to start thread

Python Serial Read Timeout

Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment




broken image