Skip to content

Instantly share code, notes, and snippets.

@OneGneissGuy
Last active March 18, 2021 17:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save OneGneissGuy/3651632db20258fdddfbeda5e5c1e578 to your computer and use it in GitHub Desktop.
Save OneGneissGuy/3651632db20258fdddfbeda5e5c1e578 to your computer and use it in GitHub Desktop.
a script to plot streaming arduino data on a com port
# -*- coding: utf-8 -*-
"""
stream_arduino.py
Stream data from an arduino on a com port
must run %matplotlib
data comes in this format:
12351\r\n
Written by: John Franco Saraceno
"""
import datetime
from drawnow import *
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use("tkAgg")
import logging
import numpy as np
import pandas as pd
import serial
#increase font size and weight for easier plot viewing
font = {'font.weight' : 'bold',
'font.size' : 24}
#update matplotlib fonts
plt.rcParams.update(**font)
#define the serial port of the arduino
serialPort = '/dev/ttyUSB0'
baudRate = 115200
first_data =[]
second_data =[]
N = 480 #number of points to show
cnt = 0
plt.ion()
datetimes=[]
arduinoData = serial.Serial(serialPort, baudRate)
arduinoData.flushInput()
#Create and configure logger
logging.basicConfig(filename="datalogfile.log",
format='%(asctime)s %(message)s',
filemode='w')
logger=logging.getLogger()
logger.setLevel(logging.INFO)
def makeFig(): #Create a function that makes our desired plot
plt.title('Streaming Radiometer Data') #Plot the title
plt.grid(True) #Turn the grid on
plt.ylabel('W/m2',) #Set ylabels
plt.plot(first_data, 'ro-', label='First parameter',) #plot the temperature
plt.legend(loc='upper left') #plot the legend
while True: # While loop that loops forever
try:
arduinoString = arduinoData.readline() #read the line of text from the serial port
#Split the incoming string into an array called dataArray
dataArray = arduinoString.decode('utf-8').rstrip().lstrip().split(',')
first = float(dataArray[0].split(' ')[-1])#Convert first element to floating number and put in temp
logging.info(str(first))
# logging.debug("\t")
first_data.append(first) #Build our tempF array by appending temp readings
drawnow(makeFig) #Call drawnow to update our live graph
plt.pause(.000001) #Pause Briefly. Important to keep drawnow from crashing
cnt = cnt+1
if(cnt>N): #If you have N or more points, delete the first one from the array
first_data.pop(0) #This allows us to just see the last N data points
except KeyboardInterrupt:
print("Keyboard Interrupted the datastream")
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment