# # hello.HC-SR04.py # # HC-SR04 sonar hello-world # hello.HC-SR04.py serial_port # # Neil Gershenfeld 11/15/15 # (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 import sys prev_value = 0 def main(): global prev_value # 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 abs(value - prev_value) > 10: print(value) prev_value = value # check command line arguments if (len(sys.argv) != 2): print "command line: hello.HC-SR04.py serial_port" sys.exit() port = sys.argv[1] # open serial port ser = serial.Serial(port, 9600) ser.setDTR() while 1: main()