Skip to content

Instantly share code, notes, and snippets.

@MercuryRising
Last active December 12, 2015 07:18
Show Gist options
  • Save MercuryRising/4735267 to your computer and use it in GitHub Desktop.
Save MercuryRising/4735267 to your computer and use it in GitHub Desktop.
''' This is adapted from an example I found somewhere, if anyone knows what it is let me know and I'll credit the original '''
import threading
import time
import math
import gobject
import matplotlib
matplotlib.use('GTKAgg')
import matplotlib.pyplot as plt
import random
import serial
import Queue
class Arduino(threading.Thread):
def __init__(self, queue):
''' Threaded arduino reader '''
threading.Thread.__init__(self)
try:
self.baudRate = 115200
self.ser = serial.Serial("/dev/ttyUSB0", self.baudRate)
print 'initiated arduino'
except:
# Couldn't connect, generated random data
self.connected = False
print "Using random data"
self.queue = queue
def run(self):
while True:
if self.connected:
self.ser.flushInput()
self.ser.flushOutput()
while True:
if self.ser.inWaiting() > 0:
'''Parse data here, put it in the queue'''
datax = ser.readline()
# NEEDS to be ints/floats to plot!
self.queue.put(datax)
else:
self.queue.put(random.randint(0,255))
time.sleep(0.5)
def update():
''' Called every updateDelay milliseconds
grabs data from the queue, plots the data'''
global windowLength, q, a, data, f
# Clear our A axis so we don't see everything that we plotted before, but that means we'll have to
# remake our labels
a.cla()
a.set_xlabel("Time (Seconds)")
a.set_ylabel("Value")
while not q.empty():
data.append(q.get())
data.pop(0) # As we initialized our data array, we need to pop off the first entries
x, = a.plot(data, 'b-')
# Auto adjust our plot for our data (just Y)
min_t = min(data)
max_t = max(data)
a.axis([0, windowLength, min_t-10,max_t+10])
f.canvas.draw_idle()
return True
if __name__ == '__main__':
# time in milliseconds to wait before grabbing new data
updateDelay = 100
# Make a queue so we can do the data processing in one thread (reading from arduino) and plot in another
q = Queue.Queue()
# Start the arduino - tries to connect on /dev/ttyUSBX (linux), may need to change port for windows
arduino = Arduino(q)
# Start the thread
arduino.start()
f = plt.figure()
a = f.add_subplot(111)
a.grid(True)
windowLength = 101
data = [0 for x in range(windowLength)]
f.suptitle("Live Plot")
gobject.timeout_add(updateDelay, update)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment