RRADIUS TUTOR
Robotics Lab / Experiment 03

Arduino Ultrasonic Distance Simulator

Move a virtual obstacle, adjust temperature and measurement interval, and see how the HC-SR04 calculates distance using sound echoes.

Find a Tutor

01   Experiment parameters

Yellow code values follow your settings

02   Live sensor view

ARDUINO UNOATmega328PHC-SR04TXRX5VD9 TRIGD10 ECHOGNDVirtual wiring (illustrative, not a physical hole-by-hole wiring plan)
Measured distance—
ECHO pulse width—
Speed of sound343.4 m/s
Stopped · waiting for trigger
Target: 75 cm

03   Arduino code

C++ / Arduino IDE
Yellow highlights = user-selected pins, sampling interval and temperature assumption. Object distance is a simulated physical input, not a code constant.
// 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);
}
Yellow = adjustable code parameter.
Understand the logic

04   How does ultrasonic distance measurement work?

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.

1

Send a trigger pulse

Arduino pin D9 sends a 10 µs HIGH pulse to the TRIG input.

2

Transmit and receive sound

The sensor emits a short ultrasonic burst. Its ECHO output stays HIGH for a duration corresponding to the round trip.

3

Measure time

Pin D10 reads the ECHO pulse using pulseIn(). At the selected distance, expect approximately 4,368 µs.

4

Calculate distance

Distance = speed of sound × echo time ÷ 2. Divide by two because sound travels to the obstacle and back.

Physics connection: Sound speed is approximately 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.