#
# hello.temp.45.test.py
#
# receive and display temperature
# hello.temp.45.py serial_port
#
# Neil Gershenfeld
# CBA MIT 3/27/12
#
#
# (c) Massachusetts Institute of Technology 2012
# Permission granted for experimental and personal use;
# license for commercial sale available from MIT
#
# This script adapted by Juan Carlos Perez
# 4/15/12 Fab Lab Sevilla
#
#

from Tkinter import *
from numpy import log
import serial

WINDOW = 400 # window size
CENTER = 0.5*WINDOW
eps = 0.5 # filter time constant
filter = 0.0 # filtered value

def idle(parent,canvas):
   global filter, eps
   #
   # idle routine
   #
   byte2 = 0
   byte3 = 0
   byte4 = 0
   ser.flush()
   while 1:
      #
      # find framing 
      #
      byte1 = byte2
      byte2 = byte3
      byte3 = byte4
      byte4 = ord(ser.read())
      if ((byte1 == 1) & (byte2 == 2) & (byte3 == 3) & (byte4 == 4)):
         break
   low = ord(ser.read())
   high = ord(ser.read())
   value = 256*high + low
   #if (value > 511):
   #value -= 1024
   V = 2.5 - value*5.0/(20.0*512.0)
   R = 10000.0/(5.0/V-1.0)
   # NHQ103B375R5
   # R25 10000 (O)
   # B (25/85) 3750 (K)
   # R(T(C)) = R(25)*exp(B*(1/(T(C)+273.15)-(1/(25+273.15))))
   B = 3750.0
   R25 =  10000.0
   T = 1.0/(log(R/R25)/B+(1/(25.0+273.15))) - 273.15
   filter = (1-eps)*filter + eps*T
   x = int(.2*WINDOW + (.9-.2)*WINDOW*(filter-20.0)/10.0)
   x2 = .25*x
   x3 = .15*x
   canvas.itemconfigure("text6",text="%s"%T)
   canvas.itemconfigure("text",text="%.2f C"%filter)
   canvas.coords('rect',CENTER-x2+50, CENTER-x2-25, CENTER+x2+50, CENTER+x2-25)
   canvas.update()
   parent.after_idle(idle,parent,canvas)

#
#  check command line arguments
#
if (len(sys.argv) != 2):
   print "command line: hello.temp.45.py serial_port"
   sys.exit()
port = sys.argv[1]
#
# open serial port
#
ser = serial.Serial(port,9600)
ser.setDTR()
#
# start plotting
#
root = Tk()
root.title('Sensor de temperatura (x to exit)')
root.bind('x','exit')
# Cambio titulo de ventana y caracter de salida
canvas = Canvas(root, width=WINDOW*1.5, height=WINDOW, background='pink')
# cambio el tamano de ancho y cambiando fondo de ventana
canvas.create_text(WINDOW,.5*WINDOW,text=".33",font=("Arial", 25),tags="text",fill="black")
canvas.create_text(.75*WINDOW,.15*WINDOW, text="Sensor de temperatura",font=("Helvetica", 25), fill="black")
canvas.create_text(.75*WINDOW,.8*WINDOW, text='''Juan Carlos Perez Juidias
class12 interfaces & applications
Prueba con varias lineas''',font=("Helvetica", 14), fill="#009900")
canvas.create_rectangle(400,300,500,400, tags='rect', fill='#009900', outline='black')
canvas.pack()
root.after(100,idle,root,canvas)
root.mainloop()
