Sub topic 11
How much RAM the OLED frame buffer uses
This chapter explains where an SSD1306 OLED's memory goes and how to calculate it. It also shows how to measure it on a running board and what to do when a sketch runs out. It assumes you can already show text on an SSD1306 with the Adafruit libraries. It also assumes you know what setup(), loop(), global variables and the F() macro are. The examples target an Arduino Uno, which has an ATmega328P with 2048 bytes of RAM, but the arithmetic applies to any board.
Why the display costs RAM
The SSD1306 controller has its own display memory, but the Adafruit library cannot read it back over I2C. Instead, Adafruit_SSD1306 keeps a full copy of the screen in the microcontroller's RAM. This copy is the frame buffer.
Every drawing call such as print(), drawRect() or drawPixel() changes bytes in that buffer only. Nothing appears on the screen until display() sends the whole buffer over I2C. This is why clearDisplay() plus a redraw gives clean frames, and it is also why the buffer must stay in RAM for as long as the display is in use.
The arithmetic
The display is monochrome, so each pixel needs one bit. The controller organizes memory in horizontal bands called pages. Each page is 8 pixels tall, and each byte holds one column of 8 vertical pixels.
The buffer size in bytes is:
bytes = width * ceil(height / 8)In integer arithmetic, ceil(height / 8) is (height + 7) / 8.
| Resolution | Pages | Buffer size | Share of Uno RAM (2048 bytes) |
|---|---|---|---|
| 128x64 | 8 | 1024 bytes | 50% |
| 128x32 | 4 | 512 bytes | 25% |
| 96x16 | 2 | 192 bytes | about 9% |
| 64x48 | 6 | 384 bytes | about 19% |
A 128x64 screen has 8192 pixels, which is 8192 bits, which is 1024 bytes. The page rounding only matters when the height is not a multiple of 8.
The size depends only on resolution. Text size, how much is drawn, and whether the screen is mostly black make no difference. A blank screen costs as much RAM as a full one.
How pixels map to bytes
The library stores the buffer as one flat array, page by page. For a pixel at (x, y) on a display WIDTH pixels wide:
- The byte index is
x + (y / 8) * WIDTH. - The bit inside that byte is
y % 8, where bit 0 is the top pixel of the page.
You can check this with getBuffer(), which returns a pointer to the array:
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
const uint8_t WIDTH = 128;
const uint8_t HEIGHT = 64;
Adafruit_SSD1306 display(WIDTH, HEIGHT, &Wire, -1);
void setup() {
Serial.begin(9600);
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation or init failed"));
for (;;) {}
}
display.clearDisplay();
display.drawPixel(10, 20, SSD1306_WHITE);
uint8_t x = 10;
uint8_t y = 20;
uint16_t index = x + (y / 8) * WIDTH;
uint8_t mask = 1 << (y % 8);
uint8_t *buffer = display.getBuffer();
Serial.print(F("Byte index: "));
Serial.println(index);
Serial.print(F("Pixel set in buffer: "));
Serial.println((buffer[index] & mask) != 0 ? F("yes") : F("no"));
}
void loop() {}The sketch prints a byte index of 138 (10 + 2 64... see below) and yes. Check the index yourself: y / 8 is 2 and WIDTH is 128, so the index is 10 + 2 128 = 266. The serial monitor shows 266, and bit 4 of that byte is set.
You rarely need to touch the buffer directly, but the layout explains two things you will see later. Vertical lines are cheap to draw, and every drawing operation costs CPU time proportional to the number of bytes it changes.
Where the buffer lives
The buffer is not a global array, and this has three consequences.
- The constructor
Adafruit_SSD1306 display(128, 64, &Wire, -1);does not allocate the buffer. The object itself is small. display.begin()callsmalloc()to allocate the buffer on the heap. If the heap does not have a free block that large,begin()returnsfalse.- The IDE's compile report does not count the buffer. The line "Global variables use ... bytes of dynamic memory" can show a comfortable number, such as 30%, and the sketch can still fail at runtime.
The sketches in the library examples treat a false return from begin() as a fatal error and loop forever. On a board with little free RAM, a display that stays blank for no visible reason is often this allocation failure. The serial message in the sketch above is the quickest way to confirm it.
The rest of RAM
On an Uno, the 2048 bytes are shared by several things:
- Global and static variables, including every string literal that is not wrapped in
F(). - The heap, where the display buffer goes.
- The stack, which grows downward from the top of RAM as functions are called.
- Library buffers.
Serialkeeps a 64-byte receive buffer and a 64-byte transmit buffer.Wirekeeps 32-byte buffers for receiving and transmitting, with more inside its low-level TWI layer.
After the 1024-byte display buffer and roughly 300 bytes of library overhead, a 128x64 display on an Uno leaves about 700 bytes for the whole rest of your program. The Adafruit library's own documentation warns that 128x64 screens work on an Uno only if the rest of the sketch is small.
The danger is not a clean error. If the stack grows down into the heap, or the heap grows up into the stack, variables change value for no obvious reason, and the board may reset or hang. These failures are intermittent and often appear only on certain code paths.
Measuring free RAM
You can measure rather than guess. On AVR boards, the gap between the heap end and the current stack pointer is the free memory:
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
Adafruit_SSD1306 display(128, 64, &Wire, -1);
#ifdef __AVR__
extern int __heap_start, *__brkval;
int freeRam() {
int v;
return (int)&v - (__brkval == 0 ? (int)&__heap_start : (int)__brkval);
}
#else
int freeRam() {
return -1; // not implemented for this architecture
}
#endif
void setup() {
Serial.begin(9600);
Serial.print(F("Free RAM before begin(): "));
Serial.println(freeRam());
bool ok = display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
Serial.print(F("begin() returned: "));
Serial.println(ok ? F("true") : F("false"));
Serial.print(F("Free RAM after begin(): "));
Serial.println(freeRam());
}
void loop() {}On an Uno, the "after" number is about 1024 bytes lower than the "before" number, plus a couple of bytes that malloc() uses for bookkeeping. If the "before" number is below about 1100, begin() fails.
Two details matter when you use this function:
- It reports the gap at the moment you call it. A function that is deeper in the call chain later will use more stack, so leave a margin of at least 100 to 200 bytes.
- On non-AVR boards it returns -1 here. ESP32 and ESP8266 expose
ESP.getFreeHeap(), and most ARM cores have their own equivalents. Those boards have tens or hundreds of kilobytes of RAM, so a 1 KB buffer rarely matters.
Freeing RAM
When the numbers do not fit, work down this list from cheapest change to biggest.
- Move string literals to flash.
Serial.println("Starting up")copies the string into RAM at boot.Serial.println(F("Starting up"))keeps it in flash. The Adafruit examples useF()throughout, as doesdisplay.println(F("Hello, OLED")). A sketch with many messages can free several hundred bytes this way. - Use smaller types. Use
uint8_tinstead ofintfor values below 256, and avoid large global arrays. Check for lookup tables that could be declared withPROGMEM. - Avoid the
Stringclass. It allocates on the heap, fragments free memory, and can leavebegin()without a block big enough when it runs after your code has already churned the heap. Allocate the display first (callbegin()early insetup()), or usechararrays withsnprintf()ordtostrf(). - Shrink buffers you control. Reduce a
Serialbuffer size only if you are comfortable editing the core, which most projects should avoid. Reading fewer bytes per call is safer. - Choose a 128x32 display. It halves the cost to 512 bytes. This is a fair trade if your content is two or three lines of text.
- Change the board. An Arduino Mega has 8 KB of RAM, and many 32-bit boards have far more. A 1 KB buffer is then insignificant.
Page-buffer alternatives
A full buffer is only one design. The U8g2 library supports the SSD1306 with three buffer modes, chosen by the suffix in the constructor name:
| Suffix | Buffer held in RAM (128x64) | Behavior |
|---|---|---|
| `_1_` | 128 bytes (one page) | Redraw the scene once per page in a loop |
| `_2_` | 256 bytes (two pages) | Same loop, two pages per pass |
| `_F_` | 1024 bytes (full) | Draw once, send once, like Adafruit |
In page mode you wrap your drawing code in firstPage() and nextPage(), and the library runs it 8 times (or 4 times in _2_ mode), each time keeping only one slice of the screen. You trade RAM for CPU time and an awkward drawing loop. It is a good fit for an Uno that also needs a lot of RAM for sensors, but it is not needed when memory is plentiful. Check the U8g2 documentation for the exact constructor name for your controller and wiring.
Common mistakes
- Assuming content changes the size. A screen with one character costs the same as a full one.
- Declaring a second display object. Two 128x64 displays on an Uno would need 2048 bytes of buffer alone. This cannot work.
- Calling
begin()late. After hundreds of allocations and frees, the heap may have no 1 KB contiguous block even though the total free memory looks sufficient. Initialize the display before anything else that allocates. - Ignoring the return value. Without a check on
begin(), the sketch continues, and every later call writes through a null buffer pointer. The result is a blank screen or a crash, with no message. - Measuring free RAM only once. A reading taken in
setup()does not include the stack used inside deeply nested calls orprintf-style formatting later inloop(). Print the value from inside the deepest code path too.
Exercise
You plan to use a 128x64 SSD1306 on an Arduino Uno. The IDE reports "Global variables use 1190 bytes (58%) of dynamic memory, leaving 858 bytes for local variables." Will display.begin() succeed, and what would you do?
Show answer
Probably not. The frame buffer needs 128 * (64 / 8) = 1024 bytes, which is more than the 858 bytes left, and the buffer is not included in the compiler's figure. begin() would return false, and the display would stay blank. First wrap string literals in F() and shrink global data, aiming to free at least 1024 bytes plus 200 to 300 bytes of margin for the stack and the Wire and Serial buffers. If that is not enough, switch to a 128x32 display (512 bytes), use U8g2 in page-buffer mode, or move to a board with more RAM.
Exercise
What is the frame buffer size, in bytes, for a 128x32 SSD1306, and what is the index in the buffer of the byte that holds pixel (x = 5, y = 17)? Which bit of that byte is that pixel?
Show answer
The size is 128 (32 / 8) = 512 bytes. The pixel is in page 17 / 8 = 2, so the index is 5 + 2 128 = 261. The bit within the byte is 17 % 8 = 1, so it is bit 1 (mask 0b00000010).