#
# 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
import tkFont

NX = 190
NY = 500
nloop = 190
nstart = 10

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
   counter =0
   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)
      if value > 400:
          counter = counter+1

   count_text = "%i screams" % counter
   canvas.itemconfigure("text", text=count_text)
   
   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('how many screams')
root.bind('q','exit')
helv36 = tkFont.Font (family="Helvetica",size=72, weight="bold")
canvas = Canvas(root, width=3*NX, height=NY, background='white')
canvas.create_text(0.5*NY,0.5*NX,text="0 screams",fill="#FF0066",font=helv36,tags="text")
canvas.pack()
root.after(100,idle,root,canvas)
root.mainloop()

