Find a course

Module 5: Motors, Power and ProjectsLesson 10 of 1214 min

Sound, Distance Sensors and Libraries

Make tones with a piezo buzzer, measure distance with an ultrasonic sensor, and add displays and modules by installing and using libraries.

Step 1 of 12Learn

A parking sensor in thirty lines

Tom's garage is tight. He wants a gadget on the wall that beeps faster and faster as his car's bumper gets closer, then sounds a steady tone at 30 cm. It needs three new skills: making sound, measuring distance and using code other people have written.

Sound first. A piezo buzzer clicks each time its voltage changes. Switch it on and off 440 times per second and you hear the musical note A. Arduino's tone() function does the switching for you in the background:

tone(8, 440);        // play 440 Hz on pin 8 until stopped
tone(8, 1000, 200);  // play 1000 Hz for 200 ms
noTone(8);           // silence

Higher frequency means higher pitch. Humans hear roughly 20 Hz to 20,000 Hz, and small piezos sound loudest around 2,000 to 4,000 Hz. Doubling the frequency raises the pitch by one octave.

Two details: an active buzzer has its own oscillator and just beeps when given 5 V (use digitalWrite), while a passive buzzer needs tone() and can play melodies. And tone() uses one of the chip's timers, so while it plays, PWM on pins 3 and 11 is disturbed on the Uno.

Step 2 of 12Practice · Work it out

Doubling a frequency raises a note one octave. If tone(8, 440) plays A, what frequency in hertz plays the A two octaves higher?

Step 3 of 12Learn

Measuring distance with an ultrasonic sensor

The popular HC-SR04 module has two round "eyes": a speaker and a microphone for ultrasound at 40 kHz, above human hearing. It works like a bat:

  1. The Arduino sends a 10-microsecond pulse to the TRIG pin.
  2. The module fires a short burst of ultrasound.
  3. The ECHO pin goes HIGH and stays HIGH until the echo returns.
  4. The Arduino measures how long ECHO was HIGH with pulseIn().

Sound travels at about 343 m/s in room-temperature air, which is 0.0343 cm per microsecond. The pulse covers the distance twice (there and back), so:

distance (cm) = time (µs) × 0.0343 / 2

digitalWrite(TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG, LOW);
unsigned long t = pulseIn(ECHO, HIGH, 30000);
float cm = t * 0.0343 / 2;

An echo time of 1,749 µs means 1,749 × 0.0343 / 2 ≈ 30 cm. The sensor reads roughly 2 cm to 4 m. Soft surfaces like curtains absorb the sound, and angled surfaces bounce it away, giving missing or wild readings, so ignore any reading of 0 (the timeout) and consider averaging a few measurements.

Step 4 of 12Diagram

One HC-SR04 measurement

One HC-SR04 measurementProcess diagram: 10 µs pulse on TRIG → 8 bursts at 40 kHz → ECHO pin goes HIGH → pulseIn measures µs → Halve and convert.10 µs pulse on TRIG8 bursts at 40 kHzECHO pin goes HIGHpulseIn measures µsHalve and convert

Tap a shape with to see more.

10 µs pulse on TRIG

digitalWrite HIGH, delayMicroseconds(10), then LOW.

8 bursts at 40 kHz

The module chirps ultrasound, too high for people to hear.

ECHO pin goes HIGH

It stays HIGH until the reflected sound returns.

pulseIn measures µs

The time for the sound to go out and come back.

Halve and convert

distance = time × speed of sound / 2, because the sound travels there and back.

Step 5 of 12Try the calculator

Ultrasonic distance calculator

Convert an echo time into distance. The speed of sound rises about 0.6 m/s for every degree Celsius.

Speed of sound
343.4 m/s
Distance
30 cm

Step 6 of 12Practice · Work it out

An HC-SR04 reports an echo time of 2,000 µs. Using 0.0343 cm/µs for the speed of sound, how far away is the object in centimeters?

Step 7 of 12Practice · Chart

Speed of sound vs. air temperature

Tap the temperature where 0.0343 cm/µs (343 m/s) is accurate.

Tap the point that answers the question, then press Check.

Speed of sound vs. air temperatureLine chart with 6 categories: −10 °C: 325 m/s; 0 °C: 331 m/s; 10 °C: 337 m/s; 20 °C: 343 m/s; 30 °C: 350 m/s; 40 °C: 356 m/s.320 m/s330 m/s340 m/s350 m/s360 m/s−10 °C0 °C10 °C20 °C30 °C40 °CAir temperature
Approximation: 331.3 + 0.606 × T m/s.
Speed of sound vs. air temperature
Air temperatureSpeed of sound
−10 °C325 m/s
0 °C331 m/s
10 °C337 m/s
20 °C343 m/s
30 °C350 m/s
40 °C356 m/s

Step 8 of 12Learn

Libraries: standing on other people's code

Many parts, such as OLED screens, LCDs, humidity sensors and LED strips, need hundreds of lines of low-level code to talk to them. You rarely write that yourself. You install a library: a package of tested code with simple functions.

In the IDE, open Tools > Manage Libraries, search for the part (for example "LiquidCrystal I2C" or the sensor's chip name), and click Install. Then add the library at the top of your sketch:

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);  // address, columns, rows

void setup() {
  lcd.init();
  lcd.backlight();
  lcd.print("Distance:");
}

Many displays and sensors use I2C, a two-wire bus (SDA and SCL, on A4 and A5 of the Uno) that lets many devices share the same two pins. Each device has an address, such as 0x27; if a display stays blank, the address is the first thing to check, and an "I2C scanner" example sketch finds it.

Every library comes with examples under File > Examples. Start there: run the unchanged example to confirm wiring before adding the part to your own project. Check that a library is maintained and widely used; an abandoned one may not compile with current boards.

Step 9 of 12Note

Step 10 of 12Tap to reveal

Choosing between similar parts

  1. Active or passive buzzer?

    Active buzzers beep at one fixed pitch when powered, ideal for alarms. Passive buzzers need tone() but can play any note or melody. If digitalWrite(HIGH) gives only a click, you have a passive buzzer.

  2. Ultrasonic or infrared distance sensor?

    Ultrasonic modules measure from a few centimeters to several meters and ignore color, but struggle with soft or angled surfaces. Infrared and laser time-of-flight sensors are smaller and faster, and handle soft surfaces better, but can be confused by sunlight or very dark materials.

  3. LCD or OLED display?

    Character LCDs are cheap and readable in sunlight but only show text. Small OLEDs show graphics with sharp contrast but are tiny and use more SRAM for their screen buffer, which matters on a 2 KB Uno.

Step 11 of 12Practice · Match the pairs

Match each part or function to its job in the parking sensor.

Tap an answer, then tap the place where it belongs (or drag it there).

  1. pulseIn()
  2. tone()
  3. Library Manager
  4. I2C address

Step 12 of 12Practice · What would you do?

What would you do?

A newly wired I2C LCD lights up its backlight but shows no text, even with the library example. The wiring has been checked twice. What is the most likely next step?