OLED graphics
Draw text and a bouncing ball on a 128×64 OLED with the Adafruit SSD1306 library.
Displays · Intermediate
In a real product: Fitness band display (Wearables): A small OLED shows time and stats.
A 0.96" OLED has 128×64 pixels that light up by themselves, so it needs no backlight and has great contrast. Unlike a character LCD you draw anything: text, lines, shapes, images.
What you'll learn
- Framebuffer graphics: draw into memory, then send the whole picture with
display() - The Adafruit GFX drawing functions: text, rectangles, circles
- Simple animation: move, bounce, redraw
How it works
The SSD1306 controller is on I²C (DATA = SDA on A4, CLK = SCL on A5) at address 0x3C. The library keeps a copy of the screen in the Uno's RAM: 128 × 64 bits = 1 KB, half the Uno's memory!
Each frame, the loop clears the buffer, prints a title and the uptime, draws a box, moves the ball one step (reversing its direction when it reaches a wall) and calls display.display() to send the buffer to the screen.
Try this
- Add a second ball, or make the ball leave a trail by not clearing the screen.
- Plot a sensor reading as a scrolling graph.
- Make a game of Pong with a potentiometer as the paddle.
sketch.ino
// A 128x64 SSD1306 OLED on I2C (0x3C): a title, the uptime and a bouncing ball.
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
Adafruit_SSD1306 display(128, 64, &Wire, -1);
int x = 20, y = 40, dx = 3, dy = 2;
void setup() {
Serial.begin(9600);
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println("SSD1306 not found");
while (true) {}
}
}
void loop() {
display.clearDisplay();
display.setTextColor(SSD1306_WHITE);
display.setTextSize(2);
display.setCursor(0, 0);
display.println("Hello!");
display.setTextSize(1);
display.print("Uptime: ");
display.print(millis() / 1000);
display.println(" s");
display.drawRect(0, 26, 128, 38, SSD1306_WHITE);
x += dx;
y += dy;
if (x < 5 || x > 122) dx = -dx;
if (y < 31 || y > 58) dy = -dy;
display.fillCircle(x, y, 4, SSD1306_WHITE);
display.display();
delay(30);
}