U8g2 is a free graphics library by Oliver Kraus for monochrome OLED and LCD screens: you add #include <U8g2lib.h>, create one display object whose name describes your screen, then draw text, shapes and bitmaps into memory and send them to the display. It supports dozens of display controllers, so the only hard part is picking the constructor that matches yours, and for the OLED in the 30 Days Lost in Space kit that is U8G2_SH1106_128X64_NONAME_F_HW_I2C.
Everything below was written for the HERO Board (Uno-compatible, ATmega328P, 2 KB of RAM), and every sketch on this page was compiled and run in our simulator before it went up.
Install U8g2 and Include U8g2lib.h
In the Arduino IDE, open Tools > Manage Libraries, search for U8g2 and install the one by oliver. Then start your sketch with two includes:
#include <U8g2lib.h> // the U8g2 graphics library
#include <Wire.h> // I2C, the two-wire bus the OLED talks over
U8g2lib.h is the header for the U8g2 class you use in sketches. The same download also contains U8x8lib.h, a smaller text-only version, covered in the FAQ.
Wire the OLED
| OLED pin | HERO Board pin | |----------|----------------| | VCC | 5V | | GND | GND | | SDA | A4 | | SCL | A5 |
A4 and A5 are the board's hardware I2C pins, and the display answers at I2C address 0x3C. Four wires drive all 8,192 pixels. The OLED display guide covers the screen itself, and the I2C guide covers the bus.
Read the Constructor Name
Every U8g2 constructor name is a small spec sheet. This is the line the 30 Days lessons use:
U8G2_SH1106_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE);
| Part | What it means | |------|---------------| | SH1106 | The controller chip on the display | | 128X64 | The resolution in pixels | | NONAME | The generic version of the module (other names cover specific modules and settings) | | F | Full frame buffer: the whole picture in RAM. 1 and 2 are page buffers | | HW_I2C | Hardware I2C on A4 and A5. SW_I2C works on any two pins, more slowly | | u8g2 | The name you give your display object; the lessons call theirs lander_display | | U8G2_R0 | Rotation: R0 normal, R1 90 degrees, R2 180, R3 270 | | U8X8_PIN_NONE | No reset pin is wired. You can leave this argument out |
SH1106, Not SSD1306
Most U8g2 tutorials use the SSD1306 constructor because that is the most common OLED chip. The kit's OLED uses the SH1106. The SH1106 keeps 132 columns of memory for a 128-pixel panel, so SSD1306 code compiles, runs, and then draws a picture that is shifted or full of noise on the real screen. When a tutorial's picture comes out wrong, change only the controller in the name:
U8G2_SH1106_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0); // the kit's OLED
// U8G2_SSD1306_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0); // most tutorials: wrong picture on an SH1106
Full Buffer or Page Buffer
The letter after NONAME decides how much of the HERO Board's 2,048 bytes of RAM the screen takes, and how you draw:
| Constructor | RAM | How you draw | Where it's used | |-------------|-----|--------------|-----------------| | _F_ | 1,024 bytes | clearBuffer(), draw, sendBuffer() | 30 Days, Days 21 and 22 | | _2_ | 256 bytes | firstPage(), then do { draw } while (nextPage()); | 30 Days, Days 23 to 29 | | _1_ | 128 bytes | the same loop, 8 strips instead of 4 | our simulator's verified examples |
The full buffer is the easiest: draw everything, then send the finished picture. It costs half the board's RAM, so once a sketch grows (a keypad, a 4-digit display, arrays), switch to _2_ or _1_. Day 23 of the course does exactly that to make room for its launch sequence.
In page mode U8g2 draws the screen in horizontal strips and runs your drawing code once per strip. Two rules follow: everything you draw goes inside the do { } while (u8g2.nextPage()); loop, and the values it draws must not change between passes, so read sensors and do your math before firstPage().
Example 1: Hello World with a Full Buffer
Adapted from the 30 Days Day 21 lesson, which centers its text the same way:
// Hello on the kit's OLED, adapted from the 30 Days Day 21 lesson.
#include <U8g2lib.h>
#include <Wire.h>
// SH1106 controller, 128x64, full frame buffer (_F_), hardware I2C on A4 (SDA) and A5 (SCL)
U8G2_SH1106_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE);
void setup() {
u8g2.begin();
u8g2.setFont(u8g2_font_ncenB08_tr);
}
void loop() {
u8g2.clearBuffer(); // 1. wipe the picture in memory
u8g2.drawStr(0, 12, "Exploration Lander"); // 2. draw: y = 12 is the bottom of the letters
const char* message = "Hello World!";
int x = (u8g2.getDisplayWidth() - u8g2.getStrWidth(message)) / 2; // centred
u8g2.drawStr(x, 36, message);
u8g2.drawFrame(0, 44, 128, 20); // an outlined box
u8g2.sendBuffer(); // 3. send the whole picture to the screen
delay(500);
}
The y in drawStr(x, y, text) is the baseline, the bottom of the capital letters, so drawStr(0, 12, ...) puts an 8-pixel-high font fully on screen. getStrWidth() measures a string in the current font, which is how you center text: the screen width minus the text width, halved.
Example 2: Show a Live Number and a Bar
U8g2 inherits from the same Print class as Serial, so print() handles numbers for you. Wire a photoresistor divider to A0 (see the photoresistor guide) and show the light level:
// Light gauge: a big number and a bar, redrawn 10 times a second.
#include <U8g2lib.h>
#include <Wire.h>
U8G2_SH1106_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0);
const int SENSOR_PIN = A0; // photoresistor and 10k resistor
void setup() {
u8g2.begin();
}
void loop() {
int percent = map(analogRead(SENSOR_PIN), 0, 1023, 0, 100);
u8g2.clearBuffer();
u8g2.setFont(u8g2_font_6x10_tr);
u8g2.drawStr(0, 10, "LIGHT LEVEL");
u8g2.setFont(u8g2_font_ncenB18_tr);
u8g2.setCursor(0, 40);
u8g2.print(percent); // print() works like Serial.print()
u8g2.print("%");
u8g2.drawFrame(0, 50, 128, 12); // the bar's outline
u8g2.drawBox(2, 52, map(percent, 0, 100, 0, 124), 8); // the fill
u8g2.sendBuffer();
delay(100);
}
setCursor() sets where print() starts, using the same baseline rule as drawStr(). drawFrame() draws the bar's outline and drawBox() fills it, with map() turning 0 to 100 percent into 0 to 124 pixels.
Example 3: A Bitmap in Page Mode
This sketch uses the _1_ constructor, so the whole screen costs 128 bytes of RAM, and draws a small picture six times:
// A bitmap in page-buffer mode: 128 bytes of RAM instead of 1,024.
#include <U8g2lib.h>
#include <Wire.h>
U8G2_SH1106_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0);
// 8 x 8 pixels in XBM format: one byte per row, the leftmost pixel is the lowest bit
static const unsigned char SMILE[] U8X8_PROGMEM = {
0x3C, 0x42, 0xA5, 0x81, 0xA5, 0x99, 0x42, 0x3C
};
void setup() {
u8g2.begin();
}
void loop() {
u8g2.firstPage();
do { // runs once per strip: draw the whole screen every time
u8g2.setFont(u8g2_font_6x10_tr);
u8g2.drawStr(0, 10, "Crew status: happy");
for (int i = 0; i < 6; i++) {
u8g2.drawXBMP(8 + i * 20, 28, 8, 8, SMILE);
}
u8g2.drawRFrame(0, 20, 128, 24, 4); // a box with rounded corners
} while (u8g2.nextPage());
delay(1000);
}
drawXBMP() draws an image in XBM format: one bit per pixel, rows padded to whole bytes, and the leftmost pixel of each row in the lowest bit. U8X8_PROGMEM keeps the image in flash instead of RAM. Days 26 to 29 of the course draw their pictures the same way, and Day 26 fills the whole screen with drawXBMP(0, 0, 128, 64, image). Image editors such as GIMP can export a black-and-white picture as an .xbm file whose contents you paste into the array.
Text and Fonts
Font names describe the font. u8g2_font_ncenB08_tr is New Century Schoolbook (ncen), Bold (B), size 8 (08), with transparent background (t) and the reduced character set (r: the printable ASCII characters). Fonts ending in _tn hold only digits and a few symbols, which saves flash; _tf holds the full set. The course uses u8g2_font_ncenB08_tr on Day 21 and u8g2_font_6x10_tr from Day 23 on. For big numbers, try u8g2_font_ncenB14_tr, u8g2_font_ncenB18_tr or u8g2_font_ncenB24_tr.
If you'd rather position text by its top edge, call u8g2.setFontPosTop() once after setFont(). Then y is the top of the text, which is what the course does from Day 21 on.
The Calls You'll Use Most
| Call | What it does | |------|--------------| | begin() | Starts the display. Once, in setup() | | clearBuffer() / sendBuffer() | Wipe the picture in RAM / send it to the screen (full buffer) | | firstPage() / nextPage() | The drawing loop for page buffers | | setFont(font) | Font for the text drawn after it | | drawStr(x, y, text) | Text, y at the baseline | | setCursor(x, y) then print(value) | Numbers and variables, like Serial.print() | | getStrWidth(text) / getMaxCharHeight() | Measure text, for centering and line spacing | | drawPixel, drawLine, drawHLine, drawVLine | Dots and lines | | drawFrame / drawBox | Rectangle outline / filled rectangle | | drawRFrame / drawRBox | Rounded rectangle; the last argument is the corner radius | | drawCircle / drawDisc | Circle outline / filled circle | | drawTriangle | Filled triangle | | drawXBMP(x, y, w, h, image) | Bitmap stored in flash | | setDrawColor(c) | 1 draws lit pixels, 0 draws dark ones, 2 inverts what's there | | setContrast(0 to 255) | Brightness | | setDisplayRotation(U8G2_R2) | Turn the picture after begin(): Day 21's fix for upside-down text |
Coordinates start at (0, 0) in the top-left corner; x grows to the right up to 127 and y grows downward up to 63.
Common Mistakes
- The SSD1306 constructor on an SH1106 screen. It compiles and runs, and the picture comes out shifted or as noise. Use the SH1106 line above.
- Text at y = 0. With the default baseline,
drawStr(0, 0, "Hi")draws above the screen and you see nothing. Use a y at least as big as the font's height, or callsetFontPosTop(). - Drawing without sending. With
_F_, nothing appears untilsendBuffer(). With_1_or_2_, anything drawn outside thedo { } while (u8g2.nextPage());loop never reaches the screen. - Running out of RAM. A full buffer takes 1,024 of the board's 2,048 bytes. If the board resets or prints garbage after you add the display, switch to
_2_or_1_and wrap fixed text forSerialinF("..."). - Printing decimals with sprintf(). On this board
sprintf()doesn't support%f: in our testsprintf(line, "v=%f", 3.14)producedv=?. Useu8g2.print(value, 2)for two decimals, ordtostrf()to make the string.
A screen that stays completely dark has its own checklist in Display Shows Nothing (OLED).
Frequently Asked Questions
What is the difference between U8g2 and U8x8?
U8g2 is the graphics side: fonts of any size, shapes and bitmaps, drawn into a buffer. U8x8 comes in the same download and writes 8 × 8 pixel characters straight to the display with no buffer, so it needs almost no RAM, but it can't draw lines, shapes or large fonts. On the kit's OLED it looks like this:
#include <U8x8lib.h>
#include <Wire.h>
U8X8_SH1106_128X64_NONAME_HW_I2C u8x8(/* reset=*/ U8X8_PIN_NONE);
void setup() {
u8x8.begin();
u8x8.setFont(u8x8_font_chroma48medium8_r);
u8x8.drawString(0, 0, "Hello"); // column 0, row 0 of a 16 x 8 grid
u8x8.drawString(0, 2, "No buffer");
}
void loop() {
}
Which U8g2 constructor do I use for a 128x64 I2C OLED?
Match the controller chip. For the SH1106 in the 30 Days kit: U8G2_SH1106_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0); (or _1_ / _2_ to save RAM). For an SSD1306 module: U8G2_SSD1306_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0);. If you don't know the chip, try both and keep the one whose picture lines up with the edges of the glass.
How do I display a variable with U8g2?
Use setCursor(x, y) and then print(value), exactly like Serial.print(). For a float, print(value, 1) shows one decimal. To build a string first, sprintf() works for whole numbers; for decimals use dtostrf().
My display uses address 0x3D. How do I tell U8g2?
Call u8g2.setI2CAddress(0x3D * 2); before u8g2.begin(). U8g2 expects the address shifted left by one bit, which is why it's doubled. The kit's OLED uses the default, 0x3C, and needs no call.
Why is U8g2lib.h "not found" when I compile?
The library isn't installed in the IDE you're compiling with. Install U8g2 by oliver from Tools > Manage Libraries and compile again.