Inside void loop(), create the number variables for the duration and distance that will be measured.
long duration, distance;
Next, include the following lines that will turn off the ultrasonic speaker.
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
Type the command below afterwards. This will turn on the trigger speaker and emit a burst of high-frequency sound for 10 microseconds and then turn off the trigger speaker.
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
The way this program is able to measure distance is in this following line. The pulseIn(pinNumber,State
function saves the amount of time it takes for the sound burst to travel back and forth from an object to reach the echo speaker. Once the state changes value on the chosen pin between HIGH to LOW or LOW to HIGH, the timer ends. The output is the amount of time in milliseconds.
duration = pulseIn(echoPin, HIGH);
Next, code the math that converts the time traveled by the ultrasonic sound into centimeters.
distance = (duration/2) / 29.1;
Finally, include this command to allow for the distance to be displayed on the serial monitor on your computer.
Serial.println(distance);