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:
pySerial
: If you don't already have pySerial
installed, you can install it using pip:pip install pyserial
import serial
def read_serial_data(port, baudrate=9600, timeout=1):
# Open the serial port
ser = serial.Serial(port, baudrate, timeout=timeout)
try:
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
try:
numbers = [float(num) for num in numbers]
# Ensure there are exactly three numbers
if len(numbers) == 3:
return numbers
else:
print(f"Expected 3 numbers, got {len(numbers)}: {numbers}")
except ValueError:
print(f"Non-numeric data received: {line}")
else:
print(f"Line not terminated by carriage return: {line}")
finally:
ser.close()
# Example usage
port = 'COM3' # Replace with your serial port ('/dev/ttyS0' for linux)
numbers = read_serial_data(port)
print(f"Received numbers: {numbers}")
serial
module: This is part of the pySerial
library.serial.Serial
function opens the specified serial port with the given baud rate and timeout.ser.readline()
function reads a line from the serial port. It reads until a newline character is encountered.decode('ascii').strip()
part converts the bytes object to a string and removes any surrounding whitespace.'\r'
).finally
block to ensure it is closed even if an error occurs.'COM3'
with the appropriate serial port for your system.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.