We need to control the sensor's high-frequency emission. To do this, we need to send the sensor module a logic HIGH signal that's at least 10µs wide to the trigger pin. We first write the pin LOW, then HIGH. It waits for at least 10µs, and then writes it LOW again. This tells the sensor to emit the signal. When the sound emitted by the sensor reflects off of an object and returns to the sensor, the sensor sends a digital signal to the Arduino. This digital signal indicates the ultrasonic signal's round-trip travel time.

digitalWrite(trigP in , LOW); delayMicroseconds(2); digitalWrite(trigP in , HIGH); delayMicroseconds(10); digitalWrite(trigP in , LOW);

We need to do a few things in order to convert this distance in microseconds into a distance in centimeters. Since the echo pin indicates how long it takes for sound to reach an object and return, we first need to divide the echo-pin pulse width by 2 to determine the one-way travel time.Sound travels at 340 m/s under typical conditions. Using some simple math, we find that this corresponds to 29 µs/cm. So far so good! To convert travel time to a distance in centimeters, we must divide the one-way travel time, in microseconds, by 29. Here is the code: