Sub topic 9
Drawing text, lines, and shapes with Adafruit GFX
This chapter assumes you can upload sketches, have the Adafruit GFX and Adafruit SSD1306 libraries installed, and have an SSD1306 OLED working over I2C at address 0x3C, as in the previous OLED chapter. Everything here applies to any display that Adafruit GFX supports. The SSD1306 is the example.
The working model: a buffer and a flush
Adafruit GFX is a drawing layer. It knows how to turn "draw a circle at x, y" into a set of pixel writes. It does not know how to talk to any particular screen. The SSD1306 library supplies that part, through one function that GFX calls for every pixel: drawPixel().
On the SSD1306, drawPixel() does not touch the screen. It changes one bit in a frame buffer, which is an array in the Arduino's RAM. The screen only changes when you call display(), which sends the whole buffer over I2C.
This gives you three rules that explain most behavior:
- Nothing appears until you call
display(). - Old content stays in the buffer until you clear or overwrite it.
- Drawing is cheap.
display()is the slow step, because it sends about 1 KB over I2C.
The coordinate system
The origin (0, 0) is the top-left pixel. X grows to the right and Y grows downward. On a 128x64 display, valid x values are 0 to 127 and valid y values are 0 to 63.
Pixels drawn outside that range are clipped silently. GFX does not raise an error, so a shape that "disappears" is often just positioned off-screen.
Colors on a monochrome OLED are three values:
| Constant | Effect |
|---|---|
| `SSD1306_WHITE` | Turns the pixel on |
| `SSD1306_BLACK` | Turns the pixel off |
| `SSD1306_INVERSE` | Flips the pixel's current state |
"White" is whatever color your panel emits. Many modules are white or blue. Some are split, with a yellow strip across the top 16 rows and blue below. That split is physical, and you cannot change it in software. Plan the layout around it.
Drawing text
Text uses a built-in 5x7 pixel font. Each character sits in a 6x8 cell, because GFX adds one blank column and one blank row of spacing. setTextSize(n) scales the font by an integer factor, so size 2 gives 12x16 cells.
| Text size | Cell (pixels) | Characters per line on 128 px | Lines on 64 px |
|---|---|---|---|
| 1 | 6x8 | 21 | 8 |
| 2 | 12x16 | 10 | 4 |
| 3 | 18x24 | 7 | 2 |
The cursor is the point where the next character is drawn. setCursor(x, y) places it, with (x, y) being the top-left corner of the first cell. print() and println() behave as they do on Serial, so you can print numbers, floats, and F() strings. println() moves the cursor to the start of the next line, and text wraps automatically at the right edge.
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
Adafruit_SSD1306 display(128, 64, &Wire, -1);
void setup() {
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
for (;;) {}
}
display.clearDisplay();
display.setTextColor(SSD1306_WHITE);
display.setTextSize(1);
display.setCursor(0, 0);
display.println(F("Size 1"));
display.setTextSize(2);
display.println(F("Size 2"));
display.setTextSize(1);
display.print(F("Pi = "));
display.println(3.14159, 2); // prints 3.14
display.display();
}
void loop() {}Two details matter here. First, the text size and cursor persist until you change them, so set them before each block of text instead of assuming defaults. Second, the F() macro keeps string literals in flash instead of RAM. On a board with 2 KB of RAM, such as the Uno, this matters, because the frame buffer already takes half of it.
Inverted text and text bounds
Passing two colors to setTextColor() draws a background behind each character:
display.setTextColor(SSD1306_BLACK, SSD1306_WHITE); // black on whiteThis produces highlighted text, useful for menu selections. A single-color call leaves the background transparent, so the text is drawn over whatever is already in the buffer.
To center or right-align text, you need its size. getTextBounds() measures a string without drawing it:
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
Adafruit_SSD1306 display(128, 64, &Wire, -1);
void setup() {
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
for (;;) {}
}
display.clearDisplay();
display.setTextSize(2);
display.setTextColor(SSD1306_WHITE);
const char *msg = "READY";
int16_t x1, y1;
uint16_t w, h;
display.getTextBounds(msg, 0, 0, &x1, &y1, &w, &h);
display.setCursor((display.width() - w) / 2, (display.height() - h) / 2);
display.print(msg);
display.display();
}
void loop() {}getTextBounds() returns the bounding box in x1, y1, w, and h. The width w is what you need for centering. Calling display.width() and display.height() instead of typing 128 and 64 keeps the code correct if you change panels.
Drawing lines
GFX has special-purpose line functions, and they are faster than the general one when the line is straight.
| Function | Draws |
|---|---|
| `drawPixel(x, y, color)` | One pixel |
| `drawLine(x0, y0, x1, y1, color)` | Any straight line |
| `drawFastHLine(x, y, w, color)` | Horizontal line of width `w` |
| `drawFastVLine(x, y, h, color)` | Vertical line of height `h` |
Note that the fast versions take a length, not an end coordinate. A common mistake is passing the end x where the width belongs.
Drawing shapes
Every shape comes in two forms: draw... for an outline and fill... for a solid shape.
| Outline | Filled | Arguments |
|---|---|---|
| `drawRect` | `fillRect` | x, y, w, h, color |
| `drawRoundRect` | `fillRoundRect` | x, y, w, h, corner radius, color |
| `drawCircle` | `fillCircle` | center x, center y, radius, color |
| `drawTriangle` | `fillTriangle` | three x, y points, color |
Rectangles take the top-left corner plus width and height. Circles take the center plus the radius. A circle at (64, 32) with radius 20 spans x from 44 to 84.
The following sketch draws one of each on a single frame:
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
Adafruit_SSD1306 display(128, 64, &Wire, -1);
void setup() {
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
for (;;) {}
}
display.clearDisplay();
display.drawRect(0, 0, 40, 28, SSD1306_WHITE);
display.fillRoundRect(46, 0, 40, 28, 6, SSD1306_WHITE);
display.drawCircle(106, 14, 13, SSD1306_WHITE);
display.fillTriangle(20, 36, 0, 63, 40, 63, SSD1306_WHITE);
display.drawLine(46, 36, 127, 63, SSD1306_WHITE);
display.drawFastHLine(46, 36, 82, SSD1306_WHITE);
display.fillCircle(106, 50, 6, SSD1306_INVERSE);
display.display();
}
void loop() {}The last call uses SSD1306_INVERSE. The circle at (106, 50) with radius 6 overlaps the diagonal line, and inverse mode shows the overlap as a gap in the filled circle. This is a quick way to draw a cursor or marker that stays visible over any background.
Common patterns
A progress bar
A progress bar is an outline plus a filled rectangle whose width scales with the value. Use constrain() so a reading outside the expected range cannot draw past the border:
void drawBar(int x, int y, int w, int h, int value, int maxValue) {
int fill = map(constrain(value, 0, maxValue), 0, maxValue, 0, w - 4);
display.drawRect(x, y, w, h, SSD1306_WHITE);
display.fillRect(x + 2, y + 2, fill, h - 4, SSD1306_WHITE);
}The fill is inset by two pixels so it does not touch the border. The helper assumes display is the global object from the earlier sketches.
Clearing part of the screen
clearDisplay() wipes the whole buffer. To redraw only one region, paint a black rectangle over it first:
display.fillRect(0, 16, 128, 16, SSD1306_BLACK);Then draw the new content in that region. Remember that nothing is shown until display().
Common errors
- Blank screen after drawing. You forgot
display(). Every drawing sequence must end with it. - Leftover pixels from the previous frame. You did not call
clearDisplay()or paint over the old region. The buffer keeps everything you drew. - Text is invisible. You never called
setTextColor(). Set it once afterbegin(). - Shape appears in the wrong place or is missing. Check that Y grows downward and that you passed width and height, not an end point, to
drawRect()and the fast line functions. - Text wraps or is cut off. At size 2, only 10 characters fit on a 128 px row. Measure with
getTextBounds(), or use a smaller size. - Sketch crashes or behaves oddly on an Uno. The frame buffer uses 1 KB of the 2 KB of RAM. Long strings not wrapped in
F()push you out of memory.
Exercises
Exercise
A sketch draws a rectangle with drawRect(10, 10, 50, 20, SSD1306WHITE) and then a horizontal line with drawFastHLine(10, 40, 100, SSD1306WHITE). The screen stays blank. List the first thing you would check, and give the x range the line covers.
Show answer
Check that display.display() is called after the drawing calls, because drawing only changes the RAM buffer. The line starts at x = 10 and has a width of 100, so it covers x = 10 through 109.
Exercise
You want to print the word "OK" at text size 3 centered horizontally on a 128x64 display. Each character cell is 18 pixels wide at that size. What x value do you pass to setCursor(), ignoring the trailing spacing column? What function would give you the exact width instead of calculating it by hand?
Show answer
Two characters at 18 pixels each give 36 pixels, so x = (128 - 36) / 2 = 46. The function getTextBounds() returns the exact width of a string, which you can use in the formula (display.width() - w) / 2.