Sharjah, UAE GST
Home/ Projects/ Lesson 8: OLED Distance Meter
Lesson 8 of 9 Display Intermediate ◎ 45 min

Lesson 8: OLED Distance Meter

Show the distance in big numbers on the small OLED screen, with the zone and a bar graph. You will install your first Arduino libraries.

Arduino Ultrasonic Distance & Parking Learning Kit
One of 9 projects in the Arduino Ultrasonic Distance & Parking Learning Kit — the parts below are from that kit.

Before you start

Time
45 min
Do these first
Adult help needed
You can do this lesson on your own once the libraries are installed. The OLED needs its 4 header pins fitted - if yours has only holes, an adult must solder them.
  • Only if your OLED has no header pins: soldering by an adult

Exact parts

PartHow many
Wiring from Lesson 1 (the other parts can stay)
0.96" OLED display, 4 pins1
Male-to-male jumper wires4

Not in the box

Nothing extra - just the kit and your computer.

What you build and learn

  • Installing libraries in the Arduino IDE
  • I2C: two wires (SDA, SCL) for a whole display
  • Drawing text and shapes on a screen
  • Saving memory with F("...")

The OLED has its own controller chip, the SSD1306. The Adafruit library knows how to talk to it, so we only call commands like print() and fillRect().

The UNO talks to the display over I2C: SDA on A4 carries the data, SCL on A5 the clock. The display answers at address 0x3C (some at 0x3D) - the sketch tries both.

Drawing happens in the UNO's memory first. Nothing appears until display.display() sends the whole picture. The picture needs 1 KB of the UNO's 2 KB of memory, which is why the text uses F("...").

The zones are the same as Lessons 2 and 3. The bar is full width at 100 cm.

New words

Library
Ready-made code you install once and use with #include, such as Adafruit SSD1306.
I2C
A way for chips to talk over 2 wires: SDA (data) and SCL (clock). On the UNO they are A4 and A5.
Address
A number like 0x3C that tells the UNO which I2C device it is talking to.
Pixel
One dot on the screen. This display has 128 × 64 of them.

What this project uses

Every item is in the kit — nothing extra to buy.

Build this with

Arduino Ultrasonic Distance & Parking Learning Kit

All 9 parts in one box, with this project and 8 more to build from them.

AED 85.00 See the kit
Need only these parts? Order them loose · from AED 98.23
Used in this project tick what you still need
Selected parts AED 98.23

One of each part. Packs (resistor assortment, jumper wires) already hold more than a single build needs. Delivery is AED 20, free on orders AED 100+.

Connections

Unplug USB before you change any wire. Pin names are the labels printed on the board.

Lesson 8: OLED Distance Meter - connection diagram with labelled pins
Connection diagram, drawn from this lesson's pin plan - not a photo of a tested build. Tap to open it full size. The table below says the same thing in words.
Part / pinConnect toNote
OLED VCC+ rail (5V)Rated 3.3-5V. Go by the labels: the pin order varies
OLED GND− rail (GND)
OLED SDAUNO A4I2C data
OLED SCLUNO A5I2C clock
HC-SR04As in Lesson 1TRIG pin 9, ECHO pin 10

Step by step

One thing at a time. Tick nothing off until it matches the diagram.

  1. In the Arduino IDE open Tools → Manage Libraries. Search Adafruit SSD1306 and click Install. When asked, choose Install All so Adafruit GFX and BusIO come too.
  2. Unplug the USB cable.Watch out: Always unplug the USB cable before you add, move or remove a wire.
  3. Check the OLED has 4 header pins. If it has only holes, stop here: an adult must solder the pins first.Watch out: Soldering irons are very hot. Adults only.
  4. Read the 4 labels on the OLED: GND, VCC, SCL, SDA (the order varies). Push it into the breadboard with each pin in its own row.
  5. Wire VCC to the + rail, GND to the − rail, SDA to UNO A4 and SCL to UNO A5.Watch out: Go by the labels. VCC and GND swapped can damage the display.
  6. Check against the diagram, plug in USB, copy the Lesson 8 code into the IDE and upload it.
  7. Open the Serial Monitor at 9600 baud: it says "OLED found at 0x3C" (or 0x3D). Move a book towards the sensor and watch the screen.

Sketch for this project

Written for the board in the kit. Copy it into the Arduino IDE; change the pin numbers if you wire it differently.

lesson8_oled_meter.ino arduino
/*
  DIY KIT - Arduino Ultrasonic Distance & Parking Learning Kit
  Lesson 8 of 9: OLED Distance Meter

  LIBRARIES (once): Tools > Manage Libraries, search "Adafruit SSD1306",
  click Install, and choose "Install all" so Adafruit GFX and BusIO come too.

  WIRING (unplug the USB cable before you wire)
    The sensor from Lesson 1 (TRIG pin 9, ECHO pin 10) stays.
    OLED display - go by the labels printed on it, the order varies:
      VCC -> 5V  (+ rail)      GND -> GND (- rail)
      SDA -> UNO A4            SCL -> UNO A5
    The LEDs and buzzer can stay; this sketch does not use them.

  WHAT SHOULD HAPPEN
    The OLED shows the zone at the top, the distance in big numbers and a
    bar that grows as the target moves away (full at 100 cm).
    The Serial Monitor (9600 baud) says which address the display answered on.

  F("...") keeps text in the UNO's large program memory instead of its small
  working memory (RAM). The display needs 1 KB of RAM for its picture.
*/

#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

const int TRIG_PIN = 9;
const int ECHO_PIN = 10;

const int CLEAR_CM = 50;      // the same zones as Lessons 2 and 3
const int NEAR_CM = 20;
const int BAR_FULL_CM = 100;  // the bar is full width at this distance

const unsigned long ECHO_TIMEOUT_US = 30000;
const int MIN_CM = 2;
const int MAX_CM = 400;

Adafruit_SSD1306 display(128, 64, &Wire, -1);   // 128 x 64 pixels, no reset pin
bool displayOk = false;

long readOnceCm() {
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);
  unsigned long us = pulseIn(ECHO_PIN, HIGH, ECHO_TIMEOUT_US);
  if (us == 0) return 0;
  long cm = us / 58;
  if (cm < MIN_CM || cm > MAX_CM) return 0;
  return cm;
}

// Most of these displays answer at address 0x3C, some at 0x3D. Try both.
bool startDisplay() {
  if (display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println(F("OLED found at 0x3C"));
    return true;
  }
  if (display.begin(SSD1306_SWITCHCAPVCC, 0x3D)) {
    Serial.println(F("OLED found at 0x3D"));
    return true;
  }
  Serial.println(F("OLED not found - unplug USB and check VCC, GND, SDA (A4) and SCL (A5)"));
  return false;
}

void setup() {
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  Serial.begin(9600);
  Serial.println(F("Lesson 8: OLED Distance Meter"));
  displayOk = startDisplay();
  if (displayOk) {
    display.clearDisplay();
    display.setTextColor(SSD1306_WHITE);
    display.display();
  }
}

void loop() {
  long cm = readOnceCm();
  Serial.println(cm);                       // 0 means no echo

  if (displayOk) {
    display.clearDisplay();

    // Top line: the zone, in small letters.
    display.setTextSize(1);
    display.setCursor(0, 0);
    if (cm == 0)            display.print(F("NO ECHO"));
    else if (cm < NEAR_CM)  display.print(F("NEAR"));
    else if (cm < CLEAR_CM) display.print(F("CAUTION"));
    else                    display.print(F("CLEAR"));

    // Middle: the distance, 3 times bigger.
    display.setTextSize(3);
    display.setCursor(0, 22);
    if (cm == 0) {
      display.print(F("--"));
    } else {
      display.print(cm);
      display.setTextSize(2);
      display.print(F(" cm"));
    }

    // Bottom: a bar, full width at BAR_FULL_CM.
    if (cm > 0) {
      int width = map(constrain(cm, 0, BAR_FULL_CM), 0, BAR_FULL_CM, 0, 128);
      display.fillRect(0, 56, width, 8, SSD1306_WHITE);
    }
    display.display();                      // nothing appears until display() is called
  }

  delay(150);
}
ℹCompiler-checked for Arduino UNO (0 warnings) and run in the kit simulator. Pins match the lesson diagram. Not yet bench-tested on the shipped parts.

Upload it

  1. Click Copy (or Download .ino and open the file).
  2. In the Arduino IDE choose File → New Sketch, select everything in it and paste.
  3. Check the bottom of the window says Arduino Uno and your port (Start here, step 5).
  4. Click Upload (the → arrow) and wait for Done uploading.

How the code works

In the codeWhat it does
#include <Adafruit_SSD1306.h>Brings in the library you installed.
Adafruit_SSD1306 display(128, 64, &Wire, -1);A display that is 128 × 64 pixels on the I2C wires (Wire), with no reset pin.
startDisplay()Tries address 0x3C, then 0x3D, and tells you in the Serial Monitor which one worked.
display.setTextSize(3); display.print(cm);Big digits. Then display.display() sends the picture to the screen.

Change it and see

Change: Change BAR_FULL_CM from 100 to 50.What happens: The bar fills up twice as fast.
Change: Change setTextSize(3) to setTextSize(4).What happens: Bigger digits - three-digit numbers may no longer fit.

What you should see or hear

  • Serial Monitor: "OLED found at 0x3C" (or 0x3D).
  • The OLED shows the zone at the top, the distance in big numbers and a bar at the bottom.
  • No echo: "NO ECHO" and "--", with no bar.

If it doesn't work

ProblemWhat to check
"OLED not found"Unplug USB. Check VCC, GND, SDA to A4 and SCL to A5 by the labels. Push the OLED pins firmly into the breadboard.
"Adafruit_SSD1306.h: No such file or directory"The library is not installed: do step 1 again and choose Install All.
The screen stays black but "OLED found" appearsUpload again. If it still stays black, ask us - the display may need a different setting.
The screen shows random dotsPress the UNO's reset button. If it keeps happening, a wire may be loose.
It always says no echoUnplug USB. Check VCC to the + rail, GND to the − rail, TRIG to pin 9 and ECHO to pin 10 - by the labels on the sensor, not their position. Point it at a big flat object 20-50 cm away.

Small experiment

Draw a frame round the screen: add display.drawRect(0, 0, 128, 64, SSD1306_WHITE); just before display.display(). Then try a circle with display.drawCircle(110, 8, 6, SSD1306_WHITE);

Check what you learned

Which two UNO pins are used for I2C?

A4 (SDA, data) and A5 (SCL, clock).

Why does nothing appear until display.display() is called?

The picture is built in memory first and sent to the screen in one go.

What is a library?

Ready-made code you install once and use with #include.

▶In the simulator: The simulator shows what the OLED would display. It does not need the libraries installed - the real Arduino IDE does (step 1).

Next

  • Lesson 9 puts everything together: sensor, LEDs, buzzer and OLED in one sketch with commands.

Stuck?

Most problems are one wire in the wrong hole. Check these first:

  1. Unplug, then compare every wire with the lesson's diagram and table. One pin off is the most common problem.
  2. Sensor: are VCC, TRIG, ECHO and GND wired by their labels, with TRIG on 9 and ECHO on 10?
  3. LEDs: is the long leg on the resistor side?
  4. Is the − rail connected to a UNO GND pin, and the + rail to 5V?
  5. Serial Monitor: is it set to 9600 baud (and "New Line" when you type commands)?
  6. Upload problems: is Tools → Board set to Arduino Uno and Tools → Port to your UNO? (Start here, step 5.)
Still stuck? Ask us on WhatsApp. Send this message with a photo of your wiring - it tells us exactly where you are.
Hi DIY KIT, I'm stuck on the Arduino Ultrasonic Distance & Parking Learning Kit.
Lesson: __
Step number: __
What should happen: __
What happens instead: __
Error message (copied exactly): __
I'll attach a photo of my wiring.
Message us on WhatsApp

More from this kit

All projects →

Bot
ECHO
Online — usually replies instantly
Catalog assistant: verify final stock/price on the product page before checkout.