What is the work of pulseIn? I have code for an ultrasonic sensor which I found from a site. Here is the code:

#define trigPin 12
#define echoPin 13

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop() {
  int duration, distance;
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(1000);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  if (distance &gt;= 200 || distance &lt;= 0){
    Serial.println("Out of range");
  }
  else {
    Serial.print(distance);
    Serial.println(" cm");
  }
  delay(500);
}


However, I don't understand the work of pulseIn() function. I mean, I want to know when the time count starts and when it ends. For example, in this code, does the time start at digitalWrite(trigPin, HIGH); or does the time start at the pulseIn() function?

If it's the second one, when it stops, then how does the time give us the distance of an obstacle when I am already delaying 1000 microseconds after I send a ping in air?
From the docs:


  Reads a pulse (either HIGH or LOW) on a pin. For example, if value is
  HIGH, pulseIn() waits for the pin to go HIGH, starts timing, then
  waits for the pin to go LOW and stops timing. Returns the length of
  the pulse in microseconds. pulsein


So, in this case, pulseIn(echoPin, HIGH) starts counting the number of microseconds until echoPin goes HIGH and stores that in duration.

It starts and ends on that line, it's what is known as a blocking function. It will really sit there until echoPin goes high and tells you how long it took (unless you specify a timeout).

That also means that any delays you have before or after the pulseIn call don't affect it in any way.

The way you get distance from this time is by the following equation:

distance = (duration/2) / 29.1;


You divide by two because it goes out and back so the time would be double that of a one-way travel. The 29.1 is the speed of sound (which is 343.5 m/s => 1 / 0.03435 = 29.1). So note the result is in CM's, not inches. You could probably figure it out by looking at the data sheet of the sensor or just get a lot of samples relating duration to distance (you would measure the distance manually) and get an equation that is very similar.