Skip to main content

Serial Reader in Python

Pascal Spörri
Author
Pascal Spörri
Table of Contents

Reading from a serial port is a common task when working with microcontrollers, sensors, or embedded systems. Below is a simple Python 3 script that continuously reads lines from a serial port and prints them to the console:

import serial

def read_serial(device="/dev/ttyUSB0", speed="115200", func=lambda x: print(x)):
    serial_device = serial.Serial(device, speed)
    try:
        while True:
            line = serial_device.readline()
            func(line.decode('utf-8'))
    finally:
        serial_device.close()

if __name__ == "__main__":
    read_serial()

Installation
#

To run this script, you need to install the pyserial library. You can do this using pip:

pip install pyserial

How It Works
#

  • The read_serial function opens the specified serial port (/dev/ttyUSB0 by default) at a baud rate of 115200.
  • It reads incoming data line by line using readline() and decodes it from UTF-8 before passing it to a handler function (func), which by default just prints it.
  • The try/finally block ensures that the serial port is closed properly if the loop is interrupted.

You can customize the device, speed, or func parameters to fit your setup or to process the input differently.