Build an Ultrasonic Distance Meter with an HC-SR04, OLED Display and Buzzer
Point it at a wall and read the distance. This project pairs an HC-SR04 ultrasonic sensor with a small OLED screen and a buzzer to make a distance meter that shows centimeters and inches and beeps faster as things get closer, like a car's parking sensor. It needs no soldering and no breadboard, and the sketch is about 200 lines.
This guide covers the parts, the wiring, the full code, the settings you can change and what to check if something doesn't work.
What It Does
About fifteen times a second the sensor sends out a burst of ultrasound and times how long the echo takes to come back. The board turns that time into a distance and then does three things with it:
- Shows the distance on the OLED in large digits (centimeters), with inches underneath.
- Draws a bar along the bottom of the screen that shrinks as the object gets closer.
- Beeps once an object is within 100 cm. The beeps speed up as it approaches and become a steady tone at 10 cm.
+--------------------------+ | DISTANCE | | | | 84 cm | | | | 33.1 in | | [####### ] | +--------------------------+
Along the way it covers several ideas that turn up in a lot of electronics projects: timing a pulse, filtering out bad readings, driving an I2C display and running a beeper without stopping the rest of the program.
Parts You'll Need
Everything is in our Ultrasonic Distance Meter Kit:
- ATmega328P R3 development board with a USB cable
- Sensor Shield V5.0, which stacks on the board and gives every pin its own 5V and ground pin
- HC-SR04 ultrasonic distance sensor
- 0.96" I2C OLED display (128x64, SSD1306 driver)
- Active buzzer module
- 11 female-to-female jumper wires (the kit has 12)
Building from parts you already have? We also sell the board, the OLED displays (2-pack) and the buzzer modules (2-pack) separately. Without a sensor shield you can use a breadboard to share the board's 5V and GND pins between the three modules; the signal pins stay the same.
You also need a computer with a USB port and the free Arduino IDE.
Wiring
Unplug the USB cable while you wire. Press the sensor shield onto the board so that all of its pins seat in the board's headers.
On the shield, each numbered pin has three header pins in a column, labelled G, V and S: ground, 5V and signal. That is what makes this build simple. Every module gets its power from the V and G pins right beside its signal pin, so nothing has to share.
This build uses the six analog columns, A0 to A5, which sit together along one edge of the shield. The sketch uses A0, A1 and A2 as ordinary on/off pins.
The shield has a small jumper cap (often marked SEL) next to its screw terminal. Leave it fitted, as shipped, and leave the screw terminal empty. That terminal is for a separate servo power supply, which this project doesn't use.
HC-SR04 shield OLED display shield ------- ------ ------------ ------ VCC ------------- A0 V VCC ------------- A4 V Trig ------------- A0 S GND ------------- A4 G Echo ------------- A1 S SDA ------------- A4 S GND ------------- A0 G SCL ------------- A5 S Buzzer shield ------ ------ VCC (+) ---------- A2 V I/O (S) ---------- A2 S GND (-) ---------- A2 G
HC-SR04 Sensor
| Sensor pin | Shield pin | Notes |
|---|---|---|
| VCC | A0, V
|
The HC-SR04 needs 5V |
| Trig | A0, S
|
The board pulses this pin to send a ping |
| Echo | A1, S
|
Goes high for as long as the echo takes to return |
| GND | A0, G
|
OLED Display
The display talks over I2C, which uses two signal wires. On this board they are fixed: A4 is SDA (data) and A5 is SCL (clock).
| Display pin | Shield pin | Notes |
|---|---|---|
| VCC | A4, V
|
|
| GND | A4, G
|
|
| SDA | A4, S
|
Data |
| SCL | A5, S
|
Clock |
Check the labels on your display before you connect power. The order of VCC and GND differs between OLED modules. Go by the printed labels, not by pin position.
Buzzer
| Buzzer pin | Shield pin | Notes |
|---|---|---|
| VCC or + | A2, V
|
|
| I/O, S or IN | A2, S
|
The signal that switches the buzzer on |
| GND or - | A2, G
|
Count them when you finish: four wires on the sensor, four on the display and three on the buzzer.
Upload and Try It
- Install the Arduino IDE if you don't have it, and connect the board with its USB cable. The board uses a CH340 USB chip. Most computers recognize it automatically; if no port appears, install the CH340 driver (named CH341SER, from the chip's maker WCH at wch-ic.com) and reconnect.
- Open Library Manager, search for Adafruit SSD1306 and install it. When it asks about dependencies, choose Install All so that Adafruit GFX comes with it.
- Open a new sketch, delete everything in it, paste in the sketch from the end of this post and save it as
distance_meter. - Under Tools > Board > Arduino AVR Boards select Arduino Uno, then pick the board's port under Tools > Port.
- Upload. The screen should show
---andout of rangefor a moment, then a distance. - Hold a book in front of the sensor and move it in and out. The number should follow it. Inside 100 cm the buzzer starts to beep, and at 10 cm it sounds continuously.
The readings are also sent to Serial Monitor at 115200 baud, five times a second.
Settings
All the settings are constants at the top of the sketch:
| Constant | Default | Purpose |
|---|---|---|
TRIG_PIN |
A0 |
Pin connected to the sensor's Trig |
ECHO_PIN |
A1 |
Pin connected to the sensor's Echo |
BUZZER_PIN |
A2 |
Pin connected to the buzzer's signal pin |
BUZZER_ACTIVE_HIGH |
true |
Set false if your buzzer sounds when it should be quiet |
OLED_ADDR |
0x3C |
I2C address of the display; a few modules use 0x3D
|
MAX_CM |
300 |
Readings beyond this show as out of range |
ALERT_CM |
100 |
Distance at which beeping starts |
SOLID_CM |
10 |
Distance at which the tone becomes continuous |
SHOW_INCHES |
true |
Show inches under the centimeter reading |
SOUND_ON |
true |
Set false for a silent meter |
SLOW_BEEP_MS |
700 |
Time between beeps at ALERT_CM
|
FAST_BEEP_MS |
90 |
Time between beeps just before the tone goes continuous |
How It Works
Timing the echo. A 10-microsecond pulse on Trig makes the sensor send a short burst of 40 kHz sound. The sensor then holds its Echo pin high until the sound comes back. pulseIn() measures that time in microseconds.
Turning time into distance. Sound travels about 343 meters per second in room-temperature air, which is 0.0343 cm per microsecond. The echo time covers the trip out and back, so the distance is the time multiplied by 0.0343 and divided by 2. An echo of 5,831 microseconds means 100 cm.
Ignoring bad readings. Ultrasonic sensors occasionally return a wild value, for example when the sound glances off an angled surface. The sketch keeps the last three readings and uses the middle one, so a single bad reading never reaches the screen or the buzzer.
Beeping without stopping. The sketch never uses delay() to time the beeps. It notes when the current beep started using millis() and, each time around the loop, checks whether it is time to switch the buzzer on or off. That leaves the board free to keep measuring.
Troubleshooting
-
Screen stays blank: check that SDA is on
A4and SCL is onA5, and that VCC and GND match the labels on the display. If the wiring is right, changeOLED_ADDRto0x3D. Serial Monitor printsDisplay not foundat startup when the board can't reach the screen. -
Nothing happens at all: check that the shield is pressed fully onto the board and that its
SELjumper cap is fitted. - Always shows "out of range": Trig and Echo are probably swapped, or the sensor has no 5V. Check the four sensor wires against the table.
-
Buzzer sounds all the time and stops when something is close: your buzzer module switches on with a low signal. Set
BUZZER_ACTIVE_HIGHtofalse. -
Buzzer never sounds: check its three wires, then confirm the object is closer than 100 cm and that
SOUND_ONistrue. - Reading jumps around: aim at a flat, hard surface square to the sensor. Soft materials such as curtains and clothing absorb the sound, and angled surfaces deflect it. The sensor's beam is roughly 15 degrees wide, so nearby objects off to the side can also be picked up.
- Goes to "out of range" and stops beeping when something touches the sensor: closer than about 2 cm is below the sensor's minimum range.
- Upload fails or no port is listed: install the CH340 driver, try another USB port and make sure the cable is the one supplied; some phone cables carry power only.
-
Compile error naming
Adafruit_SSD1306.h,Adafruit_GFX.horAdafruit_I2CDevice.h: a library is missing. Repeat step 2 above and choose Install All, or install Adafruit GFX Library and Adafruit BusIO by name.
Take It Further
-
Garage parking aid. Mount the meter on the wall at bumper height, set
SOLID_CMto the stopping distance you want and power it from a USB charger. -
Inches first. In
drawScreen(), changedisplay.print(cm);todisplay.print(cm / 2.54f, 1);and the" cm"after it to" in". Then, in the small line below, changedisplay.print(cm / 2.54f, 1);todisplay.print(cm);and" in"to" cm". - Temperature correction. Sound travels about 0.6 m/s faster for each degree Celsius. Add a temperature sensor and adjust the 0.0343 figure for better accuracy outdoors.
- Put it in a case. A 3D-printed enclosure with two holes for the sensor's transducers makes this a tidy desk tool. Press M3 Durathread heat set inserts into the standoffs for threads that won't strip when you open it up again. Our Heat Set Insert Size Guide covers which size and style to choose.
Safety: unplug USB before changing wires, and never connect a V pin straight to a G pin. The HC-SR04 is not waterproof, so keep it dry.
The Code
Here is the complete sketch. Copy it into the Arduino IDE, save it as distance_meter and upload it.
// Ultrasonic distance meter
//
// HC-SR04 ultrasonic sensor + 0.96" SSD1306 I2C OLED + active buzzer module
// on an ATmega328P R3-form board. Shows the distance in centimeters and
// inches, draws a bar that shrinks as things get closer, and beeps faster
// the closer an object is, like a parking sensor.
//
// Libraries (install from Library Manager): Adafruit SSD1306, Adafruit GFX.
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
// ---- Configuration ---------------------------------------------------------
// The analog pins are used as ordinary digital pins here. On the sensor
// shield their 5V pins are always powered, whatever the power jumper is doing.
const uint8_t TRIG_PIN = A0; // HC-SR04 Trig
const uint8_t ECHO_PIN = A1; // HC-SR04 Echo
const uint8_t BUZZER_PIN = A2; // buzzer module signal pin
// Most active buzzer modules sound when the signal pin is HIGH. If yours
// sounds all the time and goes quiet when it should beep, set this to false.
const bool BUZZER_ACTIVE_HIGH = true;
// I2C address of the display. Almost all 0.96" modules use 0x3C; try 0x3D if
// the screen stays blank.
const uint8_t OLED_ADDR = 0x3C;
const int MAX_CM = 300; // readings beyond this are shown as out of range
const int ALERT_CM = 100; // beeping starts at this distance
const int SOLID_CM = 10; // at or under this distance the tone is continuous
const bool SHOW_INCHES = true; // second line of the display
const bool SOUND_ON = true; // set false for a silent meter
const unsigned long SAMPLE_MS = 60; // time between pings (60 ms minimum)
const unsigned long DISPLAY_MS = 200; // time between screen updates
const unsigned long BEEP_ON_MS = 40; // length of each beep
const unsigned long SLOW_BEEP_MS = 700; // beep spacing at ALERT_CM
const unsigned long FAST_BEEP_MS = 90; // beep spacing just above SOLID_CM
// ---- Display ---------------------------------------------------------------
const uint8_t SCREEN_W = 128;
const uint8_t SCREEN_H = 64;
Adafruit_SSD1306 display(SCREEN_W, SCREEN_H, &Wire, -1);
// ---- State -----------------------------------------------------------------
const int OUT_OF_RANGE = -1;
int samples[3] = {OUT_OF_RANGE, OUT_OF_RANGE, OUT_OF_RANGE};
uint8_t sampleIndex = 0;
int distanceCm = OUT_OF_RANGE;
unsigned long lastSample = 0;
unsigned long lastDisplay = 0;
unsigned long lastBeepStart = 0;
// ---- Measurement -----------------------------------------------------------
// Sound travels about 0.0343 cm per microsecond. The echo time covers the
// trip out and back, so halve it.
float echoToCm(unsigned long echoMicros) {
return echoMicros * 0.0343f / 2.0f;
}
// Middle value of three readings. One wild reading can't move the result.
// Out-of-range readings (-1) sort low, so two of three must agree.
int median3(int a, int b, int c) {
if (a > b) { int t = a; a = b; b = t; }
if (b > c) { int t = b; b = c; c = t; }
if (a > b) { int t = a; a = b; b = t; }
return b;
}
// Sends one ping and returns the distance in whole centimeters, or
// OUT_OF_RANGE if no echo came back in time.
int pingCm() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// 25 ms covers a little over 4 m; pulseIn returns 0 on timeout.
unsigned long echoMicros = pulseIn(ECHO_PIN, HIGH, 25000UL);
if (echoMicros == 0) return OUT_OF_RANGE;
int cm = (int)(echoToCm(echoMicros) + 0.5f);
if (cm < 2 || cm > MAX_CM) return OUT_OF_RANGE;
return cm;
}
// ---- Buzzer ----------------------------------------------------------------
void setBuzzer(bool on) {
digitalWrite(BUZZER_PIN, (on == BUZZER_ACTIVE_HIGH) ? HIGH : LOW);
}
// Time between beep starts for a given distance.
// Returns -1 for silence and 0 for a continuous tone.
long beepPeriodMs(int cm) {
if (cm == OUT_OF_RANGE || cm > ALERT_CM) return -1;
if (cm <= SOLID_CM) return 0;
return map(cm, SOLID_CM, ALERT_CM, FAST_BEEP_MS, SLOW_BEEP_MS);
}
void updateBuzzer(int cm, unsigned long now) {
long period = SOUND_ON ? beepPeriodMs(cm) : -1;
if (period < 0) {
setBuzzer(false);
return;
}
if (period == 0) {
setBuzzer(true);
return;
}
if (now - lastBeepStart >= (unsigned long)period) lastBeepStart = now;
setBuzzer(now - lastBeepStart < BEEP_ON_MS);
}
// ---- Screen ----------------------------------------------------------------
void drawScreen(int cm) {
display.clearDisplay();
display.setTextColor(SSD1306_WHITE);
display.setTextSize(1);
display.setCursor(0, 0);
display.print(F("DISTANCE"));
display.setTextSize(3);
display.setCursor(0, 14);
if (cm == OUT_OF_RANGE) {
display.print(F("---"));
} else {
display.print(cm);
display.setTextSize(2);
display.print(F(" cm"));
}
display.setTextSize(1);
display.setCursor(0, 42);
if (cm == OUT_OF_RANGE) {
display.print(F("out of range"));
} else if (SHOW_INCHES) {
display.print(cm / 2.54f, 1);
display.print(F(" in"));
}
// Bar along the bottom: full at MAX_CM, empty at zero.
display.drawRect(0, 54, SCREEN_W, 10, SSD1306_WHITE);
if (cm != OUT_OF_RANGE) {
int fill = map(constrain(cm, 0, MAX_CM), 0, MAX_CM, 0, SCREEN_W - 4);
display.fillRect(2, 56, fill, 6, SSD1306_WHITE);
}
display.display();
}
// ---- Setup and loop --------------------------------------------------------
void setup() {
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(BUZZER_PIN, OUTPUT);
setBuzzer(false);
Serial.begin(115200);
// begin() only reports a memory failure, so also ask the display to answer
// on the I2C bus. That catches loose wires and a wrong address.
bool found = display.begin(SSD1306_SWITCHCAPVCC, OLED_ADDR);
Wire.beginTransmission(OLED_ADDR);
if (Wire.endTransmission() != 0) found = false;
if (!found) {
Serial.println(F("Display not found. Check wiring and OLED_ADDR."));
// Keep going: the buzzer and Serial Monitor still work without a screen.
}
drawScreen(OUT_OF_RANGE);
Serial.println(F("Distance meter ready."));
}
void loop() {
unsigned long now = millis();
if (now - lastSample >= SAMPLE_MS) {
lastSample = now;
samples[sampleIndex] = pingCm();
sampleIndex = (sampleIndex + 1) % 3;
distanceCm = median3(samples[0], samples[1], samples[2]);
}
updateBuzzer(distanceCm, millis());
if (now - lastDisplay >= DISPLAY_MS) {
lastDisplay = now;
drawScreen(distanceCm);
if (distanceCm == OUT_OF_RANGE) {
Serial.println(F("out of range"));
} else {
Serial.print(distanceCm);
Serial.println(F(" cm"));
}
}
}
If you build it, or take it somewhere new, we'd love to hear about it.