Skip to content

Instantly share code, notes, and snippets.

@Robotto
Last active September 2, 2024 11:09
Show Gist options
  • Save Robotto/aef4b324106d27ba0ceafdd62898a146 to your computer and use it in GitHub Desktop.
Save Robotto/aef4b324106d27ba0ceafdd62898a146 to your computer and use it in GitHub Desktop.
Pyserial example for receiving multiple values from an arduino
from time import sleep
import serial ### pip install pyserial: https://pypi.org/project/pyserial/
# MAKE SURE THE BAUDRATE MATCHES WITH THE ARDUINO (Serial.begin(115200);)
# ser = serial.Serial("/dev/ttyACM0",115200) #Linux
ser = serial.Serial("COM15", 115200) # Windows
while True:
#sleep(1)
# The arduino is doing something like:
# Serial.print(ax);
# Serial.print(",");
# Serial.print(ay);
# Serial.print(",");
# Serial.println(az);
line = ser.readline().decode("ascii").strip() # read until newline, then convert (decode) the bytearray to a string, and strip the \r\n newline stuff
lineSplit = line.split(",") # split the line into a list
if len(lineSplit) == 3: #A very crude way to check if the data is as expected: did the split result in an array with lenght 3?
# Parse float values and assign variables from the list:
ax = float(lineSplit[0])
ay = float(lineSplit[1])
az = float(lineSplit[2])
print(f"X:{ax}, Y:{ay}, Z:{az}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment