Interfacing ultrasonic sensor with raspberry pi

Introduction

In this tutorial, we will be looking at how to interface an ultrasonic sensor with the raspberry pi and measure the distance to an object in the surroundings of the sensor.

Required Components

  • Raspberry Pi
  • Ultrasonic sensor(HC-SR04)
  • Jumper cables
  • USB Cable

Circuit Diagram 

Circuit diagram

Explanation

An ultrasonic sensor is an electronic device that measures the distance of a target object by emitting ultrasonic sound waves and converts the reflected sound into an electrical signal. This sensor has two important components, one transmits the waves and the other receives the echo of the transmitted wave and by calculating the time taken for this cycle of transmission and receiving, one can find the distance of the object ahead of the sensor.

For interfacing, the ultrasonic sensor with pi, Connect the sensor with raspberry pi using jumper cables and breadboard according to the above-given circuit diagram. Power up the raspberry pi using the USB cable.

Coming to the coding part, we will be using a library called gpiozero on raspberry pi. Install the library using the command below.

sudo pip3 install gpiozero 

Now, copy and paste the below-given python code and execute it using the terminal on raspberry pi. 

Code

# libraries required for this
from gpiozero import DistanceSensor
from time import sleep

# Initialize ultrasonic sensor as per pin connection diagram given
sensor = DistanceSensor(trigger=18, echo=24)

while True: // making it run for every 3 seconds
# Wait for 3 seconds
sleep(3)

# Getting the distance(in metres)
distance = sensor.distance

# convert it into centimetres by multiplying with 100
distance = sensor.distance * 100

# Rounding it to 2 places
distance = round(sensor.distance, 2)

# Print the distance of an object
print(“Distance: {} cm”.format(sensor.distance))

We have successfully completed how to interface the ultrasonic sensor to raspberry pi and measured distance to an object.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.