Skip to main content
Editing Step 4 —

Step Type:

Drag to rearrange

This first function is used for finding the distance between the sensor and nearest object through the defined variables, trigPin and echoPin. This is before the set-up. The start of the function, float getdistance (int trigPin, echoPin), states the function name and the variables

{digitalWrite (trigPin, LOW); //prepares to emit the sound that reflects off of the nearest object

delayMicroseconds(2); //the delay is there so there can be silence before the sound is emitted

digitalWrite (trigPin, HIGH); //amps the trigPin so it releases the sound

delayMicroseconds(10); //there needs to be silence after emitting the sound so the receiver (echoPin) is not confused by the two

digitalWrite (trigPin, LOW); // the trigPin needs to return to low so it does not keep emitting a sound

duration= pulseIn (echoPin, HIGH); //the echoPin/receiver needs to be amped so that it can hear the sound after it bounces off of the nearest object

distance=duration * 0.034/2; //this equation at the end calculates the distance by using the duration (the time it took for the sound to bounce off of the object and come back) and the speed of sound

Your contributions are licensed under the open source Creative Commons license.