graph_plotter.py 2.68 KB
#!/usr/bin/env python

import pyglet
import math
import random
import time
import serial

datafeed = serial.Serial(
 port='/dev/ttyUSB0',
 baudrate = 9600,
 parity=serial.PARITY_NONE,
 stopbits=serial.STOPBITS_ONE,
 bytesize=serial.EIGHTBITS,
 timeout=1
)
 
window = pyglet.window.Window()
window.set_caption("Test graph")

starttime = time.time()
 
title = pyglet.text.Label('Test Graph',
                          font_name='Arkhip',
                          font_size=12,
                          x=window.width//2, y=window.height//2,
                          anchor_x='center', anchor_y='top')

                 
def round_sig(x, sig=2):
    return round(x, sig-int(math.floor(math.log10(abs(x))))-1)
                 
def drawgrid(xlines, ylines, xlimits, ylimits):
    pyglet.gl.glColor4f(0.5, 0.5, 0.5, 1.0) 
    for xpos in range(0, window.width, window.width/xlines):
        pyglet.graphics.draw(2, pyglet.gl.GL_LINES, ('v2i', (xpos, 0, xpos, window.height)))
        tagtext = str(round((xlimits[1]-xlimits[0])*(float(xpos)/window.width) + xlimits[0], 1))
        tag = pyglet.text.Label(tagtext, font_name='Arkhip', font_size=10, x=xpos-2, y=0, anchor_x='right', anchor_y='bottom')
        tag.draw()
    for ypos in range(0, window.width, window.height/ylines):
        pyglet.graphics.draw(2, pyglet.gl.GL_LINES, ('v2i', (0, ypos, window.width, ypos)))
        tagtext = str(round((ylimits[1]-ylimits[0])*(float(ypos)/window.height) + ylimits[0], 1))
        tag = pyglet.text.Label(tagtext, font_name='Arkhip', font_size=10, x=0, y=ypos-2, anchor_x='left', anchor_y='top')
        tag.draw()


def plotline(xdata, ydata):
    pyglet.gl.glColor4f(1, 0, 0, 1.0)
    points = []
    for n in range(max(len(xdata), len(ydata))):
        try:
            xpos = ((xdata[n]-min(xdata))*window.width)/(max(xdata)-min(xdata))
        except:
            xpos = 0
        xpos = int(xpos)
        try:
            ypos = ((ydata[n]-min(ydata))*window.height)/(max(ydata)-min(ydata))
        except:
            ypos = 0
        ypos = int(ypos)
        points.append([xpos, ypos])
    for n in range(len(points)-1):            
        pyglet.graphics.draw(2, pyglet.gl.GL_LINES, ('v2i', (points[n][0], points[n][1], points[n+1][0], points[n+1][1])))


xdata = [0]
ydata = [0]


@window.event
def on_draw():
    window.clear()
    value = datafeed.readline()
    try:
        value = float(value)
        ydata.append(value)

        if len(ydata) > 250:
            del ydata[0]
        xdata.append(round(time.time() - starttime, 3))
        if len(xdata) > 250:
            del xdata[0]
    except:
        pass
    drawgrid(10, 10, [min(xdata), max(xdata)], [min(ydata), max(ydata)])
    plotline(xdata, ydata)


    
pyglet.app.run()