Embedded HandbookApps
All sections › III. Peripherals
STM32F411, STM32F407, STM32F429 · level intermediate · 16 min read
Open in the interactive handbook

22р. LVGL: a graphical interface on a display — buffers, flush with DMA, touch, tick and a memory estimate

Section 22а says that any interface library asks the firmware for four things: where to draw, how to hand over what was drawn, time and input. Sections 22о and 22п cover the ILI9341 display on SPI with DMA and the FT6236 capacitive touch controller. Here these parts are assembled for the most widespread free library — LVGL version 9: how it is built, which buffers to give it and what that costs in RAM, how to write a flush callback that hands over a strip via DMA without waiting for it, how to connect the touch panel, where to get the tick and how to run lv_timer_handler, and how to work out with a formula whether all this fits into the chosen part.

Basis. The port is alg.c: the flush callback, the DMA handler, touch, the tick, the first screen. On the computer it is built with gcc 12.2.0 (stm-sys:1, -Wall -Wextra -Werror) not with the real LVGL but with the stub lvgl_stub.h, which contains only the needed functions with LVGL 9 signatures as they are described here. The stub "draws" a frame in strips the same way LVGL does in partial mode and calls the flush callback; the panel model assembles the bytes sent over the wire into a picture and compares it with a reference. This checks the arithmetic of the window, the byte order and the order of calls — not the library itself. The tables of buffers, the RAM budget and the transfer time are computed by the same program and recomputed in Python. Check the names of LVGL functions, constants and behaviour against the documentation of your version: this code was not built with the real LVGL here, and the API was refined between 9.x releases. Cycles and drawing time were not measured on silicon.

Terms used in the documentation

Original Meaning
draw buffer the memory LVGL draws into before sending to the display
render mode PARTIAL / DIRECT / FULL rendering mode: in strips into a small buffer, straight into the frame or the whole frame at once
flush callback the port function that hands the drawn area over to the display
lv_display_flush_ready the message to the library "the area is handed over, the buffer is free"
input device (indev) an input device: touch panel, buttons, encoder
lv_timer_handler the LVGL timer handler: drawing, animations, input polling
lv_conf.h the LVGL settings file: colour depth, heap, fonts, modules
LV_MEM_SIZE the size of LVGL's own heap for objects and styles
invalidated area the part of the screen that needs to be redrawn

In plain words. LVGL is an artist who cannot talk to the display. You give it a canvas smaller than the screen and say: "when you have drawn a piece — call me, I will carry it". It draws a strip, calls your function, you start DMA and return at once, and when DMA has delivered the strip, you tell the artist "the canvas is free". Plus a clock it lives by, and the user's hands — the touch panel.


22р.1 What LVGL is and what it asks of the firmware

LVGL is an open-source C library (MIT licence): widgets (buttons, lists, sliders, charts), styles, anti-aliased fonts, animations, touch handling. It knows nothing about any display: all the hardware is in the port that you write. From the port it needs:

  1. A draw buffer — one or two, partial or full-frame (22р.2).
  2. A flush callback — hand the drawn area to the display and report when the buffer is free (22р.3).
  3. An input device — a function "is there a touch and where" (22р.5).
  4. Time — milliseconds on which animations, redrawing and input polling live (22р.6).
  5. A regular call of lv_timer_handler() from the main loop or a task.

Initialising the port is three lines for the display and three for the touch panel, after lv_init():

void lv_port_display_init(bool spi16)
{
    swap_bytes = !spi16; /* в 16-битном режиме SPI байты меняет сама шина */
    disp = lv_display_create(LCD_W, LCD_H);
    lv_display_set_color_format(disp, LV_COLOR_FORMAT_RGB565);
    lv_display_set_buffers(disp, buf1, buf2, sizeof buf1, LV_DISPLAY_RENDER_MODE_PARTIAL);
    lv_display_set_flush_cb(disp, flush_cb);
}

Build settings are in lv_conf.h: colour depth (LV_COLOR_DEPTH 16 for RGB565), the heap size LV_MEM_SIZE, the enabled fonts and widgets. Every unused widget and font switched off there is flash saved.


22р.2 Buffers: partial, double, full frame

The main decision of the port is how much memory to give for drawing. The LVGL 9 modes:

Buffers for different screens in RGB565 (2 bytes per pixel):

Screen RGB565 frame 1/10 strip two 1/10 strips
ST7735 128×160 40960 4096 8192
ST7789 240×240 115200 11520 23040
ILI9341 320×240 153600 15360 30720
LTDC 480×272 261120 25920 51840
LTDC 800×480 768000 76800 153600

The LVGL documentation advises a partial buffer of at least a tenth of the screen: less means more flush calls, more window overhead and more often one widget redrawn in pieces. For the ILI9341 this is 24 lines of 320 pixels — 15360 bytes:

#define LCD_W 320
#define LCD_H 240
#define BYTES_PER_PX 2 /* RGB565 */
#define BUF_LINES 24   /* десятая часть экрана */
#define BUF_BYTES (LCD_W * BUF_LINES * BYTES_PER_PX)

static uint8_t buf1[BUF_BYTES] __attribute__((aligned(4)));
static uint8_t buf2[BUF_BYTES] __attribute__((aligned(4)));

The second buffer lets LVGL draw the next strip while DMA carries the previous one (22р.8). LVGL 9 requires 4-byte alignment of the buffers (the LV_DRAW_BUF_ALIGN parameter in lv_conf.h), and DMA with 32-bit words does not work without it. The buffers must be in memory that DMA can see: on the F407 that is SRAM1 and SRAM2, not CCM (section 22о.3).


22р.3 A flush callback with DMA

The flush callback receives the rectangle area and a pointer to the pixels. Its job is to set the window on the display and start the transfer. Waiting for the end of the transfer in the callback is not allowed: then the processor idles for the whole SPI time and the double buffer loses its point.

static void flush_cb(lv_display_t *d, const lv_area_t *area, uint8_t *px_map)
{
    uint32_t w = (uint32_t)(area->x2 - area->x1 + 1); /* границы включительно */
    uint32_t h = (uint32_t)(area->y2 - area->y1 + 1);
    if (swap_bytes)
        lv_draw_sw_rgb565_swap(px_map, w * h);
    panel_set_window(area->x1, area->y1, area->x2, area->y2);
    panel_dma_start(px_map, w * h * BYTES_PER_PX); /* вернуться сразу, не дожидаясь DMA */
    (void)d;
}

panel_set_window and panel_dma_start are driver functions from section 22о: the CASET/RASET/RAMWR commands and starting a DMA stream on SPI. The end of the transfer comes as a DMA interrupt, and from there LVGL learns that the buffer is free:

void panel_dma_done_isr(void)
{
    lv_display_flush_ready(disp);
}

A subtlety from 22о.2: the "DMA finished" flag is raised when the last byte has been handed to SPI, not when it has left over the wire. If CS is raised or D/C is switched for the next command right after that, the last byte will be corrupted. In the handler, before lv_display_flush_ready or at the start of the next panel_set_window, wait for TXE = 1 and BSY = 0.

The model run: a 320 × 240 frame went out in 10 flush calls, 24 lines each; the stub "waited" for a buffer to be freed 9 times — before every strip except the first; 153710 bytes went over the wire — 153600 bytes of pixels and 10 windows of 11 bytes. The picture on the model glass matched the reference in all 76800 pixels.


22р.4 Byte order and the window: two mistakes out of nowhere

Byte order. LVGL keeps an RGB565 pixel as a uint16_t, that is, in Cortex-M memory the low byte comes first. The ILI9341 expects the high byte first over the wire (section 22а.3). There are two solutions:

The model ran all three cases:

Bus and port wrong pixels out of 76800
8-bit, bytes swapped in flush 0
16-bit, no swap 0
8-bit, swap forgotten 76486

Without the swap almost all pixels are wrong — only the 314 whose high and low bytes happen to coincide stayed correct. On the screen this is recognised at once: the colours are "acid", white stays white, black stays black, and everything else is mixed up.

The window. The area bounds in LVGL are inclusive: a full-width strip is x1 = 0, x2 = 319. The width is x2 - x1 + 1. Forget the +1 and the window is one pixel narrower, there are fewer data per line and per column, and each line shifts relative to the previous one. The model with this mistake corrupted 73610 pixels out of 76800 — a slanted "saw" across the whole screen.


22р.5 Touch: an input device

The touch panel is connected as an input device of the "pointer" type. LVGL polls it itself from lv_timer_handler (by default once every 33 ms, the LV_DEF_REFR_PERIOD setting — check with your version) and turns touches into press, click, long-press and scroll events. The port only has to say whether there is a touch and where:

static void touch_read_cb(lv_indev_t *indev, lv_indev_data_t *data)
{
    uint16_t x, y;
    if (touch_get(&x, &y)) {
        data->point.x = x;
        data->point.y = y;
        data->state = LV_INDEV_STATE_PRESSED;
    } else {
        data->state = LV_INDEV_STATE_RELEASED; /* point оставить прежним: LVGL помнит, где отпустили */
    }
    (void)indev;
}

touch_get is the FT6236 driver from section 22п: reading the report over I2C and converting the point from glass coordinates to screen coordinates taking rotation into account (22п.4). On release the coordinate is not touched: LVGL needs the point where the finger left the glass — it decides whether this was a click on a button or the finger slid off. In the run after release the point stayed (100, 50), and the state changed to "released".

Registration is three calls:

void lv_port_indev_init(void)
{
    lv_indev_t *touch = lv_indev_create();
    lv_indev_set_type(touch, LV_INDEV_TYPE_POINTER);
    lv_indev_set_read_cb(touch, touch_read_cb);
}

Reading over I2C inside the callback takes bus time (section 22п.6). If the touch controller gives an INT interrupt, the callback can simply return the last value read by the handler — then lv_timer_handler does not wait for the bus. Your own gestures (debouncing, holding) from 22п.5 are not needed with LVGL: the library does this itself.


22р.6 The tick and lv_timer_handler

LVGL needs to know the time in milliseconds. Two ways: call lv_tick_inc(1) once per millisecond from an interrupt or give the library a function that returns the time (lv_tick_set_cb, for example HAL_GetTick). The first is one line in SysTick:

void SysTick_Handler(void)
{
    lv_tick_inc(1);
}

In a HAL project a SysTick handler already exists (it calls HAL_IncTick) — the line is added there rather than creating a second one. Under FreeRTOS SysTick is taken by the kernel, and lv_tick_set_cb with a function returning the RTOS tick counter in milliseconds is more convenient.

The library's work is in lv_timer_handler(): it redraws the invalidated areas, runs animations, polls the touch panel. The function returns in how many milliseconds it must be called again:

uint32_t gui_loop_step(void)
{
    uint32_t idle = lv_timer_handler();
    return idle > 5 ? 5 : idle; /* не спать дольше 5 мс: сенсор опрашивается в этом же цикле */
}

The main loop calls gui_loop_step and sleeps for the returned time (__WFI until the next tick or a task delay). The upper limit is so as not to miss a touch if the rest of the firmware lives in the same loop. The stub in the run: the next timer at 30 ms, a call at 25 ms returned 5, at 35 ms — 0 (time to work); 1000 calls of SysTick_Handler gave exactly 1000 ms of library time.


22р.7 Memory: a formula and a budget

The RAM taken by LVGL with the port:

RAM ≈ draw buffers + LV_MEM_SIZE + the library's static data + stack.

The budget for a 320 × 240 screen on four parts — buffers plus heap, without static data and stack:

Setup for 320×240 buffers + heap F103C8 F411CE F407 (SRAM1+2) F429 (no CCM)
2 × 24 lines, 64 KB heap 96256 short by 75776 left 34816 left 34816 left 100352
1 × 24 lines, 32 KB heap 48128 short by 27648 left 82944 left 82944 left 148480
1 × 10 lines, 16 KB heap 22784 short by 2304 left 108288 left 108288 left 173824

Conclusions. The F103C8 with 20 KB does not fit even the most modest setup — and that is without static data, stack and the rest of the firmware; LVGL on it is not an option, for it there are the text screens of 22о.6. The F411 and F407 fit the full setup with two buffers, but after it 34 KB remain for everything else — tight if there is a USB stack or networking alongside; with one buffer and a 32 KB heap — roomy. The F429 with external SDRAM (section 22а.4) is already a whole frame and LTDC.

Flash: LVGL itself with a few widgets and one font takes hundreds of kilobytes; the exact figure depends on what is enabled in lv_conf.h and is visible in the .map. Every anti-aliased font is tens of kilobytes per size, and Cyrillic is not part of the standard fonts (Pitfalls).


22р.8 Frame time: strips and a double buffer

The transfer time of a strip is the pixel bytes plus 11 window bytes, multiplied by 8 and divided by the SPI frequency (as in 22о.2):

SPI 320×24 strip, ms frame of 10 strips, ms frame in one window, ms
18 MHz 6.832 68.32 68.27
21 MHz 5.856 58.56 58.52
42 MHz 2.928 29.28 29.26

Splitting into 10 strips costs almost nothing: 10 windows of 11 bytes added 0.02 ms to the frame at 42 MHz. The "frame in one window" figures match the table of 22о.2. But LVGL redraws the screen this fast only if the whole screen changes; usually a few widgets are invalidated, and only their strips go out.

A double buffer pays off when drawing and transfer run simultaneously:

Top — the path of a strip: lv_timer_handler draws a strip into buf1 or buf2 of 15360 bytes, flush_cb sets the window and starts DMA, SPI with DMA carries it to the ILI9341, the DMA interrupt calls lv_display_flush_ready; bottom — a time scale of the first four strips: with one buffer drawing and transfer take turns, with two they overlap; a model with strip drawing equal to the 2.928 ms transfer: a frame takes 58.6 ms with one buffer and 32.2 ms with two

With one buffer LVGL draws a strip, hands it over and waits until DMA delivers it — the frame time equals 10 × (R + T), where R is drawing a strip and T is the transfer. With two it draws the next one while the previous one travels: 10 × max(R, T) + min(R, T). The drawing time R was not measured on silicon here and depends strongly on the content (fills, anti-aliased text, shadows); if it is taken equal to the transfer at 42 MHz, the model gives 58.6 ms with one buffer and 32.2 ms with two. The gain of a double buffer is up to two times when R and T are comparable, and almost none when one is much larger than the other. Measure R yourself: the DWT CYCCNT counter before and after lv_timer_handler (section 75а) or the performance monitor built into LVGL (LV_USE_SYSMON).


22р.9 The first screen: a label and a button

After lv_init() and port initialisation the interface is created from objects. A screen, a label and a button with a click handler:

void gui_create(void)
{
    lv_obj_t *scr = lv_screen_active();
    label = lv_label_create(scr);
    lv_label_set_text(label, "Готов");
    lv_obj_t *btn = lv_button_create(scr);
    lv_obj_center(btn);
    lv_obj_add_event_cb(btn, button_cb, LV_EVENT_CLICKED, NULL);
}

The click handler is called from lv_timer_handler, not from an interrupt — other objects can safely be changed in it:

static void button_cb(lv_event_t *e)
{
    presses++;
    lv_label_set_text_fmt(label, "Нажатий: %u", presses); /* LVGL копирует строку к себе */
    (void)e;
}

In the run on the stub three calls of the handler gave the label Нажатий: 3 (Russian for "presses"). The text is copied into the LVGL heap — another reason to size LV_MEM_SIZE with a margin. And for Готов and Нажатий to appear on the screen rather than as empty rectangles, a font with Cyrillic is needed (Pitfalls).


22р.10 Threads and an RTOS

LVGL is not thread-safe: all lv_* calls come from one place. Under FreeRTOS the interface lives in its own low-priority task that runs lv_timer_handler; other tasks do not touch LVGL objects directly but send messages to the interface task through a queue (sections 27 and 125а). LVGL 9 also has the lv_lock()/lv_unlock() lock when OS support is enabled in lv_conf.h — check the documentation of your version; a message queue is simpler and does not hold a mutex for the duration of drawing.

The exception is lv_display_flush_ready and lv_tick_inc: they are called from interrupts, and the library allows this.


22р.11 Pitfalls

Waiting for DMA inside flush. while (dma_busy); in the callback — and the processor stands still for the whole transfer, the double buffer is useless. The callback returns at once, lv_display_flush_ready comes from the DMA interrupt.

flush_ready is never called. The DMA interrupt is not enabled or there is a transfer error — LVGL waits forever, the interface "freezes" after the first strip. Handle the DMA error too, and call lv_display_flush_ready in it as well.

Width without +1. The area bounds are inclusive: 73610 corrupted pixels in the model, a slanted saw across the screen.

RGB565 bytes in reverse order. An 8-bit SPI without swapping gives 76486 wrong pixels out of 76800, "acid" colours. A 16-bit SPI or lv_draw_sw_rgb565_swap.

A buffer in CCM. On the F407 DMA cannot see CCM: a buffer there means DMA sends garbage or fails with a bus error. Buffers go in SRAM1/SRAM2.

CS raised before the last byte. The DMA flag is raised before SPI has sent out the last byte; wait for TXE and BSY (22о.2).

Boxes instead of Russian letters. The standard LVGL fonts are Latin and icons. Cyrillic is generated with the LVGL font converter for the needed range (U+0400–U+04FF) and your own font is included; the source is in UTF-8.

lv_* from two tasks. Corrupted object lists, crashes in random places. One interface task, the others through a queue.

The heap ran out. Objects are not created, LVGL logs a lack of memory. lv_mem_monitor after visiting all screens, max_used with a margin.

The tick is not running. lv_tick_inc or lv_tick_set_cb was forgotten — the interface is drawn once, animations and presses do not work.


22р.12 Summary

Next: section 43 "Hardware cryptography: CRC, RNG, HASH, CRYP".

Open in the interactive handbook