#
# hello.mic.45.py
#
# plot microphone audio
#
# Neil Gershenfeld
# CBA MIT 10/28/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

NX = 190
NY = 500
nloop = 190
nstart = 10
path = []

def idle(parent,canvas):
   global path
   #
   # 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(nstart):
      lo = ord(ser.read())
      hi = ord(ser.read())
   for i in range(nloop):
      lo = ord(ser.read())
      hi = ord(ser.read())
      reading = 256*hi + lo
      value = NY*(1.0-reading/1024.0)
      path.append(3*i)
      path.append(value)
   canvas.delete("path")
   canvas.create_line(path,tag="path",width=3,fill="#00b000")
   parent.after_idle(idle,parent,canvas)

#
# open serial port
#
ser = serial.Serial('/dev/ttyS0',115200)
#ser = serial.Serial('/dev/ttyUSB0',115200)
ser.setDTR()
#
# start plotting
#
root = Tk()
root.title('hello.mic.45.py')
root.bind('q','exit')
canvas = Canvas(root, width=3*NX, height=NY, background='white')
canvas.pack()
root.after(100,idle,root,canvas)
root.mainloop()
