Simple python script to read two serial ports at the same time. Good for snooping on bidirectional comms!
This quick-start example shows how you can create a UART device for communicating with hardware serial devices. To use this example, you'll need something to generate the UART data. We've used a GPS! Note that the GPS will give you UART data without getting a fix on your location. You can use this example right from your desk! Do specify a timeout when opening the serial port otherwise it could block forever if no newline character is received. Also note that readlines only works with a timeout. Readlines depends on having a timeout and interprets that as EOF (end of file). It raises an exception if the port is not opened correctly. Python Serial.write - 30 examples found. These are the top rated real world Python examples of serial.Serial.write extracted from open source projects. You can rate examples to help us improve the quality of 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 <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
The Bandwidth provided for Premium users it nearly up to 1TB. Magnet links wiki.
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: |
|
---|---|
Returns: | Serial object. |
Return type: | |
Raises: |
|
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 blocking read with a timeout inseconds, zero for a non-blocking read, or negative or None for ablocking read that will block until length number of bytes are read.Default is a blocking read.
![Example Example](https://cdn.instructables.com/FJ8/J6B8/J8KGWMI3/FJ8J6B8J8KGWMI3.LARGE.jpg)
For a non-blocking or timeout-bound read, read() may return less thanthe requested number of bytes.
For a blocking read with the VMIN setting configured, read() willblock until at least VMIN bytes are read. For a blocking read with bothVMIN and VTIME settings configured, read() will block until at leastVMIN bytes are read or the VTIME interbyte timeout expires after thelast byte read. In either case, read() may return less than therequested number of bytes.
Parameters: |
|
---|---|
Returns: | data read. |
Return type: | bytes |
Raises: | SerialError – if an I/O or OS error occurs. |
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. Dungeon siege 3 cheat pc. |
Return type: | int |
Raises: |
|
poll
(timeout=None)[source]¶Poll for data available for reading from the serial port with anoptional timeout.
timeout can be positive for a timeout in seconds, zero 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. |
---|
![Python Python](/uploads/1/1/9/8/119847547/171323246.png)
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
¶Get the device path of the underlying tty device.
Python Serial Example
Type: | str |
---|
baudrate
¶Get or set the baudrate.
Raises: |
|
---|---|
Type: | int |
databits
¶Get or set the data bits. Can be 5, 6, 7, 8.
Raises: |
|
---|---|
Type: | int |
parity
¶Get or set the parity. Can be “none”, “even”, “odd”.
Raises: |
|
---|---|
Type: | str |
stopbits
¶Get or set the stop bits. Can be 1 or 2.
Raises: |
|
---|---|
Type: | int |
xonxoff
¶Get or set software flow control.
Raises: |
|
---|---|
Type: | bool |
rtscts
¶Get or set hardware flow control.
Raises: |
|
---|---|
Type: | bool |
Python Serial Read Time Out Example Sentences
vmin
¶Get or set the VMIN termios setting for minimum number of bytes returnedfrom a blocking read. Can be between 0 and 255.
When configured in conjunction with VTIME, VTIME acts as an interbytetimeout that restarts on every byte received, and a blocking read willblock until at least VMIN bytes are read or the VTIME timeout expires afterthe last byte read. See the termios man page for more information.
Raises: |
|
---|---|
Type: | int |
vtime
¶Get or set the VTIME termios setting for timeout in seconds of ablocking read. Can be between 0 to 25.5 seconds, with a resolution of 0.1seconds.
When configured in conjunction with VMIN, VTIME acts as an interbytetimeout that restarts on every byte received, and a blocking read willblock until at least VMIN bytes are read or the VTIME timeout expires afterthe last byte read. See the termios man page for more information.
On your Mac, select a disk, folder, or file, then choose File Get Info. If the information in Sharing & Permissions isn’t visible, click the disclosure triangle. Click the lock icon to unlock it. Enter an administrator name and password. Click a user or group in the Name column, then choose a privilege setting from the pop-up menu. Directory permission 2016 for mac windows 7.
Raises: |
|
---|---|
Type: | float |