Skip to content

Instantly share code, notes, and snippets.

@ajturner
Last active February 25, 2024 21:27
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 ajturner/733638ede7b7982feeb5ef198cd466dd to your computer and use it in GitHub Desktop.
Save ajturner/733638ede7b7982feeb5ef198cd466dd to your computer and use it in GitHub Desktop.
Read data from a serial port and plot
# !pip3 install pyserial
import serial
ser = serial.Serial('/dev/cu.usbmodem1101') # open serial port
print(ser.name) # check which port was really used
ser.close()
data = {}
material = 'Pencil'
ser = serial.Serial('/dev/cu.usbmodem1101', 115200, timeout=10)
# while True:
# # x = ser.read() # read one byte
# # s = ser.read(100) # read up to ten bytes (timeout)
# line = ser.readline() # read a '\n' terminated line
# print(line)
# 5V with 10 bit ADC
conversion = 5/1023
start = False
data = []
index = []
with open(f'sensor_data_{material}.csv', 'wb') as datafile:
while True:
# datafile.write(ser.read(10000))
line = ser.readline()
# if start:
print(line)
datafile.write(line)
try:
value = int(line.strip())
except:
value = -1
# if value > 10:
# start = True
index.append(len(data))
data.append(value * conversion)
# datafile.write(ser.read(10000))
# !pip3 install bokeh
from bokeh.models import Range1d
from bokeh.plotting import figure, show
p = figure(title=f'Testing with: {material}', width=1000, height=800)
p.y_range = Range1d(0, 5) # max 5 volts
# add a circle renderer with a size, color, and alpha
p.line(index,data, line_width=2, color="navy", alpha=0.5)
# show the results
show(p)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment