Skip to content

Instantly share code, notes, and snippets.

@xiongyihui
Created December 2, 2014 08:08
Show Gist options
  • Save xiongyihui/7b5c7c43d5434055575f to your computer and use it in GitHub Desktop.
Save xiongyihui/7b5c7c43d5434055575f to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import sys, serial
import numpy as np
from collections import deque
from matplotlib import pyplot as plt
# class that holds data for N samples
class DataPoll:
# constr
def __init__(self, maxLen):
self.ax = 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):
self.addToBuf(self.ax, data[0])
# plot class
class DataPlot:
# constr
def __init__(self, data):
# set plot to animated
plt.ion()
self.axline, = plt.plot(data.ax)
plt.ylim([0, 20000])
# update plot
def update(self, data):
self.axline.set_ydata(data.ax)
plt.draw()
# main() function
def main():
# expects 1 arg - serial port string
if(len(sys.argv) != 2):
print 'Usage: python %s /dev/ttyACM0' % sys.argv[0]
exit(1)
# strPort = '/dev/ttyACM0'
strPort = sys.argv[1];
# plot parameters
data = DataPoll(100)
dataPlot = DataPlot(data)
print 'plotting data...'
# open serial port
ser = serial.Serial(strPort, 4000000)
while True:
try:
line = ser.readline()
c = [0]
c[0] = float(line)
data.add(c)
dataPlot.update(data)
except KeyboardInterrupt:
print 'exiting'
break
# close serial
ser.flush()
ser.close()
# call main
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment