Skip to content

Instantly share code, notes, and snippets.

@fcgomes92
Created May 11, 2017 14:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fcgomes92/861c922c5573706ee0a5f078bbdb871a to your computer and use it in GitHub Desktop.
Save fcgomes92/861c922c5573706ee0a5f078bbdb871a to your computer and use it in GitHub Desktop.
Read / Write some serial data
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