Programming with the distance sensor (HC-SR04)




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.

The next tutorial:





  • Robotics with the Raspberry Pi
  • Programming GPIO example
  • Running GPIO
  • Building Autonomous / RC car intro
  • Supplies needed
  • Motor Control
  • Connecting the four motors
  • Forward and Reverse
  • Turning
  • Pivoting
  • User Control
  • Remotely controlling the car
  • Adding a distance sensor (HC-SR04)
  • Programming with the distance sensor
  • Autopilot and/or auto-correct
  • Autonomous Beginnings
  • Testing Autonomous Code
  • Streaming video example one
  • Less latency streaming option