# # distance-direction.py # # Distance and Directional sensor # distance-direction-sensor.py serial_port # # Neil Gershenfeld & Ravi Tejwani # # (c) Massachusetts Institute of Technology 2015 # # This work may be reproduced, modified, distributed, # performed, and displayed for any purpose. Copyright is # retained and must be preserved. The work is provided # as is; no warranty is provided, and users accept all # liability. # from Tkinter import * import serial WINDOW = 800 # window size filt = 0 eps = 0.1 cm_pre = 0 def idle(parent,canvas): global filt,eps,cm_pre # # 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) filt = (1-eps)*filt+eps*value us = filt/8.0 # 8 MHz counter cm = us/58.0 velocity = (cm-cm_pre)*10 cm_pre = cm x = int(.2*WINDOW + (.9-.2)*WINDOW*cm/50) y = int(.2*WINDOW + (.9-.2)*WINDOW*velocity/500) canvas.itemconfigure("text_cm",text="%.0f cm"%cm) canvas.itemconfigure("text_vel",text="%.0f vel"%velocity) canvas.coords('rect1',.2*WINDOW,.05*WINDOW,x,.2*WINDOW) canvas.coords('rect2',x,.05*WINDOW,.9*WINDOW,.2*WINDOW) canvas.coords('rect3',.2*WINDOW,.25*WINDOW,y,.4*WINDOW) canvas.coords('rect4',y,0.25*WINDOW,.9*WINDOW,.4*WINDOW) canvas.update() parent.after_idle(idle,parent,canvas) # # check command line arguments # if (len(sys.argv) != 2): print "command line: distance-direction-sensor.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('distance-direction-sensor.py (q to exit)') root.bind('q','exit') canvas = Canvas(root, width=WINDOW, height=.50*WINDOW, background='white') canvas.create_text(.1*WINDOW,.125*WINDOW,text=".33",font=("Helvetica", 24),tags="text_cm",fill="#0000b0") canvas.create_rectangle(.2*WINDOW,.05*WINDOW,.3*WINDOW,.2*WINDOW, tags='rect1', fill='#b00000') canvas.create_rectangle(.3*WINDOW,.05*WINDOW,.9*WINDOW,.2*WINDOW, tags='rect2', fill='#0000b0') canvas.create_text(.1*WINDOW,.325*WINDOW,text=".33",font=("Helvetica", 24),tags="text_vel",fill="#0000b0") canvas.create_rectangle(.2*WINDOW,.25*WINDOW,.3*WINDOW,.4*WINDOW, tags='rect3', fill='#b00000') canvas.create_rectangle(.3*WINDOW,.25*WINDOW,.9*WINDOW,.4*WINDOW, tags='rect4', fill='#0000b0') canvas.pack() # # start idle loop # root.after(100,idle,root,canvas) root.mainloop()