#
# ADC-readout and display 
#
# reads two serial bytes from ADC and displays actual voltage-level
# hello.light.45.py serial_port
#
# modified by Christian Teissl from hello.light.45.py* from Neil Gershenfeld
# CBA MIT 10/24/09
#
# *(c) Massachusetts Institute of Technology 2009
# Permission granted for experimental and personal use;
# license for commercial sale available from MIT
#

from Tkinter import *
import serial

WINDOW = 600 # window size


def idle(parent,canvas):
   #
   # idle routine
   #
   
   low = ord(ser.read())
   high = ord(ser.read())
   x = int (.2*WINDOW + WINDOW* (0.7*high/255))
   volt = float(5.0*high/255.0)
   canvas.itemconfigure("text",text="U = %.2f V"%volt)
   canvas.coords('rect1',.2*WINDOW,.05*WINDOW,x,.2*WINDOW)
   canvas.coords('rect2',x,.05*WINDOW,.9*WINDOW,.2*WINDOW)
   canvas.update()
   parent.after_idle(idle,parent,canvas)

#
#  check command line arguments
#
if (len(sys.argv) != 2):
   print "command line: adc45interface.py serial_port"
   sys.exit()
port = sys.argv[1]

#
# open serial port
#
ser = serial.Serial(port,9600)
ser.setDTR()

#
# set up GUI
#
root = Tk()
root.title('ADC interface (q to exit)')
root.bind('q','exit')
canvas = Canvas(root, width=WINDOW, height=.25*WINDOW, background='grey')
canvas.create_text(.1*WINDOW,.125*WINDOW,text="U = 0.00 V",font=("Helvetica", 16),tags="text",fill="#0000b0")
canvas.create_rectangle(.2*WINDOW,.05*WINDOW,.2*WINDOW,.2*WINDOW, tags='rect1', fill='#0000b0')
canvas.create_rectangle(.2*WINDOW,.05*WINDOW,.9*WINDOW,.2*WINDOW, tags='rect2', fill='#00b000')
canvas.pack()
#
# start idle loop
#
root.after(100,idle,root,canvas)
root.mainloop()