
Using PySerial in Python: A Comprehensive Guide
PySerial is a Python library that provides access to the serial ports on a variety of operating systems. It is widely used for communication between microcontrollers and computers, enabling the exchange of data over serial communication protocols. In this article, we will explore the PySerial library and its various functions, as well as how to use it effectively in Python.
Table of Contents
- Introduction to Serial Communication
- Installing PySerial
- Opening and Closing a Serial Port
- Reading and Writing Data
- Setting Timeout and Buffer Sizes
- Working with Serial Events
- Example: Reading Sensor Data from Arduino
- Conclusion
Introduction to Serial Communication
Serial communication is a way of transmitting data between two devices using a serial interface. It involves sending data one bit at a time, sequentially, over a single communication channel. Some popular serial communication protocols include UART (Universal Asynchronous Receiver/Transmitter), SPI (Serial Peripheral Interface), and I2C (Inter-Integrated Circuit).
PySerial makes it easy to work with serial devices in Python, abstracting away the underlying hardware and providing a consistent, easy-to-use interface regardless of the platform you are using.
Installing PySerial
To install PySerial, use the following pip command:
pip install pyserialThis will download and install the latest version of PySerial from the Python Package Index (PyPI).
Opening and Closing a Serial Port
To start using PySerial, you’ll need to open a serial port. This is usually done by specifying the port name and the baud rate. The baud rate is the speed at which the data is transmitted over the serial connection, measured in bits per second (bps).
Here’s an example of opening a serial port:
import serial
ser = serial.Serial('COM3', 9600) ## Open serial port with the name 'COM3' and baud rate of 9600Make sure to replace 'COM3' with the appropriate port name for your system. On Windows, port names are usually in the format 'COMx', while on Linux and macOS, they are in the format '/dev/ttyUSBx' or '/dev/ttyACMx'.
Once you’ve finished using the serial port, it’s important to close it to free up system resources:
ser.close()Reading and Writing Data
To read data from the serial port, you can use the read() or readline() methods. The read() method reads a specified number of bytes from the serial port, while the readline() method reads a line of data terminated by a newline character (\n).
Here’s an example of reading a line of data:
data = ser.readline().decode('ascii') ## Read a line of data and decode it as an ASCII string
print(data)To write data to the serial port, use the write() method:
data = "Hello, world!\n"
ser.write(data.encode('ascii')) ## Encode the string as ASCII and write it to the serial portSetting Timeout and Buffer Sizes
PySerial allows you to set a timeout for read operations, which is useful when you don’t want your program to block indefinitely while waiting for data. To set a timeout, simply pass the timeout parameter when opening the serial port:
ser = serial.Serial('COM3', 9600, timeout=1) ## Set a timeout of 1 secondIn addition to setting a timeout, you can also control the size of the input and output buffers:
ser = serial.Serial('COM3', 9600, timeout=1, bytesize=8, parity='N', stopbits=1)This example sets the byte size to 8 bits, no parity, and one stop bit. These parameters are common for most serial devices, but you may need to adjust them based on the device you are communicating with.
Working with Serial Events
In some cases, you may want to perform specific actions when certain events occur, such as when new data is received. PySerial provides support for event-driven programming through the serial.threaded sub-module.
Here’s an example of using a serial.threaded.ReaderThread to handle incoming data:
import serial
import serial.threaded
class SerialReader(serial.threaded.Protocol):
def __init__(self):
self.buffer = bytearray()
def data_received(self, data):
self.buffer.extend(data)
if b'\n' in self.buffer:
lines = self.buffer.split(b'\n')
self.buffer = bytearray()
for line in lines[:-1]:
print(line.decode('ascii'))
ser = serial.Serial('COM3', 9600, timeout=1)
with serial.threaded.ReaderThread(ser, SerialReader) as protocol:
## The ReaderThread will automatically call the data_received method when data is received
## You can perform other tasks here while the ReaderThread handles incoming data
time.sleep(10) ## Example: wait for 10 seconds before exitingThis example defines a SerialReader class that inherits from serial.threaded.Protocol. The data_received() method is automatically called whenever new data is received, making it easy to handle incoming data in an event-driven manner.
Example: Reading Sensor Data from Arduino
In this example, we’ll use PySerial to read sensor data from an Arduino. Assume that the Arduino is programmed to send sensor data as a string in the format "<sensor_name>:<value>\n" over the serial port.
import serial
## Open the serial port
ser = serial.Serial('COM3', 9600, timeout=1)
def read_sensor_data():
data = ser.readline().decode('ascii').strip()
if data:
sensor_name, value = data.split(':')
print(f"{sensor_name}: {value}")
## Read sensor data in a loop
while True:
read_sensor_data()This simple script continuously reads and prints sensor data from the Arduino. Make sure to adapt the port name ('COM3' in this example) to match your system.
Conclusion
PySerial is a powerful and easy-to-use Python library for working with serial communication. It provides a consistent interface across various platforms and simplifies the process of opening, closing, reading from, and writing to serial ports. By leveraging PySerial’s capabilities and following best practices, you can create robust applications that communicate with a wide range of serial devices, such as microcontrollers and sensors.
In this article, we’ve covered the basics of PySerial, including installation, opening and closing serial ports, reading and writing data, setting timeouts and buffer sizes, working with serial events, and an example of reading sensor data from an Arduino. With this knowledge, you’re well-equipped to start using PySerial in your own Python projects.






