Python Serial Read Timeout Example

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

The following are 30 code examples for showing how to use serial.EIGHTBITS. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar. 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. Python -m serial.tools.listportswill print a list of available ports. It is also possible to add a regexp as first argument and the list will only include entries that matched. Simple python script to read two serial ports at the same time. Good for snooping on bidirectional comms! - readserial.py.

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 <baud> <port1> [<port2>]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

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

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

Bases: object

Instantiate a Serial object and open the tty device at the specifiedpath with the specified baudrate, and the defaults of 8 data bits, noparity, 1 stop bit, no software flow control (xonxoff), and no hardwareflow control (rtscts).

Parameters:
  • devpath (str) – tty device path.
  • baudrate (int) – baudrate.
  • databits (int) – data bits, can be 5, 6, 7, 8.
  • parity (str) – parity, can be “none”, “even”, “odd”.
  • stopbits (int) – stop bits, can be 1 or 2.
  • xonxoff (bool) – software flow control.
  • rtscts (bool) – hardware flow control.
Returns:

Serial object.

Return type:
Raises:
  • SerialError – if an I/O or OS error occurs.
  • TypeError – if devpath, baudrate, databits, parity, stopbits, xonxoff, or rtscts types are invalid.
  • ValueError – if baudrate, databits, parity, or stopbits values are invalid.
read(length, timeout=None)[source]

Read up to length number of bytes from the serial port with anoptional timeout.

timeout can be positive for a timeout in seconds, 0 for anon-blocking read, or negative or None for a blocking read that willblock until length number of bytes are read. Default is a blockingread.

Python Serial Read Time Out Example Pdf

For a non-blocking or timeout-bound read, read() may return data whoselength is less than or equal to the requested length.

Parameters:
  • length (int) – length in bytes.
  • timeout (int, float, None) – timeout duration in seconds.
Returns:

data read.

Return type:

bytes

Raises:

SerialError – if an I/O or OS error occurs.

Python Read Serial Port

write(data)[source]

Write data to the serial port and return the number of byteswritten.

Parameters:

data (bytes, bytearray, list) – a byte array or list of 8-bit integers to write.

Returns:

number of bytes written.

Return type:

int

Raises:
  • SerialError – if an I/O or OS error occurs.
  • TypeError – if data type is invalid.
  • ValueError – if data is not valid bytes.
poll(timeout=None)[source]

Poll for data available for reading from the serial port.

timeout can be positive for a timeout in seconds, 0 for anon-blocking poll, or negative or None for a blocking poll. Default isa blocking poll.

Parameters:timeout (int, float, None) – timeout duration in seconds.
Returns:True if data is available for reading from the serial port, False if not.
Return type:bool
flush()[source]

Flush the write buffer of the serial port, blocking until all bytesare written.

Raises:SerialError – if an I/O or OS error occurs.
input_waiting()[source]

Query the number of bytes waiting to be read from the serial port.

Returns:number of bytes waiting to be read.
Return type:int
Raises:SerialError – if an I/O or OS error occurs.
output_waiting()[source]

Query the number of bytes waiting to be written to the serial port.

Returns:number of bytes waiting to be written.
Return type:int
Raises:SerialError – if an I/O or OS error occurs.
close()[source]

Close the tty device.

Raises:SerialError – if an I/O or OS error occurs.
fd

Get the file descriptor of the underlying tty device.

Type:int
devpath
Python timeout example

Get the device path of the underlying tty device.

Python Serial Read Time Out Example Sentences

Type:str
baudrate

Get or set the baudrate.

Python Serial Read Timeout Example
Raises:
  • SerialError – if an I/O or OS error occurs.
  • TypeError – if baudrate type is not int.
  • ValueError – if baudrate value is not supported.
Type:

int

databits

Get or set the data bits. Can be 5, 6, 7, 8.

Raises:
  • SerialError – if an I/O or OS error occurs.
  • TypeError – if databits type is not int.
  • ValueError – if databits value is invalid.
Type:

int

parity

Get or set the parity. Can be “none”, “even”, “odd”.

Raises:
  • SerialError – if an I/O or OS error occurs.
  • TypeError – if parity type is not str.
  • ValueError – if parity value is invalid.
Type:

str

stopbits

Get or set the stop bits. Can be 1 or 2.

Raises:
  • SerialError – if an I/O or OS error occurs.
  • TypeError – if stopbits type is not int.
  • ValueError – if stopbits value is invalid.
Type:

int

xonxoff

Get or set software flow control.

Raises:
  • SerialError – if an I/O or OS error occurs.
  • TypeError – if xonxoff type is not bool.
Type:

bool

rtscts

Get or set hardware flow control.

Python Serial Read Timeout

Raises:
  • SerialError – if an I/O or OS error occurs.
  • TypeError – if rtscts type is not bool.
Type:

bool