from Tkinter import *
import serial

window_width = 600 # window width
number_of_samples = 100.0 # number of samples taken

port = "/dev/ttyUSB0"
#
# open serial port with supplied port and baud rate. My serial is running in 4800 baud
#
serial = serial.Serial(port, 4800)
serial.setDTR()

def idle(parent,canvas):

   # crears all the serial data at once
   serial.flush()
   #create a variable to hold the data from the serial
   text = ""
   #keep looping over the serial data
   while 1:
      #read serial char
      data =  serial.read()
      # if you find an enter, break the loop
      if (data == '\n'):
         break
          #otherwise keep contacting the string
      text += data
       # convert the string to an integer
   value = int(text)
   print value
   x = int(.2 * window_width + (.9 - .2) * window_width * value / 1024.0)
   canvas.itemconfigure("text",text="%.1f"%value)
   # change the size of the rectangle according to the value
   canvas.coords('rect1', .2 * window_width, .05 * window_width, x, .2 * window_width)
   canvas.coords('rect2', x, .05 * window_width, .9 * window_width, .2 * window_width)
   canvas.update()
   parent.after_idle(idle,parent,canvas)

# set up ui

UI = Tk()
UI.title('hall sensor ui')
UI.bind('q', 'exit')
canvas = Canvas(UI, width=window_width, height=.25 * window_width, background='white')
canvas.create_text(.1 * window_width, .125 * window_width, text=".33", font=("Helvetica", 24), tags="text", fill="#0000b0")
canvas.create_rectangle(.2 * window_width, .05 * window_width, .3 * window_width, .2 * window_width, tags='rect1', fill='#ffff00')
canvas.create_rectangle(.3 * window_width, .05 * window_width, .9 * window_width, .2 * window_width, tags='rect2', fill='#0000ff')
canvas.pack()

# start loop

UI.after(100, idle, UI, canvas)
UI.mainloop()
