How to measure distance with a Raspberry Pi?

Introduction

The distance sensor (also called an ultrasonic sensor) allows you to measure distance.
It can estimate distances ranging from 2 cm to 400 cm with an accuracy of 3 mm.
It is the most commonly used and cheapest distance sensor available.
There are much more precise sensors, but they are also much more expensive.

You can purchase one here or find it included in this kit.

In this lesson, we will see how to measure distance using a Raspberry Pi.
Here is the wiring diagram for connecting the HC-SR04 sensor to the Raspberry Pi:

Here is the Python program that reads the distance measurement.
To add it, you need to create a new file like this:

To run the program, you can type the following command:

You can see the distance measured by the sensor to an object in the Raspberry Pi terminal: