CYTHEIA AIOpen the editor

Ultrasonic Distance Meter

Measure distance using HC-SR04 ultrasonic sensor.

Open this circuit and run it

Opens in your browser with the parts, wiring and code already in place. Press Run to watch it work, then change anything you like.

How it works

An HC-SR04 ultrasonic sensor measures distance by timing an echo. The Arduino sends a short pulse on pin 7 (TRIG), the sensor sends out a burst of ultrasound, and then the sensor holds pin 6 (ECHO) high for as long as the sound takes to reach an object and bounce back.

The sketch makes a clean 10-microsecond pulse on TRIG, then pulseIn(ECHO, HIGH) measures how many microseconds ECHO stays high. Sound travels about 0.034 centimetres per microsecond, and the echo covers the distance twice, there and back, so distance = duration × 0.034 ÷ 2. The result prints in centimetres twice a second. Select the sensor in the editor and change its distance in the properties panel to see the reading move.

Parts

Wiring

Arduino code

// Ultrasonic Distance Meter
#define TRIG 7
#define ECHO 6

void setup() {
  Serial.begin(9600);
  pinMode(TRIG, OUTPUT);
  pinMode(ECHO, INPUT);
}

void loop() {
  digitalWrite(TRIG, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG, LOW);

  // How long the echo pin stays HIGH is proportional to the distance.
  long duration = pulseIn(ECHO, HIGH);
  float distance = duration * 0.034 / 2;

  Serial.print("Distance: ");
  Serial.print(distance, 1);
  Serial.println(" cm");
  delay(500);
}

Try changing it

Open this circuit and run it

Next challenge

More projects in Sensors