sobota, 15 marca 2014

Arduino with HC-SR04 ranging sensor


How it works

To begin the measurement supply the TRIG pin with +5 V for 10 μs. The module begins to emit the ultrasonic wave (with frequency of 40 kHz).  ECHO pin receives the returning signal - it's high state time is proportional to the distance traveled by the wave.

distance [m] = (high level time [s] x 340 m/s) / 2
distance [cm] = (high level time [μs] x 34) / 1000 / 2


Arduino code

int getDistance(int trigPin, int echoPin) {
  unsigned long duration = 0;
  
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  
  duration = pulseIn(echoPin, HIGH);

  return duration * 34 / 1000 / 2;
}