The HC-SR04 Ultrasonic Sensor is a very affordable proximity/distance sensor that has been used mainly for object avoidance in various robotics projects . It essentially gives your Raspberry Pi eyes / spacial awareness and can prevent your robot from crashing or falling off a table. It has also been used in turret applications, water level sensing, and even as a parking sensor. This simple project will use the HC-SR04 sensor with Raspberry Pi and a Processing sketch to provide a neat little interactive display on your computer screen.
- Raspberry Pi
- ULTRASONIC Sensor
- 330 Ohm Resistor
- 470 Ohm Resistor
Code - Blocks
Code - Python
Create new python file Ultrasonic.py and enter following code. To run the code, open the terminal and go to directory where you code is located and enter the command " sudo python Ultrasonic.py " and hit enter.
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(20, GPIO.OUT) GPIO.setup(26, GPIO.IN) while True: GPIO.output(20,False) time.sleep(2) GPIO.output(20,True) time.sleep(0.00001) GPIO.output(20,False) while GPIO.input(26)==0: pulse_start = time.time() while GPIO.input(26)==1: pulse_end = time.time() pulse_duration = pulse_end - pulse_start distance =pulse_duration * 17150 print(str('Distance :') + str(round(distance, 2)))