#
# hello.step.45.py
#
# receive and display step response
#
# Neil Gershenfeld
# CBA MIT 10/27/07
#
# (c) Massachusetts Institute of Technology 2007
# Permission granted for experimental and personal use;
# license for commercial sale available from MIT
#

from Tkinter import *
import serial
import time
import math

WINDOW = 600
NSAMPLES = 254
MAX = 1040
eps = .9
saveflag = 0
index = 0
path = []
step = []
path_filt = []
step_filt = []
baseline = []

angle = 0.0



def hex2dec(s):
    out = int(s, 16)
    return out


def idle(parent,canvas):
    global index, channel, baseline, path, path_filt, step, step_filt, saveflag, angle



    # get serial Data
    ser.flushInput()
    ser.write("R")

    #time.sleep(0.15)
    #print "in buffer", ser.inWaiting()

    # Wait for return packet with timeout
    a = 0
    while((a < 10000) and (ser.inWaiting() < 12)):
        a = a + 1

    line = ser.readline()
    #print "line:  ", line
    rateW     = hex2dec(line[1:4])
    rateX     = hex2dec(line[4:8])
    rateY     = hex2dec(line[8:12])
    #print rateW, "  ", rateX, "  ", rateY  

    angle2 = math.atan((500.1 - rateY)/(500.1 - rateX)) * (180/math.pi)
    print angle2

    #x = 0.7
    angle += ((rateW-497)/10.0)
    canvas.itemconfigure('pie1', start=angle)
    canvas.itemconfigure('pie2', start=angle2)
    canvas.update()
    parent.after_idle(idle,parent,canvas)



#
# open serial port
#
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=0)
ser.flush()

#
# set up GUI
#
root = Tk()
root.title('hello.step.45.py')
root.bind('q','exit')
canvas = Canvas(root, width=WINDOW, height=WINDOW, background='white')

xy = 50, 50, 250, 250
canvas.create_oval (xy, fill='gray', outline='gray')
canvas.create_arc(xy, start=10, extent=180, tags='pie1', fill='red', outline='red')

xy = 300, 50, 500, 250
canvas.create_oval (xy, fill='gray', outline='gray')
canvas.create_arc(xy, start=10, extent=10, tags='pie2', fill='green', outline='green')

canvas.pack()
root.after(100, idle, root, canvas)
root.mainloop()





