-
-
Save brazen-paradox/347bebac053feb8bc12cfd68eb29de28 to your computer and use it in GitHub Desktop.
Reading from a serial port in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import serial | |
from argparse import ArgumentParser | |
parser = ArgumentParser(description="UART reader for python enabled devices") | |
# positional arguments | |
parser.add_argument("device_location", help='device location through which serial data is communicated. Eg. dev/ttyACM0') | |
parser.add_argument("baud_rate", help='Baud rate in which serial data is communicated. Eg. 9600') | |
args = parser.parse_args() | |
# this port address is for the serial tx/rx pins on the GPIO header | |
SERIAL_PORT = args.device_location | |
# be sure to set this to the same rate used on the other device | |
SERIAL_RATE = args.baud_rate | |
def main(): | |
ser = serial.Serial(SERIAL_PORT, SERIAL_RATE) | |
while True: | |
# using ser.readline() assumes each line contains a single reading | |
# sent using Serial.println() on the Arduino | |
reading = ser.readline().decode('utf-8') | |
# reading is a string...do whatever you want from here | |
print(reading) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment