#
# Ben's semi-random waveform graphing program
# based on Gershenfeld's hello.SPU0414HR5H.py
#
# Neil Gershenfeld 11/17/15
# (c) Massachusetts Institute of Technology 2015
#
# This work may be reproduced, modified, distributed,
# performed, and displayed for any purpose. Copyright is
# retained and must be preserved. The work is provided
# as is; no warranty is provided, and users accept all 
# liability.
#

from tkinter import *
import math
import random
import time

NX = 500 
NY = 500
nloop = 100
path = []
loop_int = 0
baseline = 0
baseline_filt = 0.01
gain = 5
looptime = 0
waittime = 0.5

def idle(parent,canvas):
    global path, baseline
    #
    # idle routine
    #
    
    # Grab the current time
    looptime = time.process_time()
    path = []
    # Make up a number
    loop_int = random.randint(1,nloop)
    for i in range(nloop):
        # Give a vaguely-sinusoidal reading
        reading = math.floor(gain * (math.sin(i * loop_int) + 2 * random.random() * math.sin(i * loop_int * random.random())))
        baseline = baseline_filt*reading + (1-baseline_filt)*baseline
        value = NY/2 + gain*(reading - baseline)
        path.append(i*NY/float(nloop))
        path.append(value)
    canvas.delete("path")
    canvas.create_line(path,tag="path",width=3,fill="#00b000")
    # Wait to check that waittime has elapsed
    while (time.process_time() - looptime) < waittime:
        continue
    parent.after_idle(idle,parent,canvas)
  
#
# start plotting
#
root = Tk()
root.title('random_graphs.py')
root.bind('q','exit')
canvas = Canvas(root, width=NX, height=NY, background='white')
canvas.pack()
root.after(100,idle,root,canvas)
root.mainloop()