public
Created

Display analog data from Arduino using Python (matplotlib)

  • Download Gist
showdata.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
################################################################################
# showdata.py
#
# Display analog data from Arduino using Python (matplotlib)
#
# electronut.in
#
################################################################################
 
import sys, serial
import numpy as np
from time import sleep
from collections import deque
from matplotlib import pyplot as plt
 
# class that holds analog data for N samples
class AnalogData:
# constr
def __init__(self, maxLen):
self.ax = deque([0.0]*maxLen)
self.ay = deque([0.0]*maxLen)
self.maxLen = maxLen
 
# ring buffer
def addToBuf(self, buf, val):
if len(buf) < self.maxLen:
buf.append(val)
else:
buf.pop()
buf.appendleft(val)
 
# add data
def add(self, data):
assert(len(data) == 2)
self.addToBuf(self.ax, data[0])
self.addToBuf(self.ay, data[1])
# plot class
class AnalogPlot:
# constr
def __init__(self, analogData):
# set plot to animated
plt.ion()
self.axline, = plt.plot(analogData.ax)
self.ayline, = plt.plot(analogData.ay)
plt.ylim([0, 1023])
 
# update plot
def update(self, analogData):
self.axline.set_ydata(analogData.ax)
self.ayline.set_ydata(analogData.ay)
plt.draw()
 
# main() function
def main():
# expects 1 arg - serial port string
if(len(sys.argv) != 2):
print 'Example usage: python showdata.py "/dev/tty.usbmodem411"'
exit(1)
 
#strPort = '/dev/tty.usbserial-A7006Yqh'
strPort = sys.argv[1];
 
# plot parameters
analogData = AnalogData(100)
analogPlot = AnalogPlot(analogData)
 
print 'plotting data...'
 
# open serial port
ser = serial.Serial(strPort, 9600)
while True:
try:
line = ser.readline()
data = [float(val) for val in line.split()]
#print data
if(len(data) == 2):
analogData.add(data)
analogPlot.update(analogData)
except KeyboardInterrupt:
print 'exiting'
break
# close serial
ser.flush()
ser.close()
 
# call main
if __name__ == '__main__':
main()

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.