Breadboard
docs
Example project · Sensors

Ultrasonic ruler

The Arduino Nano pings an HC-SR04 and prints the distance over serial. Drag the distance slider and watch the readings follow. The Code tab holds the same ruler as an editable Arduino sketch.

The Ultrasonic ruler circuit as rendered by the simulator

How it works

Sonar, timed by the microcontroller: the Nano fires a 10 µs pulse at the HC-SR04's TRIG (D9), the sensor answers with a pulse on ECHO (D8) whose width encodes the round trip at 58 µs per centimeter, and pulseIn measures it. The bench firmware prints the distance every 200 ms; the sensor's Inspector slider is the target you're ranging, anywhere from 2 to 200 cm. The Code tab holds the same logic as an editable Arduino sketch.

What's on the bench

  • Arduino Nano
  • Battery
  • HC-SR04

How it's wired

  • hole a13hole B-5
  • hole j13hole B+5
  • hole a30hole B+25
  • hole a33hole B-27
  • hole a21hole c31
  • hole a20hole c32

The code

This Arduino C++ sketch lives in the Code tab; sign in and press Compile & upload to build real firmware for the emulated board.

// The same HC-SR04 ruler as an Arduino sketch. Edit it, then Compile &
// upload (sign-in needed): the server builds real AVR firmware and flashes it.
const int TRIG = 9;
const int ECHO = 8;

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

void loop() {
  digitalWrite(TRIG, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG, HIGH);  // 10 us ping
  delayMicroseconds(10);
  digitalWrite(TRIG, LOW);
  long us = pulseIn(ECHO, HIGH, 30000UL);
  Serial.print("D ");
  Serial.print(us / 58);     // round trip: ~58 us per cm
  Serial.println(" cm");
  delay(200);
}

Try this

  • Drag the distance slider and watch the serial readings track it.
  • Probe ECHO with the ∿ Scope: measure the pulse width and do the ÷58 math yourself.
  • Edit the sketch to print inches (divide by 148) and Compile & upload.
  • Slide to 200 cm and note the pulse stretching toward the 30 ms timeout.

Related projects