Raspberry PI Ultrasonic Control Code

Ultrasonic sensors measure distance with ultrasonic waves. It measures timeframe from emitting sound until receiving the rebounced soundwaves. By knowing the soundspeed (340.29m/s), the ultrasonic controller can calculate the distance in 0.01cm accuracy. You can always ask the current distance between any object and the sensor. This a perfect tool for building small robots.

required hardware
Figure 1 - Raspberry PI with Ultrasonic sensor

Required hardware

  • Raspberry PI
  • Ultrasonic sensor(s)
  • Logic Level Converter(s)

Source code to install on controller


import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)

TRIG = 17
ECHO = 27

print("Distance Measurement In Progress")

GPIO.setup(TRIG, GPIO.OUT)
GPIO.setup(ECHO, GPIO.IN)

try:
    while True:
        GPIO.output(TRIG, False)
        time.sleep(1)
        GPIO.output(TRIG, True)
        time.sleep(0.00001)
        GPIO.output(TRIG, False)

        while GPIO.input(ECHO) == 0:
            pulse_start = time.time()
            while GPIO.input(ECHO) == 1:
                pulse_end = time.time()
   
        pulse_duration = pulse_end - pulse_start
        distance = pulse_duration * 17150
        distance = round(distance, 2)
        print "Distance: ", distance, "cm"

except KeyboardInterrupt:
	GPIO.cleanup()

More information