- Short introduction¶
- Configuring ports later¶
- Readline¶
- EOL¶
- Testing ports¶
- Listing ports¶
- Accessing ports¶
- Using Serial Read or Readline Functions in Python
- Prerequisites
- Reading Data from a Serial Port
- Reading serial device using serial.read()
- Using serial.readline() to read information from a serial port
- Short introduction¶
- Configuring ports later¶
- Readline¶
- EOL¶
- Testing ports¶
- Listing ports¶
- Accessing ports¶
Short introduction¶
Open port at “38400,8,E,1”, non blocking HW handshaking:
>>> ser = serial.Serial('COM3', 38400, timeout=0, . parity=serial.PARITY_EVEN, rtscts=1) >>> s = ser.read(100) # read up to one hundred bytes . # or as much is in the buffer
Configuring ports later¶
Get a Serial instance and configure/open it later:
>>> ser = serial.Serial() >>> ser.baudrate = 19200 >>> ser.port = 'COM1' >>> ser Serial(port='COM1', baudrate=19200, bytesize=8, parity='N', stopbits=1, timeout=None, xonxoff=0, rtscts=0) >>> ser.open() >>> ser.is_open True >>> ser.close() >>> ser.is_open False
with serial.Serial() as ser: ser.baudrate = 19200 ser.port = 'COM1' ser.open() ser.write(b'hello')
Readline¶
readline() reads up to one line, including the \n at the end. Be careful when using readline() . Do specify a timeout when opening the serial port otherwise it could block forever if no newline character is received. If the \n is missing in the return value, it returned on timeout.
readlines() tries to read “all” lines which is not well defined for a serial port that is still open. Therefore readlines() depends on having a timeout on the port and interprets that as EOF (end of file). It raises an exception if the port is not opened correctly. The returned list of lines do not include the \n .
Both functions call read() to get their data and the serial port timeout is acting on this function. Therefore the effective timeout, especially for readlines() , can be much larger.
Do also have a look at the example files in the examples directory in the source distribution or online.
The eol parameter for readline() is no longer supported when pySerial is run with newer Python versions (V2.6+) where the module io is available.
EOL¶
To specify the EOL character for readline() or to use universal newline mode, it is advised to use io.TextIOWrapper:
import serial import io ser = serial.serial_for_url('loop://', timeout=1) sio = io.TextIOWrapper(io.BufferedRWPair(ser, ser)) sio.write(unicode("hello\n")) sio.flush() # it is buffering. required to get the data out *now* hello = sio.readline() print(hello == unicode("hello\n"))
Testing ports¶
Listing ports¶
python -m serial.tools.list_ports will 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.
The enumeration may not work on all operating systems. It may be incomplete, list unavailable ports or may lack detailed descriptions of the ports.
Accessing ports¶
pySerial includes a small console based terminal program called serial.tools.miniterm . It can be started with python -m serial.tools.miniterm (use option -h to get a listing of all options).
© Copyright 2001-2020, Chris Liechti Revision 31fa4807 .
Versions latest stable Downloads pdf html epub On Read the Docs Project Home Builds Free document hosting provided by Read the Docs.
Using Serial Read or Readline Functions in Python
This article discusses how to read data from serial ports using serial.read() and serial.readline() functions on the pyserial library. Before we do that, however, let us cover some prerequisites.
Prerequisites
We must take care of two things before interacting with serial ports on your device.
First of all, we need to install the Python library to use. The package is called pyserial, which can be installed from the PyPI repository using pip by running the command:
Secondly, we need to identify the serial ports available on the device. We can do this using serial.tools (which is part of the pyserial library but needs to be imported separately). The serial device name can then be found using the .device method. Here is the code.
COM3 - Intel(R) Active Management Technology - SOL (COM3) COM3
You can also run serial.tools.list_ports as a module to get the list of serial ports. That can be done by running the following line on the command line.
You can also locate serial devices outside Python. If you are working with Linux or Mac, serial ports are named /dev/tty*, whereas on Windows, the ports are located on the Ports item on Devices Manager (Go to Start and search for “Device Manager” and find the Ports on the list).
Reading Data from a Serial Port
Once you have identified the active ports, we can choose the one we want to read from. Let’s assume we want to read from COM4 serial port using read() and readline() functions.
Reading serial device using serial.read()
Let’s see an example with comments to break down each line.
The timeout argument in serial.Serial() is set to 1 in the code above. That means that ser.read() will be timed out after 1 second and returns bytes that have been fetched until then.
If we set timeout=None, then the ser.read() will wait forever/until the requested bytes of data is retrieved. You can request a specific number of bytes by changing the line x=ser.read() into something like this to fetch 8 bytes:
You can also use serial object as a context manager as follows.
Using serial.readline() to read information from a serial port
If you are sure that each data piece is terminated with the End of Line character (EOL), you can use serial.readline() to read all bytes until the data piece is terminated by EOL. The new line character “\n” is the default EOL in the pyserial library.
If data coming in does not have proper EOL character, serial.readline() may run without terminating if a timeout value is not provided.
“Be careful when using readline(). 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 work with a timeout. readlines() depends on having a timeout and interprets that as EOF (end of file).” – Source: documentation.
Short introduction¶
Open port at “38400,8,E,1”, non blocking HW handshaking:
>>> ser = serial.Serial('COM3', 38400, timeout=0, . parity=serial.PARITY_EVEN, rtscts=1) >>> s = ser.read(100) # read up to one hundred bytes . # or as much is in the buffer
Configuring ports later¶
Get a Serial instance and configure/open it later:
>>> ser = serial.Serial() >>> ser.baudrate = 19200 >>> ser.port = 'COM1' >>> ser Serial(port='COM1', baudrate=19200, bytesize=8, parity='N', stopbits=1, timeout=None, xonxoff=0, rtscts=0) >>> ser.open() >>> ser.is_open True >>> ser.close() >>> ser.is_open False
Also supported with context manager:
serial.Serial() as ser: ser.baudrate = 19200 ser.port = 'COM1' ser.open() ser.write(b'hello')
Readline¶
Be carefully when using readline() . 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.
Do also have a look at the example files in the examples directory in the source distribution or online.
The eol parameter for readline() is no longer supported when pySerial is run with newer Python versions (V2.6+) where the module io is available.
EOL¶
To specify the EOL character for readline() or to use universal newline mode, it is advised to use io.TextIOWrapper:
import serial import io ser = serial.serial_for_url('loop://', timeout=1) sio = io.TextIOWrapper(io.BufferedRWPair(ser, ser)) sio.write(unicode("hello\n")) sio.flush() # it is buffering. required to get the data out *now* hello = sio.readline() print(hello == unicode("hello\n"))
Testing ports¶
Listing ports¶
python -m serial.tools.list_ports will 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.
The enumeration may not work on all operating systems. It may be incomplete, list unavailable ports or may lack detailed descriptions of the ports.
Accessing ports¶
pySerial includes a small console based terminal program called serial.tools.miniterm. It ca be started with python -m serial.tools.miniterm (use option -h to get a listing of all options).