# First attempt at plotting serial data # JFDuval 20/11/2013 # ------------------------------------- # # References/examples/credits: # Neil Gershenfeld 'term.py' http://academy.cba.mit.edu/classes/embedded_programming/term.py # Eli Bendersky 'matplotlib with wxPython GUIs' http://eli.thegreenplace.net/2008/08/01/matplotlib-with-wxpython-guis/ # ------------------------------------- # import serial import struct import matplotlib.pyplot as plt DEFAULT_PORT = '/dev/ttyUSB1' DEFAULT_BAUD = 38400 ser = serial.Serial(DEFAULT_PORT, DEFAULT_BAUD, timeout = 1) def print_byte(): wait = ser.inWaiting() if (wait != 0): byte = ser.read() print byte + '0' def print_uint16(): wait = ser.inWaiting() if (wait >= 2): b_str = ser.read(2) val = struct.unpack('h',b_str)[0] print val def get_uint16(): wait = ser.inWaiting() if (wait >= 2): b_str = ser.read(2) val = struct.unpack('h',b_str)[0] return val if __name__ == '__main__': buf = [0] * 101 x = range(101) plt.ion() fig = plt.figure() ax = fig.add_subplot(111) line1, = ax.plot(x, buf, 'r-') # Returns a tuple of line objects, thus the comma index = 0 while(1): wait = ser.inWaiting() if (wait >= 2): b_str = ser.read(2) val = struct.unpack('h',b_str)[0] #Circular buffer if index < 100: buf[index] = val index = index + 1 else: buf = buf[1:] buf.append(val) print val #Refresh graph line1.set_ydata(buf) fig.canvas.draw() ax.axis([0, 100, min(buf), max(buf)])