Skip to main content

Serial Reader in Python

The python 3 code below reads all input from the serial port in lines and prints it:

import serial

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

    serial_device.close()

if __name__ == "__main__":
    read_serial()

In order for the code to function the python pyserial module is needed.

pip install pyserial