Created
May 11, 2017 14:50
-
-
Save smokinggoats/861c922c5573706ee0a5f078bbdb871a to your computer and use it in GitHub Desktop.
Read / Write some serial data
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 | |
import json | |
import sys | |
ser = serial.Serial( | |
port='/dev/ttyUSB0',\ | |
baudrate=9600,\ | |
parity=serial.PARITY_NONE,\ | |
stopbits=serial.STOPBITS_ONE,\ | |
bytesize=serial.EIGHTBITS,\ | |
timeout=0) | |
print("connected to: " + ser.portstr) | |
option = input("Type 0: ") | |
while option != '-1': | |
#this will store the line | |
line = "" | |
data = {} | |
ser.write(option.encode()) | |
while True: | |
try: | |
c = ser.read().decode() | |
if c: | |
line += c | |
if c == '\n': | |
line = line[:-1].strip() | |
if line == "M01": | |
print("Place the card!") | |
elif line == "M02": | |
# ser.close() | |
print(data) | |
print('Remove the card!') | |
# sys.exit() | |
# exit() | |
break | |
else: | |
try: | |
data = json.loads(line) | |
except Exception: | |
pass | |
line = "" | |
except KeyboardInterrupt: | |
try: | |
ser.close() | |
except Exception: | |
pass | |
option = input("Type 0: ") | |
ser.close() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment