import RPi.GPIO as gpio import time def distance(measure='cm'): try: gpio.setmode(gpio.BOARD) gpio.setup(12, gpio.OUT) gpio.setup(16, gpio.IN) gpio.output(12, False) while gpio.input(16) == 0: nosig = time.time() while gpio.input(16) == 1: sig = time.time() tl = sig - nosig if measure == 'cm': distance = tl / 0.000058 elif measure == 'in': distance = tl / 0.000148 else: print('improper choice of measurement: in or cm') distance = None gpio.cleanup() return distance except: distance = 100 gpio.cleanup() return distance if __name__ == "__main__": print(distance('cm'))
This tutorial covers how to write Python code to work with the HC-sr04 distance sensor.
The distance sensor works by shooting ultrasonic waves, calculating the amount of time between sending the signal and receiving it.
We can use this time, and our knowledge of the speed of sound constant to calculate distance.
It should noted here that the distance sensor works well even on some slants, if the object that you're bouncing sound off of is more than a 33 degree angle, your results are likely to be very inaccurate.
What this script will do for us is convert the sensor time to a distance. For now, we just have it printing out the distance, but we're going to use this script later as an import into our car, so that it can read distances and either be semi-auto-piloted, braking when objects get too close, or we can allow the car to just run on its own until it detects a close object.