The information from a digital signal can be decoded from it's pulse. That is, from the duration of a digital pin remaining HIGH / LOW
This pulse is measured using pulseIn function
1) To start sensor to emit ultrasonic waves, Trigger pin should remain HIGH for 10 micro seconds.
2) After emiiting the ultrasonic waves, the receiver checks for bounce backs and send the echo pin to HIGH.
3) The duration of HIGH on a echo pin can be used to measure the distance of an object
#define trigPin 13
#define echoPin 12
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
if (distance >= 200 || distance <= 0){
Serial.println("Out of range");
}
else {
Serial.print(distance);
Serial.println(" cm");
}
delay(500);
}