#
# hello.mic.45.py
#
# plot microphone audio
#    hello.mic.45.py serial_port
#
# Neil Gershenfeld
# CBA MIT 10/31/10
#
# (c) Massachusetts Institute of Technology 2010
# Permission granted for experimental and personal use;
# license for commercial sale available from MIT
#

from Tkinter import *
import serial

NX = 400 
NY = 200
nloop = 100
path = []
baseline = 0
baseline_filt = 0.02
gain = 0.5

def idle(parent,canvas):
   global path, baseline
   #
   # idle routine
   #
   # look for framing
   #
   byte2 = 0
   byte3 = 0
   byte4 = 0
   while 1:
      byte1 = byte2
      byte2 = byte3
      byte3 = byte4
      byte4 = ord(ser.read())
      if ((byte1 == 1) & (byte2 == 2) & (byte3 == 3) & (byte4 == 4)):
         break
   path = []
   for i in range(nloop):
      lo = ord(ser.read())
      hi = ord(ser.read())
      reading = 256*hi + lo
      baseline = baseline_filt*reading + (1-baseline_filt)*baseline
      value = NY/2 + gain*(reading - baseline)
      path.append(i*400/float(nloop))
      path.append(value)
   canvas.delete("path")
   canvas.create_line(path,tag="path",width=3,fill="#38332b")
   parent.after_idle(idle,parent,canvas)

#
#  check command line arguments
#
if (len(sys.argv) != 2):
   print "command line: hello.mic.45.py serial_port"
   sys.exit()
port = sys.argv[1]
#
# open serial port
#
ser = serial.Serial(port,9600)
#
# start plotting
#
root = Tk()
#Set Interface Title
root.title('Joao Milheiro Hello Mic')
# Set x Key to exit
root.bind('x','exit')
#Draw Button to Exit
y = Button(root, text="EXIT", fg="white", command=root.quit, background="#a28356")
#Put Button on the Left side
y.pack(side=LEFT)
#Draw Title inside the interface
w = Canvas(root, width=400, height=50, background ="#bea373")
w.pack()
w.create_text(20, 30, anchor=W, font="Purisa",text="My Input Device assignement Updated") #write text
canvas = Canvas(root, width=NX, height=NY, background='#a28356') #format text
canvas.create_line(200, 0, 200, 200, fill="WHITE", width="2") #draw X axis line
canvas.create_line(0, 100, 400, 100, fill="WHITE", width="2") #draw Y axis line
x=0
while x<400: #draw scale lines along the X axys
	canvas.create_line(10+x, 90, 10+x, 110, fill="WHITE", width="1") #big line 	
	canvas.create_line(20+x, 95, 20+x, 105, fill="WHITE", width="0.5")	#small line
	x = x + 20
y=0
while y<200:#draw scale lines along the Y axys
	canvas.create_line(190, 0+y, 210, 0+y, fill="WHITE", width="1")	#big line
	canvas.create_line(195, 10+y, 205, 10+y, fill="WHITE", width="0.5")	#small line
	y = y + 20
canvas.pack()
canvas.pack(expand = YES, fill = BOTH)
gif1 = PhotoImage(file = 'fab.gif') #Load Fabacademy image
canvas.create_image(300, 120, image = gif1, anchor = NW) # insert image
root.after(400,idle,root,canvas) #Reload sensor path
root.mainloop()
