Breadboard
docs
Example project · Displays & sensors

Ultrasonic ruler

An MCU 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

What's on the bench

  • Battery
  • HC-SR04
  • MCU

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);
}