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.
pip install pyserialVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to open, configure, write to, and read from a serial port using PySerial. It includes error handling and ensures the port is closed. Remember to replace `'COM_PORT_HERE'` with your actual serial port name and adjust `baudrate` as needed for your device. Data sent and received must be handled as `bytes` in Python 3.
Ensure all data written to the serial port is encoded as `bytes` (e.g., `b'your data'` or `my_string.encode('utf-8')`). Data read from the port will also be `bytes` and may need to be decoded (`received_data.decode('utf-8')`).For asynchronous serial communication, install the separate `pyserial-asyncio` library (`pip install pyserial-asyncio`) and use its API.
Use `ser.in_waiting` (integer, number of bytes in input buffer) instead of `ser.inWaiting()` and `ser.is_open` (boolean) instead of `ser.isOpen()`.
Always set a `timeout` parameter (e.g., `timeout=1`) when initializing `serial.Serial`. This will cause `readline()` to return after the specified duration if no data or newline is received.
Use `serial.tools.list_ports` module for port enumeration. For example, `from serial.tools import list_ports; ports = list_ports.comports()`.
Ensure the serial port name is correct and the physical (or virtual) device is connected. On Windows, ports are typically 'COM1', 'COM2', etc. On Linux/macOS, they are usually '/dev/ttyUSB0', '/dev/ttyACM0', '/dev/ttyS0', etc. You can list available ports using `from serial.tools import list_ports; for port in list_ports.comports(): print(port.device)`.
Verify that the `port` string provided to `serial.Serial()` exactly matches an existing serial port on your system (e.g., `/dev/ttyUSB0` on Linux, `COM1` on Windows). Use `serial.tools.list_ports.comports()` to programmatically list available ports. Ensure the user running the application has appropriate permissions to access the serial port (e.g., is part of the `dialout` group on Linux). If running in a container or VM, ensure serial devices are correctly mapped or virtual ports are set up.