Distance measurement using Raspberry Pi and sensor HC-SR04 or US-015

The sensors shown allow for distance measurement by means of ultrasound. The sensor sends a wave, which returns to it after reflection from an obstacle. By calculating the time between sending and receiving the pulse, the distance between the sensor and the object can be determined.

You will need the following elements:

Connection with Raspberry Pi

The two devices shall be combined as shown in the table below

GPIO Raspberry Pi Distance sensor
5 V VCC
GND GND

GPIO 4

Trig

GPIO 1

Echo

Diagram of connection between the ultrasonic sensor and Raspberry Pi.

Support

To use the GPIO pins in Raspberry Pi we need a library that allows us to do so. For this we will use wiringPi. The description how to download and install it can be found here. Just copy the next commands. Finally, to check the installation:

  • gpio readall

After this command we should see the table below:

Now we will write a simple program. Create the file us_015.cpp

  • nano us_015.cpp

The file should contain the following program:

#include 
#include 
#include 
using namespace std;

  int CM;
  long time;
  int trig = 4;
  int echo = 1;
  void measurement_odleglosity();
  int pulseIn(int pin, int level);


int main (void)
{
 wiringPiSetup ();

 pinMode(trig, OUTPUT);
 pinMode(echo, INPUT);

 cout <<"Distance sensor test"< t0.tv_sec) micros = 1000000L; other micros = 0;

      micros += (tn.tv_usec - t0.tv_usec);

      if (micros > 10000) return 0;
   }

   gettimeofday;

   while (digitalRead(pin) === level)
   {
      gettimeofday(&tn, NULL);

      if (tn.tv_sec > t0.tv_sec) micros = 1000000L; other micros = 0;

      micros = micros + (tn.tv_usec - t0.tv_usec);

      if (micros > 10000) return 0;
   }

   if (tn.tv_sec > t1.tv_sec) micros = 1000000L; other micros = 0;
   micros = micros + (tn.tv_usec - t1.tv_usec);

   return micros;
}

Then save the changes to the file and close it. To compile the created file we use the command:

  • g++ -Wall -o us_015.o us_015.cpp -lwiringPi

Operation of the programme

To calculate the distance from the object, the response time is divided by 58 (according to documentation). Why that? This value comes from the formula:

TIME / [1/(0.34 / 2 )/10]

  • the value in square brackets is 58:
    • 0.34 - wave speed in m/ms (340 m/s) divided by 2 (because the wave travelled in both directions).
    • Additionally, everything divisible by 10 to convert millimeters into centimeters

The program is started with the following command:

  • sudo ./us_015.o

The result of the program can be viewed on the monitor:

Screenshot of the monitor.

Botland.store - shop for makers!