Chapter 24 Ultrasonic Ranging
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
int main(){
printf("Program is starting ... \n");
if(wiringPiSetup() == -1){ //when initialize wiring failed, print message to screen
printf("setup wiringPi failed !");
return 1;
}
float distance = 0;
pinMode(trigPin,OUTPUT);
pinMode(echoPin,INPUT);
while(1){
distance = getSonar();
printf("The distance is : %.2f cm\n",distance);
delay(1000);
}
return 1;
}
First, define the pins and the maximum measurement distance.
#define echoPin 5
#define MAX_DISTANCE 220 //define the maximum measured distance
If the module does not return high level, we can not wait forever. So we need to calculate the lasting time
over maximum distance, that is, time Out. timOut= 2*MAX_DISTANCE/100/340*1000000. The constant part
behind is approximately equal to 58.8.
#define timeOut MAX_DISTANCE*60
Subfunction getSonar () function is used to start the ultrasonic module for a measurement, and return the
measured distance with unit cm. In this function, first let trigPin send 10us high level to start the ultrasonic
module. Then use pulseIn () to read ultrasonic module and return the duration of high level. Finally calculate
the measured distance according to the time.
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;
}