Using pulseIn

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

Eg, Measure the duration of HIGH on a echo pin in Ultrasonic sensor (see previous notes for details)

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); 
  digitalWrite(trigPin, HIGH);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;

  if (distance >= 200 || distance <= 0){
    Serial.println("Out of range");
  else {
    Serial.println(" cm");