1
Send a trigger pulse
Arduino pin D9 sends a 10 µs HIGH pulse to the TRIG input.
Move a virtual obstacle, adjust temperature and measurement interval, and see how the HC-SR04 calculates distance using sound echoes.
// Experiment 03: HC-SR04 distance const int trigPin = 9; const int echoPin = 10; const unsigned long sampleMs = 250; const float tempC = 20; const float speedCmUs = (331.3 + 0.606 * tempC) / 10000.0; void setup() { Serial.begin(9600); pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); digitalWrite(trigPin, LOW); } void loop() { digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); unsigned long us = pulseIn(echoPin, HIGH, 30000UL); if (us == 0) { Serial.println("No echo"); } else { float cm = us * speedCmUs / 2.0; Serial.print("Distance: "); Serial.println(cm); } delay(sampleMs); }
The HC-SR04 sends an ultrasonic burst and measures how long its echo takes to return. The Arduino converts that round-trip time into a one-way distance.
Arduino pin D9 sends a 10 µs HIGH pulse to the TRIG input.
The sensor emits a short ultrasonic burst. Its ECHO output stays HIGH for a duration corresponding to the round trip.
Pin D10 reads the ECHO pulse using pulseIn(). At the selected distance, expect approximately 4,368 µs.
Distance = speed of sound × echo time ÷ 2. Divide by two because sound travels to the obstacle and back.
331.3 + 0.606 × temperature(°C) m/s. At 20°C, a 75 cm target produces an ideal echo of 4,368 µs. Real readings vary with temperature, target material, angle and sensor noise. This is an idealized model, not an electrical or acoustic solver. The HC-SR04 ECHO pin is 5 V; use level shifting before connecting it to a 3.3 V microcontroller such as ESP32 or Raspberry Pi.