Chapter 24 Ultrasonic Ranging
Code
C Code 24.1.1 UltrasonicRanging
First observe the project result, and then analyze the code.
1. Use cd command to enter 24.1.1_UltrasonicRanging directory of C code.
cd ~/Freenove_Ultimate_Starter_Kit_for_Raspberry_Pi/Code/C_Code/24.1.1_UltrasonicRanging
2. Use following command to compile "UltrasonicRanging.c" and generate executable file
"UltrasonicRanging".
gcc UltrasonicRanging.c -o UltrasonicRanging -lwiringPi
3. Then run the generated file "UltrasonicRanging".
sudo ./UltrasonicRanging
After the program is executed, make the detector of ultrasonic ranging module aim at the plane of an object,
then the distance between the ultrasonic module and the object will be displayed in the terminal. As is shown
below:
The following is the program code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <wiringPi.h>
#include <stdio.h>
#include <sys/time.h>
#define trigPin 4
#define echoPin 5
#define MAX_DISTANCE 220 // define the maximum measured distance
#define timeOut MAX_DISTANCE*60 // calculate timeout according to the maximum measured
distance
//function pulseIn: obtain pulse time of a pin
int pulseIn(int pin, int level, int timeout);
float getSonar(){ // get the measurement results of ultrasonic module, with unit: cm
long pingTime;
float distance;
digitalWrite(trigPin,HIGH); //trigPin send 10us high level
delayMicroseconds(10);
digitalWrite(trigPin,LOW);
pingTime = pulseIn(echoPin,HIGH,timeOut); //read plus time of echoPin
distance = (float)pingTime * 340.0 / 2.0 / 10000.0; // the sound speed is 340m/s, and
calculate distance
return distance;
}