PySerial
PySerial is a widely used, cross-platform Python library that provides essential functionality for serial port communication. It allows Python scripts to easily interact with a broad range of hardware devices, including microcontrollers (like Arduino and Raspberry Pi), GPS modules, industrial sensors, and other serial-enabled peripherals across Windows, Linux, and macOS. Currently at version 3.5, PySerial maintains an active development cycle, releasing bug fixes and minor feature updates periodically.
Warnings
- breaking Python 2.x vs. Python 3.x String Handling: PySerial 3.x requires `bytes` objects for write operations (e.g., `ser.write(b'data')`). Direct string literals (`'data'`) will cause errors in Python 3.x, unlike Python 2.x where strings were byte sequences.
- breaking Removal of `serial.aio`: Asynchronous I/O support (`serial.aio`) was removed from the core PySerial library in version 3.2.1.
- deprecated Deprecated methods `inWaiting()` and `isOpen()`: These methods were deprecated in favor of more Pythonic attribute names.
- gotcha `readline()` without a timeout can block indefinitely: If a timeout is not set on the `Serial` object, `readline()` will block until a newline character is received, which can lead to unresponsive applications if the device does not send one.
- breaking Removal of `serial.device()`: The function `serial.device()` for listing ports was removed.
Install
-
pip install pyserial
Imports
- Serial
import serial ser = serial.Serial(...)
- list_ports
from serial.tools import list_ports
Quickstart
import serial
import time
# Configure the serial port
# Replace 'COM3' with your actual serial port ('/dev/ttyUSB0' on Linux, 'COMx' on Windows)
# Ensure baudrate matches your device
ser = serial.Serial(
port='COM_PORT_HERE',
baudrate=9600,
bytesize=serial.EIGHTBITS,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
timeout=1 # Read timeout in seconds
)
try:
if not ser.is_open:
ser.open()
print(f"Serial port {ser.name} opened successfully.")
# Write data (must be bytes in Python 3)
message_to_send = b"Hello, device!\n"
ser.write(message_to_send)
print(f"Sent: {message_to_send.decode().strip()}")
time.sleep(0.1) # Give the device some time to respond
# Read data
received_data = ser.readline() # Reads until newline or timeout
if received_data:
print(f"Received: {received_data.decode().strip()}")
else:
print("No data received within timeout.")
except serial.SerialException as e:
print(f"Serial port error: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
finally:
if ser.is_open:
ser.close()
print("Serial port closed.")