NSK Electronics Arduino path

Arduino · Lesson 2

UltrasonicSensor

Give your Uno bat-powers. The HC-SR04 sends silent clicks, listens for the bounce, and turns travel time into centimetres — perfect for robots that must not kiss the wall.

HC-SR04 ultrasonic distance sensor module — blue board with transmitter and receiver cans, Vcc Trig Echo Gnd pins.

What you will learn

Hardware

Two “eyes” (TX + RX), four pins, 5 V friendly.

How it works

10 µs trigger → 40 kHz burst → Echo pulse width.

Arduino

Wire D9/D10, install NewPing, print cm on Serial.

Limits

Range, angle, size, soft stuff — when pings lie.

Need Blink first? Finish Basic Arduino so IDE, board, and port feel easy — then come back here.

What is ultrasound?

Your ears hear roughly 20 Hz to 20 kHz — from a deep rumble to a sharp whistle. Ultrasound is sound above that: too high for humans, but perfect for gadgets. The HC-SR04 clicks at about 40 kHz — bats would nod in approval.

Why bother? Sound travels at a known speed in air. Time a round trip, and you get distance — without touching the object. Battery-friendly, cheap, and beginner-friendly on 5 V logic.

Meet the HC-SR04

Look closely: two metal “cans” sit on a small green board. One is a transmitter (turns electricity into ultrasonic pulses). The other is a receiver (listens for the bounce). When the bounce arrives, the module stretches a pulse on the Echo pin — wider pulse means farther object.

  • Typical range: about 2 cm to 400 cm (~13 ft)
  • Claimed accuracy: around 3 mm in good conditions
  • Runs on 5 V — plug straight into an Arduino Uno

Quick specs

Operating voltageDC 5 V
Operating current~15 mA
Frequency40 kHz
Range2 cm … 400 cm
Ranging accuracy~3 mm (ideal setup)
Measuring angle~15°
Trigger pulse10 µs TTL HIGH
Module size~45 × 20 × 15 mm

Pinout VCC Trig Echo GND

Only four pins. Learn their jobs once — you will reuse them forever.

HC-SR04 pinout diagram: pins 1-4 labelled VCC, Trig, Echo, and GND. NSK Electronics.

Left-to-right on many boards: VCC, Trig, Echo, GND — always double-check the silkscreen on your module.

VCC

Power. Connect to Arduino 5V.

Trig

You pulse this HIGH for 10 µs to start a measurement.

Echo

Module answers with a pulse. Width = travel time.

GND

Ground / 0 V. Share with the Uno’s GND.

How a measurement works

Think of shouting “hello!” at a cliff and timing the echo — except the shout is ultrasonic and the cliff is your desk lamp.

Animated HC-SR04 timing: Trigger pulse, eight Transmit pulses at 40 kHz, then Echo width for object detect or 38 ms timeout. NSK Electronics.

NSK timing demo: Trigger → eight Transmit pulses → Echo width (bounce) or ≈38 ms timeout when clear.

  1. Trigger: set Trig HIGH for 10 µs.
  2. Burst: the TX fires eight pulses at 40 kHz — a pattern the RX can spot against noise.
  3. Echo HIGH: as the burst leaves, Echo goes HIGH to start the stopwatch.
  4. No bounce: if nothing returns, Echo falls after about 38 ms (treat as “clear / out of range”).
  5. Bounce heard: Echo goes LOW when the RX catches the reflection. Pulse width is typically from ~150 µs up to ~25 ms.

From pulse width to centimetres

School physics rides again: distance = speed × time. Cover the letter you want in the triangle.

Distance-speed-time triangle and worked example giving 8.5 centimetres for a 500 microsecond echo pulse.

Sound in air ≈ 340 m/s ≈ 0.034 cm/µs. Always divide by two — the pulse covers the trip out and back.

Example: Echo stays HIGH for 500 µs.

Distance = (0.034 × 500) / 2 = 8.5 cm

Remember the ÷2: you measured a round trip. Forget it and every reading looks twice as far.

Try it: ping demo

Drag the “wall” closer or farther, then press Ping. The demo pretends Echo timing and shows the centimetre result (speed of sound baked in — same idea as your sketch).

40 cm

Move the slider, then Ping — watch the pulse and the cm readout.

Wiring to Arduino Uno

Park the module on a breadboard (or use female jumpers). Four wires — that is the whole story for normal mode.

Colour-coded wiring from Arduino Uno 5V GND D9 D10 to HC-SR04 VCC GND Trig Echo.

Suggested pins for this lesson: Trig → D9, Echo → D10. You may choose other digital pins if you update the sketch.

HC-SR04Arduino Uno
VCC5V
GNDGND
TrigDigital pin 9
EchoDigital pin 10

Safety habit: unplug USB before rearranging jumpers. Never short 5V to GND.

Install the NewPing library

You could bit-bang Trig and time Echo with pulseIn() — but NewPing does the fiddly bits and can talk cm, inches, or raw microseconds. It also supports several sensors at once.

  1. Open Arduino IDE → Sketch → Include Library → Manage Libraries…
  2. Wait for the index to refresh.
  3. Search newping.
  4. Install the NewPing entry (by Tim Eckel).

Not bundled with the IDE — one install, then reuse forever.

Example sketch — Serial centimetres

Upload this, open Tools → Serial Monitor at 9600 baud, and wave your hand in front of the sensor.

// HC-SR04 + NewPing — print distance in cm
#include "NewPing.h"

#define TRIGGER_PIN  9
#define ECHO_PIN     10
#define MAX_DISTANCE 400   // cm; beyond this → 0 / clear

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

void setup() {
  Serial.begin(9600);
}

void loop() {
  Serial.print("Distance = ");
  Serial.print(sonar.ping_cm());
  Serial.println(" cm");
  delay(500);
}

What the code is doing

  • #include "NewPing.h" — bring in the library.
  • TRIGGER_PIN / ECHO_PIN — must match your wiring (9 and 10 here).
  • MAX_DISTANCE 400 — pings farther than this are treated as no echo.
  • NewPing sonar(...) — one sensor object.
  • sonar.ping_cm() — fire a ping; get centimetres (integer). Returns 0 if nothing in range.

Handy NewPing extras

  • sonar.ping_in() — same idea, inches.
  • Finer than whole centimetres: use duration mode — (sonar.ping() / 2) * 0.0343 for a float-ish cm value.
  • sonar.ping_median(5) — several pings, drop outliers, average the rest (steadier readings).

Bonus project idea — contactless distance bar

Want a gadget feel? Add a 16×2 character LCD and draw a horizontal bar that grows/shrinks with distance (LCDBarGraph library + LiquidCrystal). Wire the LCD as in any standard Uno LCD tutorial, keep the HC-SR04 on D9/D10, then after each ping_cm() call something like lbg.drawValue(distance, max_distance).

That project is optional — Serial Monitor alone already proves the sensor works.

3-wire mode (save a pin)

Short on digital pins? Trig and Echo are never busy at the same instant, so you can tie both to one Arduino pin.

  • Join Trig and Echo together → one wire to D9 (for example).
  • Still connect VCC and GND as usual (three wires to the board total).
  • In code: #define TRIGGER_PIN 9 and #define ECHO_PIN 9 — NewPing handles the rest.

Trade-off: slightly trickier debugging if a jumper is loose — start with 4-wire mode while learning.

Limitations — when bats get confused

HC-SR04 is brilliant for the price. It is not magic. These are the classic “why is my reading weird?” cases:

Four limitation cards: too far, shallow angle, too small, soft absorbing surface.

Aim the sensor at hard, flat faces when you can — and keep the path clear of carpet fluff and sofa cushions.

  • Too far: past ~400 cm / 13 ft, expect timeouts / zeros.
  • Shallow angle: sound glances away — the RX never hears it.
  • Too small / floor bounce: skinny targets reflect poorly; a low mount may “see” the floor.
  • Soft / fluffy: fabric and foam absorb ultrasound instead of reflecting it.

Quick checklist

  • 5V → VCC, GND → GND, Trig → D9, Echo → D10
  • Install NewPing from Library Manager
  • Upload the sketch · Serial Monitor @ 9600
  • Wave a notebook (hard face) in front — numbers should change
  • Remember ÷2 in any DIY timing math
  • Watch for angle, range, and soft-surface gotchas

In one sentence: Trig for 10 µs, listen on Echo, convert round-trip time with the speed of sound — NewPing prints the centimetres for you.