How to read 3 decimal numbers with an ending carriage return on the serial port in Python ?

Reading three decimal numbers terminated by a carriage return from a serial port in Python can be done using the pySerial library. Here is a step-by-step guide on how to achieve this:

  1. Install pySerial: If you don't already have pySerial installed, you can install it using pip:
pip install pyserial
  1. Reading from the Serial Port: Below is a Python script to read three decimal numbers separated by spaces or commas from the serial port, terminated by a carriage return.
import serial

def read_serial_data(port, baudrate=9600, timeout=1):
    # Open the serial port
    ser = serial.Serial(port, baudrate, timeout=timeout)
        while True:
            # Read a line from the serial port
            line = ser.readline().decode('ascii').strip()
            # Check if the line is terminated by a carriage return
            if line.endswith('\r'):
                # Remove the carriage return
                line = line[:-1]
                # Split the line into numbers
                # For separators other than spaces, set line.split('separator'),
                # For example line.split(',') for comma-separated numbers
                numbers = line.split()
                # Convert the split strings to floats
                    numbers = [float(num) for num in numbers]
                    # Ensure there are exactly three numbers
                    if len(numbers) == 3:
                        return numbers
                        print(f"Expected 3 numbers, got {len(numbers)}: {numbers}")
                except ValueError:
                    print(f"Non-numeric data received: {line}")
                print(f"Line not terminated by carriage return: {line}")


# Example usage
port = 'COM3'  # Replace with your serial port ('/dev/ttyS0' for linux)
numbers = read_serial_data(port)
print(f"Received numbers: {numbers}")


  1. Import the serial module: This is part of the pySerial library.
  2. Open the serial port: The serial.Serial function opens the specified serial port with the given baud rate and timeout.
  3. Read a line from the serial port: The ser.readline() function reads a line from the serial port. It reads until a newline character is encountered.
  4. Decode and strip the line: The decode('ascii').strip() part converts the bytes object to a string and removes any surrounding whitespace.
  5. Check for a carriage return: The script checks if the line ends with a carriage return ('\r').
  6. Remove the carriage return and split the line: The carriage return is removed, and the line is split into individual numbers.
  7. Convert to floats: The script attempts to convert the split strings to floats.
  8. Ensure there are three numbers: The script verifies that exactly three numbers have been read.
  9. Close the serial port: The serial port is closed in the finally block to ensure it is closed even if an error occurs.


  • Replace 'COM3' with the appropriate serial port for your system.
  • Adjust the baudrate and timeout parameters as needed for your specific serial device.

This script will continuously read from the serial port and return the three decimal numbers once it receives a valid line of data terminated by a carriage return.