Arduino Learning Studio full lab
0/13 lessons marked complete
● Saved in this browser← Back to homepage

Lesson 7 of 13

Read a sensor

Objective: Measure distance with an ultrasonic sensor: turn an echo time into centimetres, check it against a ruler, and treat a missing echo (0) as no reading, never as close.

MODEL OF THIS SKETCHSTOPPED
beyond 4 m0100200300400ruler, cmsendhearHC-SR04VCCTrigEchoGND5V~D9~D10GNDARDUINO UNOmodel readoutpress ▶ Run
2 cm450 cm

Moving the obstacle is a simulated input: the sketch does not change. Past 400 cm is beyond the sensor's rated range.

Model: when nothing echoes, the module's Echo goes HIGH for 38 ms (datasheet v2).

Serial Monitor · modelsketch stopped

Press ▶ Run. The monitor shows only what the sketch prints.

Line ending: New Line

The monitor shows only what the sketch prints.

While the sketch runs, a zoomed-in view shows one reading (Trig, Echo and how long pulseIn() waits), and a chart compares the ruler with what the sketch prints over the last 4 seconds.

Stage 1 of 7 · What am I building?

Explore

A rescue rover has to know how far away things are. This sensor times an echo: the board starts a reading on D9 and measures the answer on D10. Select each part on the circuit, or below.

Pick a part. 0/6 inspected.

Before you start (optional refreshers)

Timing and delay()

delay(ms) pauses the whole program. Nothing else happens while it waits, so a blink lasts ON delay + OFF delay.

Digital input

digitalRead() reports whether an input pin is HIGH or LOW. An unconnected input 'floats' and reads randomly.

Conditional logic

if (condition) { … } else { … } chooses what to do from a reading. The same test runs on every pass of loop().

New ideas in this lesson

Measuring pulses in microseconds

pulseIn() times how long a pin stays HIGH, in µs (millionths of a second). It returns 0 if no complete pulse arrives before its timeout, which is one second unless the sketch gives a shorter one.

Echo ranging (time of flight)

An ultrasonic sensor times how long its sound takes to reach an obstacle and come back. Sound travels about 343 m/s at 20 °C (0.0343 cm per µs), so distance = echo time × 0.0343 ÷ 2: about 58 µs for each cm.

Noise, spikes and missing readings

Real readings scatter a little, sometimes jump (a spike), and sometimes fail: pulseIn() returns 0 when no echo arrives in time. A robot treats 0 as no reading, never as very close, and checks more than one reading before acting.

Build it for real · Arduino Uno R3

You need

  • Arduino Uno R3 (or compatible) and its USB cable
  • HC-SR04 ultrasonic sensor
  • 4 female-to-male jumper wires (or a breadboard)

Wiring

  1. Sensor VCC → 5V; sensor GND → GND.
  2. Sensor Trig → D9; sensor Echo → D10.
  3. Open the Serial Monitor at 9600 baud.

Before you power up: The HC-SR04 is a 5 V part. On a 3.3 V board its Echo signal needs a voltage divider or level shifter.

Tip: Point it at a flat, hard surface. Soft or angled objects may give no echo, which reads as 0.

The lab models ideal parts. Real circuits add tolerances, noise and loose wires, so check your wiring against this list before you plug in.

Sketch · read-only
// Read a distance with an HC-SR04 ultrasonic sensor
// Sensor VCC to 5V, GND to GND, Trig to D9, Echo to D10
// Open the Serial Monitor at 9600 baud
const int trigPin = 9;                      // a pulse here starts a reading
const int echoPin = 10;                     // HIGH while the sound is away

void setup() {
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  Serial.begin(9600);                       // the Serial Monitor must use 9600 too
}

void loop() {
  digitalWrite(trigPin, LOW);               // start from LOW
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);              // a 10 µs pulse starts one reading
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  unsigned long duration = pulseIn(echoPin, HIGH, 30000); // µs; 0 if none within 30000 µs
  if (duration == 0) {
    Serial.println("no echo");              // 0 means no reading, not touching
  } else {
    float distance = duration * 0.0343 / 2; // there and back, so halve it
    Serial.print(duration);
    Serial.print(" us, ");
    Serial.print(distance);                 // a float prints 2 decimal places
    Serial.println(" cm");
  }
  delay(100);                               // wait before the next reading
}

Press ▶ Run, then move the obstacle.