21. Chapter Ultrasonic Ranging

In this chapter, we learn a module which use ultrasonic to measure distance.

21.1. Project Ultrasonic Ranging

In this project, we use ultrasonic ranging module to measure distance, and print out the data in the terminal.

21.1.1. Component List

  1. Raspberry Pi (with 40 GPIO) x1

  2. GPIO Extension Board & Ribbon Cable x1

  3. Breadboard x1

Jumper Wires x4

jumper-wire

Ultrasonic Module x1

Ultrasonic_Module

Resistor 1kΩ x3

res-1K-hori

21.1.2. Component Knowledge

The Ultrasonic Ranging Module uses the principle that ultrasonic waves will be reflected when they encounter any obstacles. This is possible by counting the time interval between when the ultrasonic wave is transmitted to when the ultrasonic wave reflects back after encountering an obstacle. Time interval counting will end after an ultrasonic wave is received, and the time difference (delta) is the total time of the ultrasonic wave’s journey from being transmitted to being received. Because the speed of sound in air is a constant, and is about v=340m/s, we can calculate the distance between the Ultrasonic Ranging Module and the obstacle: s=vt/2.

../../../_images/Ultrasonic_knowledge.png
\[\quad \boldsymbol{2S = V \cdot t}\]

The Ultrasonic Ranging Module integrates a both an ultrasonic transmitter and a receiver. The transmitter is used to convert electrical signals (electrical energy) into high frequency (beyond human hearing) sound waves (mechanical energy) and the function of the receiver is opposite of this. The picture and the diagram of the Ultrasonic Ranging Module are shown below:

Ultrasonic_Module

HC_SR04

Pin description:

VCC

power supply pin

Trig

trigger pin

Echo

Echo pin

GND

GND

Technical specs:

Working voltage: 5V

Working current: 12mA

Minimum measured distance: 2cm

Maximum measured distance: 200cm

Instructions for Use: output a high-level pulse in Trig pin lasting for least 10uS, the module begins to transmit ultrasonic waves. At the same time, the Echo pin is pulled up. When the module receives the returned ultrasonic waves from encountering an obstacle, the Echo pin will be pulled down. The duration of high level in the Echo pin is the total time of the ultrasonic wave from transmitting to receiving, s=vt/2. This is done constantly.

../../../_images/signal.png

21.1.3. Circuit

Note that the voltage of ultrasonic module is 5V in this circuit.

Schematic diagram

Ultrasonic_Sc

Hardware connection. If you need any support,please feel free to contact us via:

support@freenove.com

Ultrasonic_Fr

21.1.4. Code

21.1.4.1. C Code UltrasonicRanging

First, observe the project result, and then learn about the code in detail.

Hint

If you have any concerns, please contact us via: support@freenove.com

  1. Use cd command to enter 21.1.1_UltrasonicRanging directory of C code.

$ cd ~/Freenove_Kit/Code/C_Code/21.1.1_UltrasonicRanging
  1. Use following command to compile “UltrasonicRanging.c” and generate executable file UltrasonicRanging.

$ gcc UltrasonicRanging.c -o UltrasonicRanging -lwiringPi
  1. Then run the generated file UltrasonicRanging.

$ sudo ./UltrasonicRanging

After the program is executed, aim the Ultrasonic Ranging Module’s detectors (“eyes”) perpendicular to the surface of an object (try using your hand). The distance between the ultrasonic module and the object will be displayed in the terminal. As is shown below:

../../../_images/distance.png

The following is the program code:

 1#include <wiringPi.h>
 2#include <stdio.h>
 3#include <sys/time.h>
 4
 5#define trigPin 4       
 6#define echoPin 5
 7#define MAX_DISTANCE 220        // define the maximum measured distance
 8#define timeOut MAX_DISTANCE*60 // calculate timeout according to the maximum measured distance
 9//function pulseIn: obtain pulse time of a pin
10int pulseIn(int pin, int level, int timeout);
11float getSonar(){   //get the measurement result of ultrasonic module with unit: cm
12    long pingTime;
13    float distance;
14    digitalWrite(trigPin,HIGH); //send 10us high level to trigPin 
15    delayMicroseconds(10);
16    digitalWrite(trigPin,LOW);
17    pingTime = pulseIn(echoPin,HIGH,timeOut);   //read plus time of echoPin
18    distance = (float)pingTime * 340.0 / 2.0 / 10000.0; //calculate distance with sound speed 340m/s
19    return distance;
20}
21
22int main(){
23    printf("Program is starting ... \n");
24    
25    wiringPiSetup();
26    
27    float distance = 0;
28    pinMode(trigPin,OUTPUT);
29    pinMode(echoPin,INPUT);
30    while(1){
31        distance = getSonar();
32        printf("The distance is : %.2f cm\n",distance);
33        delay(1000);
34    }   
35    return 1;
36}

First, define the pins and the maximum measurement distance.

1#define trigPin 4
2#define echoPin 5
3#define MAX_DISTANCE 220        //define the maximum measured distance

If the module does not return high level, we cannot wait for this forever, so we need to calculate the time period for the maximum distance, that is, time Out. timeOut= 2*MAX_DISTANCE/100/340*1000000. The result of the constant part in this formula is approximately 58.8.

1#define timeOut MAX_DISTANCE*60

Subfunction getSonar() function is used to start the Ultrasonic Module to begin measurements and return the measured distance in cm units. In this function, first let trigPin send 10us high level to start the Ultrasonic Module. Then use pulseIn() to read the Ultrasonic Module and return the duration time of high level. Finally, the measured distance according to the time is calculated.

 1float getSonar(){   //get the measurement result of ultrasonic module with unit: cm
 2    long pingTime;
 3    float distance;
 4    digitalWrite(trigPin,HIGH); //send 10us high level to trigPin 
 5    delayMicroseconds(10);
 6    digitalWrite(trigPin,LOW);
 7    pingTime = pulseIn(echoPin,HIGH,timeOut);   //read plus time of echoPin
 8    distance = (float)pingTime * 340.0 / 2.0 / 10000.0; //calculate distance with sound speed 340m/s
 9    return distance;
10}

Lastly, in the while loop of main function, get the measurement distance and display it continually.

1while(1){
2    distance = getSonar();
3    printf("The distance is : %.2f cm\n",distance);
4    delay(1000);
5}   

About function pulseIn() :

int pulseIn(int pin, int level, int timeout);

Return the length of the pulse (in microseconds) or 0 if no pulse is completed before the timeout (unsigned long).