""" hello.light.44.py receive and display light level hello.light.44.py serial_port Orignal author: Neil Gershenfeld (CBA MIT) Modified by Alex Berke (c) Massachusetts Institute of Technology 2009 Permission granted for experimental and personal use; license for commercial sale available from MIT """ from tkinter import * import serial GUI_WIDTH = 650 GUI_HEIGHT = .25*GUI_WIDTH # The light measurement is shown in a rectangular bar. MEASUREMENT_RECT_X0 = 0.2*GUI_WIDTH MEASUREMENT_RECT_X1 = 0.9*GUI_WIDTH MEASUREMENT_RECT_Y0 = 0.45*GUI_HEIGHT MEASUREMENT_RECT_Y1 = 0.75*GUI_HEIGHT EPS = 0.5 # FILTER time constant FILTER = 0.0 # FILTERed value def idle(parent, canvas): """ Handles receiving serial messages from the microcontroller which sends information about light intensity read from the phototransistor. The message sent is framed by a prefix sequence: 1, 2, 3, 4 The message that follows is the ADC low byte and then the ADC high byte. """ 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 FILTER = (1-EPS)*FILTER + EPS*value x = int(MEASUREMENT_RECT_X0 + (MEASUREMENT_RECT_X1 - MEASUREMENT_RECT_X0)*FILTER/1024.0) canvas.itemconfigure('measurement', text='%.1f' % FILTER) canvas.coords('rect1', MEASUREMENT_RECT_X0, MEASUREMENT_RECT_Y0, x, MEASUREMENT_RECT_Y1) canvas.coords('rect2', x, MEASUREMENT_RECT_Y0, MEASUREMENT_RECT_X1, MEASUREMENT_RECT_Y1) canvas.update() parent.after_idle(idle, parent, canvas) # # check command line arguments # if (len(sys.argv) != 2): print('command line: hello.light.44.py serial_port') sys.exit() port = sys.argv[1] # # open serial port # ser = serial.Serial(port, 9600) ser.setDTR() # # set up GUI # root = Tk() root.title('hello.light.44.py (q to exit)') root.bind('q', 'exit') canvas = Canvas(root, width=GUI_WIDTH, height=GUI_HEIGHT, background='black') canvas.create_text(.55*GUI_WIDTH, .2*GUI_HEIGHT, text='LIGHT MEASUREMENT', font=('Helvetica', 18), tags='title', fill='white') canvas.create_text(.1*GUI_WIDTH, MEASUREMENT_RECT_Y0 + (MEASUREMENT_RECT_Y1 - MEASUREMENT_RECT_Y0)/2, text='.33', font=('Helvetica', 18), tags='measurement', fill='white') # start x x = MEASUREMENT_RECT_X0 + 0.1*GUI_WIDTH canvas.create_rectangle(MEASUREMENT_RECT_X0, MEASUREMENT_RECT_Y0, x, MEASUREMENT_RECT_Y1, tags='rect1', fill='black', outline='white') canvas.create_rectangle(x, MEASUREMENT_RECT_Y0, MEASUREMENT_RECT_X1, MEASUREMENT_RECT_Y1, tags='rect2', fill='white', outline='white') canvas.pack() # # start idle loop # root.after(100, idle, root, canvas) print('HELLO LIGHT') root.mainloop()