PySerial

3.5 · active · verified Mon Apr 06

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

Install

Imports

Quickstart

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.

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.")

view raw JSON →