Learn how to use Ultrasonic Distance Sensor in Raspberry Pi. Also, learn how to measure distance using HC-SR04 Ultrasonic Sensor in Raspberry Pi. We will be using Raspberry Pi 3 and HC-SR04 as Ultrasonic Sensor. So, let’s start.
First, let’s start with the basics of the Ultrasonic Distance Sensor HC-SR04.
Operating Voltage: 5V
Range: 2cm to 400cm
Effectual Angle: 15 degree
Trigger Input Signal: 10uS TTL pulse
Accuracy: ~0.3 cm
Step 1: Required Components
Ultrasonic Sensor (HC-SR04) x 1
Breadboard x 1
Raspberry Pi x 1
330 Ω Resistor x 1
470 Ω Resistor x 1
Step 2: Circuit Time
Make the circuit as per given diagram. There are four pins available in Ultrasonic Distance Sensor. Left-sided pin VCC is connected to 5V, Trigger pin is connected to GPIO 4, Echo pin connected to GPIO 17 and GND pin is connected to Raspberry Pi Ground pin. Connect one end of the 330Ω resistor to Echo pin. Then, connect a jumper wire from GPIO 17 to another end of the 330Ω resistor. Now, connect one end of the 470Ω resistor to ground and another end at a point where jumper wire form GPIO 17 is connected to the 330Ω resistor.
Step 3: Code Time
This is code for Ultrasonic Sensor in Raspberry Pi. First import GPIO and time library. Then, declare two pins GPIO 4 for TRIG and GPIO 17 for ECHO. Set TRIG pin as an output pin and ECHO pin in Input pin. Then, initialize sensor by setting TRIG pin low for 2 seconds. After initializing, it will measure the total duration of a pulse. Now, we multiply total duration with speed of sound at sea level. This will give us distance in centimeter and we have also rounded the result up to two decimal places.
Step 4: Run code to Raspberry Pi
Run the Python program in your Raspberry Pi after setting components as per circuit diagram. The Ultrasonic Distance Sensor will give time duration of the pulse to Raspberry Pi and Raspberry Pi will convert the time to distance in centimeter. Screenshot of output is given as below.
For running python code in Raspberry PI, visit: raspberrypi.org/documentation/usage/python/