嵌入式 Linux 下 LVGL 移植与性能优化实战LVGL Porting and Performance Optimization on Embedded Linux


AI free token/AI免费积分

嵌入式 Linux 下 LVGL 移植与性能优化实战

本文来源:https://www.hqwc.cn/a/1891039.html
若有版权问题,请来信告知:13951431913#139.com 或在右方提交评论。

做了几年嵌入式Linux开发,界面库这块我换过好几个方案。最开始用Qt,功能确实强,但对硬件要求高,机子稍微差一点就明显吃力。后来接触到LVGL,第一印象是“一个跑在MCU上的小图形库”,结果仔细试了试,发现它在嵌入式Linux上一样能打。这篇文章我把一次完整的LVGL移植与优化项目整理出来,覆盖方案选型、环境搭建、显示和输入打通、性能调优、常见坑点,希望能帮到正在做嵌入式HMI、智能面板、车载仪表或工控屏的朋友。

1. 项目定位与方案选型:为什么在嵌入式Linux上选LVGL

先聊方案选型。很多人听到LVGL,第一反应是“给单片机用的”,其实不准确。LVGL现在的定位是嵌入式图形库,并不限定MCU还是MPU。嵌入式Linux里跑LVGL,既能直接操作framebuffer,也能走DRM/KMS,可玩性比单片机高不少。真正要纠结的是:项目到底该用Qt、AWTK、GTK,还是LVGL?

我整理了一个选型对比,以实际嵌入式Linux项目视角来看:

我用过一个单核A7板子,256MB内存,跑Qt的QMainWindow空窗口倒是能开,但放稍微复杂点的页面,内存就把不住,操作响应也发飘。换LVGL之后,同样的板子做完整套HMI,内存占用从几十MB直接压到不到10MB,而且是即时刷新,手感更接近“直接改显存”。

LVGL在嵌入式Linux上的核心优势,我总结有三点:渲染路径短,不经过复杂窗口系统,直接朝buffer画,延迟低;组件从按钮、列表、图表到动画都有,不必每个控件都手写;代码可读性强,单个库文件集成熟,出问题容易跟踪。劣势也存在:复杂文本排版不如Qt好,对多语言排版、网页混合支持的积累较薄弱;遇到很复杂的业务界面,开发速度没有QML那样“声明式”舒服。但嵌入式产品界面通常不需要浏览器级排版,LVGL恰好卡在“够用”和“不浪费”中间。

把口号放一边,实际项目里“移植LVGL”从来不止是编译通过。我在规划阶段会把需求拆成四层:

第一层是跑起来。源码能编译,屏能亮,触摸能点,画个按钮有反馈。第二层是接得顺。显示用framebuffer还是DRM,输入设备通过libinput还是直接读evdev,时基用系统单调时钟。第三层是达到产品手感。正常操作不闪烁、不撕裂、不掉帧,动画流畅,CPU占用别飙到100%导致主业务被拖垮。第四层是稳定可交付。内存不能越用越多,异常后能重启或降级,日志可查,升级友好。

实践中很多项目挂在第三层。LVGL的默认配置偏保守,把全部组件都打开、缓冲区设得很小、解码每次都走CPU,这种配置在演示时没问题,产品化后就暴露短板。所以我会把优化工作放到和移植同等重要的位置。后面章节写到的内容,基本就是围绕这四层需求展开。

2. 环境准备与依赖梳理:少走弯路的工程配置

嵌入式Linux上的LVGL移植,第一件事不是写代码,而是把交叉编译环境理清楚。我自己通常用一个sysroot把根文件系统里的头文件和库都固定下来,避免“编译过了、上板缺so”的经典翻车。

工具链选择上,建议直接用板卡厂商SDK里配套的交叉编译器。像NXP的i.MX系列、瑞芯微的RK系列、全志的XR系列,厂商给的buildroot SDK里都带好了工具链和sysroot。如果用通用工具链,比如arm-linux-gnueabihf-gcc,需要格外确认glibc版本和内核头文件版本,不然依赖库如libinput、libpng会踩坑。

这样把LVGL源码、驱动适配、应用代码分开,后面升级LVGL版本只动third_party,不会影响业务代码。CMake里把lvgl编译成静态库,再链接到主程序,比直接编译一堆源文件要好管理。

LVGL 8/9对硬件本身依赖很低,但若开启了PNG、JPEG、GIF图片解码,以及FreeType字体渲染,就会引入一堆第三方库。很多移植教程默认把这些功能全打开,结果一交叉编译就报“找不到png.h”“找不到ft2build.h”。

我的建议是“按需裁剪”:纯图标、按钮、界面元素,完全不用PNG解码,用LVGL内置的C数组图片格式就够了,甚至可以关掉所有外部解码器;需要加载本地图片资源,且资源为JPG,考虑开libjpeg-turbo,能省内存和CPU;需要中文或特殊字体,体积小的场景用LVGL内置字体工具把ttf转成C数组,几百KB,零依赖;字体不可控、需要运行时加载的场景,再引入FreeType。

自己做产品,如果屏幕分辨率不高(480x272、800x480),我强烈建议所有图片做成C数组。这样整套系统少编译三个动态库,稳定性和启动速度都会好很多。若确定要编码PNG/JPEG,再考虑交叉编译libpng、libjpeg-turbo、zlib。这里有个经验:不要用PC上编出来的库直接拷到板子上,务必用目标机sysroot下的头文件重编一次,否则很可能因为ABI不匹配运行期崩溃。

3. 源码获取、配置与编译:把LVGL工程跑通

LVGL的代码仓库策略经常变。LVGL 8时代是lvgl、lv_drivers、lv_examples分开仓库;LVGL 9之后主仓库里带了更多驱动和demo,lv_drivers被整合。因此第一步看版本,别拿着8的教程硬套9。

我实际项目目前用的是LVGL 9.1版本,推荐的做法不是直接下载master,而是切到releases标签。master分支迭代很快,API可能一周一变。拉代码可以用:

lv_port_linux里有现成的linux平台工程,包含显示和输入适配,适合做起点。下载后把lvgl和lv_port_linux的目录结构理顺,再自己加应用。

这里要说清楚,LVGL 9的代码结构比8清爽,但配置文件生成逻辑也变了。LVGL 9里lv_conf.h如果不存在,会用lv_conf_internal.h提供默认配置。直接把示例配置拷到工程目录,然后打开LV_CONF_SKIP强制使用指定配置,可以避免很多“改了配置不生效”的问题。

LVGL配置集中在lv_conf.h,它决定功能开关、资源上限、编译特性。我挑重点参数讲,不罗列所有宏。

颜色深度LV_COLOR_DEPTH:屏是RGB565就设16,是RGB888就设32。这个值直接决定了内部颜色类型大小,不要混着设,不然flush时颜色转换会白耗CPU。内存设置LV_MEM_SIZE和LV_MEM_CUSTOM:LVGL内部有自己的内存管理器,默认用标准C的malloc/free封装,嵌入式Linux上完全可以默认。需要精确控制时可把LV_MEM_CUSTOM设为1,替换成自研池或litemalloc。

功能裁剪宏:LV_USE_ANIMATION、LV_USE_FLEX、LV_USE_GRID等,按需打开。不开的不要开着,每个功能都会带一点内存和ROM开销。字体方面,LV_FONT_DEFAULT一般选lv_font_montserrat_16;中文项目需要加载自定义字体,否则默认字体里没有中文字形。日志与系统监控:LV_USE_LOG建议开发期打开,发布时关掉或降级;LV_USE_SYSMON可用于性能调试。关于LV_CONF_SKIP,这是我上板必开的宏,避免liblvgl内部conf和外部conf冲突。

拿到lv_port_linux后,不要急着改业务,先把自带的demo跑通。比如编译simulator版,通常在PC上先跑SDL版本,验证源码可用;然后切换到linux framebuffer版,直接上板。

这段代码看着简单,实际里面有两个关键点:lv_display_set_buffers设定的缓冲区大小,LVGL会按这个缓冲区分割渲染脏矩形。缓冲设太小时,每次重绘的区域被切得很碎,刷新次数暴涨,触摸跟手度和CPU占用都会出问题;lv_timer_handler的调用周期是LVGL任务调度的“心跳”,建议5ms一次,别在主线程里跑sleep太久,否则动画卡顿。

编译时注意加微架构优化。量级小的板子,交叉编译时建议加-march=armv7-a -mfpu=neon等参数,能让颜色拷贝和blitting快很多。CMake里用Release模式,关掉调试符号。

4. 显示与输入移植:打通硬件层的最后一步

显示适配是移植的核心,也是最容易花屏、黑屏的地方。嵌入式Linux里给LVGL喂显示内存有两个主流通路:直接操作/dev/fb0的framebuffer接口,或者走DRM/KMS。framebuffer实现简单,代码量少,适合快速验证;DRM/KMS支持平面、缩放、垂直同步,显示质量更好,但API复杂,代码里需要处理drmModeSetCrtc等一堆细节。

我建议第一条:先把framebuffer版本调通,确认LVGL渲染管线和工具链没问题,再决定是否需要DRM。framebuffer的关键代码是打开设备、mmap显存、ioctl获取分辨率、计算色深:

LVGL的flush回调就是把LVGL分配的buf内容拷贝到fb内存,或者更高效地,直接把fb指针交给LVGL借用。两种方式有区别:拷贝式,LVGL渲染到内部buf,flush时memcpy到fb,实现简单,但每次刷新多一次整块拷贝,CPU开销大;借用显存式,把/dev/fb0 mmap出来作为LVGL的draw buffer,LVGL直接渲染到目标显存,省掉拷贝,但应用崩溃容易留下残影,且要处理双缓冲时屏幕撕裂。

实际产品里如果屏只有一块framebuffer,建议用双内存缓冲并手动等待vsync。LVGL渲染到后buffer,vsync到达后再切换显示地址,能明显改善撕裂。代码上可以丢给DRM的page flip机制实现,更省事。性能调优章节我还会细聊。

嵌入式产品输入五花八门,官方demo里默认用libinput,它在Linux桌面和嵌入式环境都能工作,统一了触摸屏、鼠标、键盘事件。使用libinput时,要保证rootfs里包含/lib/udev规则和sysfs权限配置。若精简系统没有udev,lv_drivers里的evdev驱动可以绕过libinput,直接读evdev设备节点,更可控。

触摸屏接入最容易翻车的两个点是坐标变换和事件过滤。LVGL用的坐标系是左上角原点、y向下,和多数电阻触摸屏一致,但电容屏的坐标可能还需要根据屏幕翻转方向做旋转或镜像。对应evdev驱动里,有一个坐标转换函数,常用ratio乘除换算后,再调用lv_indev_set_point,确保点击位置准确。

按键输入则建议把按键映射成LVGL的按键事件或编码器事件。比如实体旋钮编码器,可以接到LVGL的encoder类型输入,实现上下方向和确认操作;方向键则可以映射为LV_KEY_UP/DOWN/ENTER。这在很多工控设备上比触摸可靠得多,因为戴手套的工业环境触摸很难用。

LVGL内部需要毫秒级时基。裸机工程常用SysTick,Linux上更严谨的是用clock_gettime(CLOCK_MONOTONIC)读取单调时钟。用gettimeofday是不行的,系统时间被手动改或NTP校时后,动画会出现跳变。

我在工程里用POSIX定时器维护一个线程专门喂时基:

如果项目里已经有应用线程,也可以直接在渲染循环里通过lv_timer_handler内部拿monotonic时钟,LVGL 9默认就有对应接口。重点是别自己维护一个counter变量来模拟毫秒,时间久了会漂移。

LVGL的渲染是“脏矩形”模式,只有发生变化的区域会被重绘。影响刷新效率的最大因素不是CPU频率,而是缓冲区大小和渲染模式设置。

LVGL 9里通过lv_display_set_buffers传入buf和buf2,再配合LV_DISPLAY_RENDER_MODE_PARTIAL/FULL,控制刷新策略。如果只提供一个buffer,那么LVGL只能在单缓冲下工作,每次刷新渲染一部分、flush一部分,速度快但容易撕裂。如果提供两个大小相同的buffer,LVGL会切换渲染目标,flush一块的同时渲染另一块,能明显减少撕裂,但每块buffer至少等于屏幕宽度×行高×颜色字节数。

举个例子:800x480的RGB565屏,一个全屏buffer是800×480×2=768KB。如果RAM吃紧,也至少要保证buffer能容纳几十行扫描线,比如800×100×2=160KB,刷新效率才有保障。我见过有人为了省内存把buffer设成800×16×2,结果每次界面刷新被切成30多块,操作延迟肉眼可见。

所以我总结的缓冲区选择顺序是:条件允许,用双全屏buffer加FULL刷新模式;内存中等,用双半屏或双1/4屏buffer加PARTIAL;内存吃紧,单缓冲局部刷新,但一定要保证行高足够,别低于屏幕高度的1/8。

CPU占用高,常见原因是LVGL把所有功能都编进去、颜色转换频繁、图像解码吃满CPU。先看编译配置:

关闭不需要的组件宏,裁掉LV_USE_PNG、LV_USE_JPEG、LV_USE_GIF、LV_USE_BARCODE等。每个组件都会占flash和运行时分支。使用-Ofast或-O2,如果芯片有NEON/SIMD,编译时加-march和-mfpu,LVGL底层拷贝函数会大幅提速。开LTO,把lvgl静态库和应用做链接时优化,能省不少代码体积。

颜色转换是隐形杀手。如果屏是RGB565,而LVGL配置的是16bit,内部buffer直接用RGB565,在flush到framebuffer时可以直接memcpy;但如果颜色深度不一致,例如LVGL用32bit,屏用16bit,每次flush都要逐像素转换,800x480全屏刷新一次要算几十万个像素点,CPU必然飙高。宁可让LVGL的颜色深度和屏保持一致,也不要为省显存搞不一致。

在嵌入式Linux上,如果直接向/dev/fb0写入数据,很容易出现屏幕上部已经更新、下部还是旧画面的撕裂效果。出现这个问题的原因是屏幕扫描更新和CPU写入之间没有同步。

解决撕裂有两个常用套路:在flush开始时等待VSYNC信号,DRM/KMS下可以通过drmWaitVBlank等待,framebuffer下可以用FBIO_WAITFORVSYNC;利用双缓冲和page flip,渲染完成后把显示地址切到新buffer,时机交给KMS的page flip事件,避免直接写当前正在扫描的buffer。

我在项目里最终选择DRM/KMS + 双buffer + page flip方案,刷新延迟和撕裂情况都改善明显。缺点是DRM初始化代码比framebuffer长不少,要处理connector、encoder、mode等概念。如果产品是固定分辨率,基本就是一套find mode转set crtc转add fb的逻辑,写一次后面复用。

口说无凭,我放一组自己在项目里记录过的数据,仅供参考。硬件是单核A7 @ 528MHz,800x480 RGB565屏,LVGL 9.1:

全屏填充4ms的差异,单次看不大,但动画每帧都执行,就会明显体现到体验上。优化不是玄学,本质上还是减少画布面积、减少颜色转换、减少数据搬运。

黑屏问题,我排查思路三步走:确认/dev/fb0存在且open成功。很多精简rootfs没有/dev/fb0,需要确认内核打开fbdev驱动。确认LVGL的flush回调被调用。可以在flush里打印一个计数,若计数不涨,说明显示对象与渲染流程没接通,多半是lv_display_create和set_flush_cb没配对。若flush有调用但屏不亮,检查mmap地址是否被缓存写穿,确认buffer与屏物理地址是否有偏移。

花屏则通常是颜色深度不匹配、行距stride没对齐、或者mmap的buffer大小与屏幕实际尺寸不一致。特别注意,有些驱动里xres和yres之外还有xres_virtual/yres_virtual,实际fb内存大小要用virtual值,不然mmap小了就会花屏。

点击无反应先看事件源是否有数据。命令行cat /dev/input/eventX,手指触摸有数据则驱动通路正常。如果event设备没数据,检查设备树、触摸芯片驱动、I2C通信。

事件有数据但LVGL无反应,重点排查lv_indev_set_read_cb的事件上报方式。LVGL要求read_cb里调用lv_indev_set_point设置坐标,并设置state为LV_INDEV_STATE_PRESSED/RELEASED。有些移植代码忘了上报释放状态,表现为只能拖动、不能点击。

坐标反向常见于屏幕安装方向不同。在read_cb内根据屏幕安装角度做变换,别去改LVGL内部。坐标漂移常见于电容屏没做校准,建议在系统启动时运行libinput校准,或直接用libinput自带的校准工具。

CPU 100%先查是不是画了大的透明区域。大面积透明叠加会造成LVGL把下层也重绘,推荐界面用不透明背景,或把label和img的bg_opa设成LV_OPA_COVER。动画掉帧优先查lv_timer_handler调用频率和渲染耗时。可以在lv_timer_handler前后打点,若渲染耗时超过16ms但实际卡顿,多半是vsync没等好,进程在等I/O。

闪烁常见与单缓冲加清屏策略有关。LVGL默认不会整个清屏,但如果某个控件背景透明或颜色混合有问题,会出现刷过的残影。排查时把所有控件背景设为不透明,再看是否消失。还有一种情况是framebuffer驱动与LCD时序不匹配,需要调驱动里的像素时钟和blank参数。

LVGL内存泄漏多出在图片资源和动态创建的控件没释放。图片资源用lv_image_set_src加载后,系统默认不缓存,每次显示重新解码,若不主动关闭,缓存会一直涨。可以用LV_SYSMON或lv_mem_monitor定期打印堆内存,排查哪个操作导致内存曲线持续上升。

崩溃大概率出在中断或异步线程直接调用LVGL API。LVGL的API不是完全线程安全,建议所有UI操作集中在一个线程,通过队列与业务线程通信。我是用一个全局消息队列,业务线程把“需要更新温度值”这类消息推入队列,UI线程在下一次lv_timer_handler时消费并更新控件,这样彻底避开加锁地狱。

启动慢一般不是LVGL本身的锅,而是rootfs里的动态库加载慢、或者字体文件过大解析慢。精简系统可以把字体文件转成C数组,随应用一起加载,启动时间能从几百ms降到几十ms。

7. 项目扩展:从能跑到产品化的关键一步

很多嵌入式Linux项目把LVGL和其他业务线程混在一起,最后代码变成一团乱麻。我建议所有UI操作都只在UI线程(通常是主线程)执行,其他线程通过自定义消息结构体向UI线程投递事件。这样避免了锁竞争,也让逻辑边界清晰。

UI线程在每次lv_timer_handler之前,消费队列里的消息并调用lv_label_set_text_fmt更新文本。这个模式对单核A7尤其友好,避免多线程切来切去。

这次热点里有人总把FreeRTOS移植LVGL和嵌入式Linux移植LVGL混在一起问,顺带说下我的对比体会。两者最大的不同不是LVGL本身,而是资源与生态环境。

FreeRTOS下通常使用自定义内存池、SPI/并口屏驱动,LVGL没有文件系统,图片要么C数组要么用只读flash映射。能跑LVGL 9,但内存紧张,渲染缓冲区普遍只能设到几KB。嵌入式Linux则有文件系统、有framebuffer/DRM、有libinput,外部库可用,资源相对宽裕,优势是能加载PNG/JPG、用FreeType、跑MQTT等;代价是系统复杂度和启动时间上升。

如果你的核心诉求是低端MCU,FreeRTOS加LVGL是经典组合;如果你的产品跑着Linux且有网络协议栈,那LVGL on Linux更合适,不用自己写底层网络和文件系统。两者的应用层API是一样的,意味着业务UI代码几乎可以迁移,这也是LVGL的实践价值之一。

最后说下LVGL 9的变化,因为很多人一上来就接触9.x版本。LVGL 9把显示对象、输入设备、渲染器做了重构,API和LVGL 8差异不小,特别是lv_disp_drv_t被lv_display_t取代,lv_disp_buf_t的概念也变了。迁移时需要把老代码里的lv_disp_drv_register改成lv_display_create,把lv_disp_buf_init改成lv_display_set_buffers,输入设备的lv_indev_drv_register同样改成lv_indev_create。

LVGL 9对PC模拟器支持更友好,官方lv_port_pc_eclipse项目可以直接在Windows/Linux上跑SDL窗口。我建议新项目直接上LVGL 9,旧项目能不动就不要大改,除非有明确收益。升级前先用官方demo在模拟器里跑完所有功能,别一边改代码一边升级。

我个人实际做下来的体会是,LVGL在嵌入式Linux上“跑起来容易,跑得漂亮难”。只要把lv_conf.h的裁剪、显示buffer大小、颜色深度一致性和刷新时序这四个点握住,性能基本能到可交付的水平。如果你正在折腾移植,先别急着优化业务UI,把底层这四个问题吃透,界面自然就顺了。每次调试都多打印、多打点、多看内存,少靠猜,这是我在这个项目里最真实的收获。

LVGL Porting and Performance Optimization on Embedded Linux

本文来源:https://www.hqwc.cn/a/1891039.html
若有版权问题,请来信告知:13951431913#139.com 或在右方提交评论。

I've been doing embedded Linux development for a few years, and I've switched through several UI library solutions. I started with Qt — it's genuinely powerful, but it demands a lot of hardware, and on a slightly weaker machine it clearly struggles. Later I came across LVGL; my first impression was “a small graphics library that runs on an MCU,” but after trying it carefully I found it works just as well on embedded Linux. In this article I've organized a complete LVGL porting and optimization project, covering solution selection, environment setup, getting display and input working, performance tuning, and common pitfalls, hoping to help friends working on embedded HMI, smart panels, automotive instrument clusters, or industrial control displays.

1. Project Positioning and Solution Selection: Why Choose LVGL on Embedded Linux

Let's talk about solution selection first. When many people hear LVGL, their first reaction is “it's for microcontrollers,” which isn't actually accurate. LVGL is now positioned as an embedded graphics library, not limited to either MCU or MPU. Running LVGL on embedded Linux, you can directly operate the framebuffer or go through DRM/KMS — considerably more flexible than on a microcontroller. What really needs weighing is: should the project use Qt, AWTK, GTK, or LVGL?

I've put together a selection comparison, viewed from the perspective of a real embedded Linux project:

I once used a single-core A7 board with 256MB of RAM; running an empty Qt QMainWindow would open fine, but with a slightly more complex page, memory couldn't hold and operation responsiveness became erratic. After switching to LVGL, the same board running a full HMI suite dropped memory usage from tens of MB straight down to under 10MB, with instant refresh — the feel is closer to “directly modifying video memory.”

I sum up LVGL's core advantages on embedded Linux in three points: the rendering path is short — it doesn't go through a complex windowing system and draws directly to the buffer, so latency is low; components range from buttons, lists, charts to animations, so you don't have to hand-write every control; the code is highly readable and the single-library-file integration is mature, making problems easy to trace. Disadvantages exist too: complex text layout isn't as good as Qt, and it has relatively weak accumulation in multilingual layout and web-hybrid support; for very complex business UIs, development speed isn't as comfortable as QML's “declarative” approach. But embedded product UIs usually don't need browser-level layout, and LVGL sits exactly between “good enough” and “not wasteful.”

Setting slogans aside, in real projects “porting LVGL” has never been just about getting it to compile. At the planning stage I break the requirements down into four levels:

The first level is getting it running: the source compiles, the screen lights up, touch responds, and drawing a button gives feedback. The second level is getting it connected smoothly: whether display uses framebuffer or DRM, whether input devices go through libinput or read evdev directly, and using the system monotonic clock for the time base. The third level is achieving product-grade feel: no flicker, no tearing, no dropped frames during normal operation, smooth animations, and CPU usage that doesn't spike to 100% and drag down the main business logic. The fourth level is being stable and deliverable: memory doesn't keep growing, the system can restart or degrade gracefully after exceptions, logs are inspectable, and upgrades are friendly.

In practice many projects get stuck at the third level. LVGL's default configuration is fairly conservative — turning on all components, setting the buffer very small, and running decoding on the CPU every time. Such a configuration is fine for a demo, but its weaknesses show once you productize. So I place optimization work on par with porting. The content in the following chapters basically unfolds around these four levels of requirements.

2. Environment Preparation and Dependency Sorting: Engineering Configuration That Avoids Detours

For LVGL porting on embedded Linux, the first thing isn't writing code but getting the cross-compilation environment straight. I usually use a sysroot to pin down all the headers and libraries from the root filesystem, avoiding the classic crash of “it compiled, but the board is missing the .so.”

For toolchain selection, it's recommended to use the cross-compiler that comes with the board vendor's SDK. For example, NXP's i.MX series, Rockchip's RK series, and Allwinner's XR series — the buildroot SDKs provided by these vendors all come with a ready toolchain and sysroot. If you use a general-purpose toolchain such as arm-linux-gnueabihf-gcc, you need to pay special attention to confirming the glibc version and kernel header version, otherwise dependency libraries like libinput and libpng will cause problems.

By separating the LVGL source, driver adaptation, and application code this way, later LVGL version upgrades only touch third_party and won't affect business code. In CMake, compiling lvgl into a static library and then linking it into the main program is easier to manage than directly compiling a bunch of source files.

LVGL 8/9 has very low dependence on hardware itself, but if you enable PNG, JPEG, and GIF image decoding, as well as FreeType font rendering, you'll pull in a bunch of third-party libraries. Many porting tutorials turn all these features on by default, and the moment you cross-compile you get errors like “png.h not found” and “ft2build.h not found.”

My recommendation is “trim on demand”: for pure icons, buttons, and UI elements, you don't need PNG decoding at all — LVGL's built-in C-array image format is enough, and you can even turn off all external decoders; if you need to load local image resources and they're JPG, consider enabling libjpeg-turbo, which saves memory and CPU; if you need Chinese or special fonts, for small-size scenarios use LVGL's built-in font tool to convert ttf to a C array — a few hundred KB with zero dependencies; only in scenarios where fonts are uncontrollable and need to be loaded at runtime should you bring in FreeType.

When making your own product, if the screen resolution isn't high (480x272, 800x480), I strongly recommend making all images into C arrays. This way the whole system compiles three fewer dynamic libraries, and stability and startup speed improve a lot. If you're sure you need to encode PNG/JPEG, then consider cross-compiling libpng, libjpeg-turbo, and zlib. Here's a rule of thumb: don't copy libraries compiled on the PC straight to the board — be sure to recompile once using the headers under the target machine's sysroot, otherwise you'll very likely get runtime crashes due to ABI mismatch.

3. Source Acquisition, Configuration, and Compilation: Getting the LVGL Project Running

LVGL's repository strategy changes often. In the LVGL 8 era, lvgl, lv_drivers, and lv_examples were separate repositories; after LVGL 9, the main repository includes more drivers and demos, and lv_drivers was integrated. So the first step is to check the version — don't force an 8 tutorial onto 9.

My current real project uses LVGL version 9.1, and the recommended approach isn't to download master directly but to switch to a releases tag. The master branch iterates very fast, and the API may change from week to week. To pull the code you can use:

lv_port_linux contains a ready-made Linux platform project, including display and input adaptation, making it a good starting point. After downloading, sort out the directory structure of lvgl and lv_port_linux, then add your own application.

To be clear here, LVGL 9's code structure is cleaner than 8's, but the configuration file generation logic has also changed. In LVGL 9, if lv_conf.h doesn't exist, lv_conf_internal.h is used to provide default configuration. Copying the sample configuration directly into the project directory and then enabling LV_CONF_SKIP to force the use of the specified configuration can avoid many “changed the config but it has no effect” problems.

LVGL configuration is centralized in lv_conf.h, which determines feature switches, resource limits, and compilation characteristics. I'll discuss the key parameters and not list every macro.

Color depth LV_COLOR_DEPTH: set it to 16 if the screen is RGB565, and 32 if it's RGB888. This value directly determines the size of the internal color type — don't set it inconsistently, or color conversion during flush will waste CPU. Memory settings LV_MEM_SIZE and LV_MEM_CUSTOM: LVGL has its own internal memory manager, which by default wraps the standard C malloc/free, and on embedded Linux the defaults are perfectly fine. When you need precise control, you can set LV_MEM_CUSTOM to 1 and replace it with a custom pool or litemalloc.

Feature-trimming macros: LV_USE_ANIMATION, LV_USE_FLEX, LV_USE_GRID, etc. — enable them on demand. Don't leave features on that you don't use; every feature carries a bit of memory and ROM overhead. For fonts, LV_FONT_DEFAULT is usually set to lv_font_montserrat_16; Chinese projects need to load a custom font, otherwise the default font has no Chinese glyphs. Logging and system monitoring: LV_USE_LOG is recommended on during development and turned off or downgraded at release; LV_USE_SYSMON can be used for performance debugging. As for LV_CONF_SKIP, this is a macro I always enable when bringing up a board, to avoid conflicts between liblvgl's internal conf and the external conf.

Once you have lv_port_linux, don't rush to change business logic — first get the bundled demo running. For example, build the simulator version; typically you first run the SDL version on the PC to verify the source works, then switch to the linux framebuffer version and go straight to the board.

This code looks simple, but there are two key points in it: the buffer size set by lv_display_set_buffers — LVGL splits the rendering dirty rectangles according to this buffer. When the buffer is set too small, each redraw region gets chopped into tiny pieces, the number of refreshes skyrockets, and both touch responsiveness and CPU usage suffer; the call period of lv_timer_handler is the “heartbeat” of LVGL task scheduling — 5ms is recommended, and don't run long sleeps in the main thread, or animations will stutter.

Pay attention to adding microarchitecture optimization when compiling. For smaller boards, it's recommended to add flags like -march=armv7-a -mfpu=neon during cross-compilation, which can greatly speed up color copying and blitting. Use Release mode in CMake and turn off debug symbols.

4. Display and Input Porting: The Final Step to Connecting the Hardware Layer

Display adaptation is the core of porting, and also the most likely place to get screen corruption or a black screen. In embedded Linux there are two mainstream paths for feeding display memory to LVGL: directly operating the framebuffer interface at /dev/fb0, or going through DRM/KMS. framebuffer is simple to implement with little code, suitable for quick verification; DRM/KMS supports planes, scaling, and vertical sync, giving better display quality, but its API is complex and the code has to handle a host of details like drmModeSetCrtc.

My advice is the first path: get the framebuffer version working first, confirm the LVGL rendering pipeline and toolchain are fine, then decide whether DRM is needed. The key framebuffer code is opening the device, mmap-ing the video memory, using ioctl to get the resolution, and calculating the color depth:

LVGL's flush callback copies the contents of the buffer allocated by LVGL into fb memory, or, more efficiently, directly hands the fb pointer to LVGL to borrow. The two approaches differ: with the copy approach, LVGL renders into an internal buf and memcpy-s it to fb during flush — simple to implement, but each refresh adds one full-block copy with high CPU cost; with the borrowed-video-memory approach, you mmap /dev/fb0 as LVGL's draw buffer and LVGL renders directly to the target video memory, eliminating the copy, but an application crash can easily leave ghost images, and you have to handle screen tearing with double buffering.

In a real product, if the screen has only one framebuffer, it's recommended to use dual memory buffers and manually wait for vsync. LVGL renders to the back buffer, and the display address is switched after vsync arrives, which noticeably improves tearing. In code you can hand this off to DRM's page flip mechanism, which is less work. I'll discuss this in more detail in the performance tuning chapter.

Embedded product inputs come in all varieties; the official demo uses libinput by default, which works in both Linux desktop and embedded environments and unifies touchscreen, mouse, and keyboard events. When using libinput, make sure the rootfs includes /lib/udev rules and sysfs permission configuration. If a stripped-down system has no udev, the evdev driver in lv_drivers can bypass libinput and read evdev device nodes directly, which is more controllable.

The two points most likely to trip you up when connecting a touchscreen are coordinate transformation and event filtering. The coordinate system LVGL uses has its origin at the top-left with y pointing down, consistent with most resistive touchscreens, but a capacitive screen's coordinates may also need rotation or mirroring depending on the screen's flip orientation. In the corresponding evdev driver there's a coordinate-conversion function; commonly you do ratio-based multiply/divide conversion and then call lv_indev_set_point to ensure accurate tap positions.

For key input, it's recommended to map keys to LVGL key events or encoder events. For example, a physical rotary encoder can be connected to LVGL's encoder-type input to implement up/down navigation and confirm operations; arrow keys can be mapped to LV_KEY_UP/DOWN/ENTER. This is far more reliable than touch on many industrial control devices, because touch is hard to use in industrial environments where workers wear gloves.

LVGL needs a millisecond-level time base internally. Bare-metal projects commonly use SysTick; on Linux the more rigorous approach is to read the monotonic clock with clock_gettime(CLOCK_MONOTONIC). Using gettimeofday won't work — if the system time is changed manually or corrected by NTP, animations will jump.

In my project I use a POSIX timer to maintain a thread dedicated to feeding the time base:

If the project already has application threads, you can also get the monotonic clock internally through lv_timer_handler directly in the render loop — LVGL 9 has a corresponding interface by default. The key point is not to maintain your own counter variable to simulate milliseconds; over time it will drift.

LVGL's rendering uses a “dirty rectangle” mode, where only regions that have changed are redrawn. The biggest factor affecting refresh efficiency isn't CPU frequency, but buffer size and render mode settings.

In LVGL 9 you pass buf and buf2 through lv_display_set_buffers, combined with LV_DISPLAY_RENDER_MODE_PARTIAL/FULL, to control the refresh strategy. If you provide only one buffer, LVGL can only work in single-buffer mode, rendering a part and flushing a part on each refresh — fast but prone to tearing. If you provide two buffers of equal size, LVGL switches rendering targets, flushing one while rendering the other, which noticeably reduces tearing, but each buffer must be at least screen width × row height × bytes per color.

For example: on an 800x480 RGB565 screen, one full-screen buffer is 800×480×2=768KB. If RAM is tight, you should at least ensure the buffer can hold several dozen scanlines — say 800×100×2=160KB — to guarantee refresh efficiency. I've seen people set the buffer to 800×16×2 to save memory, and as a result each UI refresh got chopped into over 30 pieces, with operation latency visible to the naked eye.

So the buffer selection order I've summarized is: when conditions allow, use dual full-screen buffers with FULL refresh mode; with medium memory, use dual half-screen or dual quarter-screen buffers with PARTIAL; when memory is tight, single-buffer partial refresh, but be sure to keep the row height sufficient — no less than 1/8 of the screen height.

High CPU usage commonly results from LVGL compiling in all features, frequent color conversion, and image decoding maxing out the CPU. First look at the build configuration:

Turn off unneeded component macros and trim LV_USE_PNG, LV_USE_JPEG, LV_USE_GIF, LV_USE_BARCODE, etc. Every component occupies flash and adds runtime branches. Use -Ofast or -O2; if the chip has NEON/SIMD, add -march and -mfpu at compile time, and LVGL's low-level copy functions will speed up dramatically. Enable LTO to do link-time optimization of the lvgl static library and the application, saving a fair amount of code size.

Color conversion is a hidden killer. If the screen is RGB565 and LVGL is configured for 16bit, the internal buffer uses RGB565 directly and can be memcpy-ed straight to the framebuffer during flush; but if the color depths don't match — for example LVGL uses 32bit and the screen uses 16bit — every flush must convert pixel by pixel, and a single full-screen 800x480 refresh means calculating hundreds of thousands of pixels, so CPU usage inevitably spikes. It's better to keep LVGL's color depth consistent with the screen than to make them inconsistent to save video memory.

On embedded Linux, if you write data directly to /dev/fb0, it's easy to get a tearing effect where the upper part of the screen is updated while the lower part still shows the old image. The cause is a lack of synchronization between the screen's scan update and the CPU's writes.

There are two common approaches to solving tearing: wait for the VSYNC signal at the start of flush — under DRM/KMS you can wait via drmWaitVBlank, and under framebuffer you can use FBIO_WAITFORVSYNC; or use double buffering and page flip, switching the display address to the new buffer after rendering is complete and leaving the timing to KMS's page flip event, avoiding writing directly to the buffer currently being scanned.

In my project I ultimately chose the DRM/KMS + dual buffer + page flip scheme, and both refresh latency and tearing improved noticeably. The downside is that DRM initialization code is considerably longer than framebuffer's, requiring you to handle concepts like connector, encoder, and mode. If the product has a fixed resolution, it's basically a sequence of find mode → set crtc → add fb logic, written once and reused afterward.

Rather than just talk, here's a set of data I recorded in my project, for reference only. Hardware: single-core A7 @ 528MHz, 800x480 RGB565 screen, LVGL 9.1:

A 4ms difference in full-screen fill doesn't look like much for a single run, but animations execute it every frame, so it shows up clearly in the experience. Optimization isn't mysticism — essentially it's about reducing canvas area, reducing color conversion, and reducing data movement.

For a black screen, my troubleshooting follows three steps: confirm /dev/fb0 exists and open succeeds — many stripped-down rootfs images lack /dev/fb0, so you need to confirm the kernel has the fbdev driver enabled. Confirm LVGL's flush callback is being called — you can print a counter inside flush; if the counter doesn't increase, the display object isn't connected to the rendering flow, most likely lv_display_create and set_flush_cb aren't paired. If flush is called but the screen stays dark, check whether the mmap address is being write-through cached, and confirm whether there's an offset between the buffer and the screen's physical address.

Screen corruption is usually caused by mismatched color depth, misaligned stride, or an mmap buffer size that doesn't match the screen's actual dimensions. Pay special attention: in some drivers, besides xres and yres there are also xres_virtual/yres_virtual — the actual fb memory size must use the virtual values, otherwise an mmap that's too small will cause screen corruption.

If taps don't respond, first check whether the event source has data. Run cat /dev/input/eventX on the command line; if there's data when you touch with a finger, the driver path is fine. If the event device has no data, check the device tree, the touch chip driver, and I2C communication.

If the event has data but LVGL doesn't respond, focus on the event-reporting method of lv_indev_set_read_cb. LVGL requires read_cb to call lv_indev_set_point to set coordinates and to set state to LV_INDEV_STATE_PRESSED/RELEASED. Some porting code forgets to report the release state, which shows up as being able to drag but not to click.

Reversed coordinates are common when the screen is mounted in a different orientation. Do the transformation inside read_cb according to the screen's mounting angle — don't modify LVGL internals. Coordinate drift is common when a capacitive screen hasn't been calibrated; it's recommended to run libinput calibration at system startup, or use libinput's own calibration tool.

For 100% CPU, first check whether you're drawing large transparent areas. Large-area transparency overlays cause LVGL to redraw the layers underneath too; it's recommended to use opaque backgrounds for the UI, or set the bg_opa of labels and images to LV_OPA_COVER. For dropped animation frames, first check the lv_timer_handler call frequency and rendering time. You can add timestamps before and after lv_timer_handler; if rendering takes over 16ms but there's actual stutter, most likely vsync isn't being waited on properly and the process is waiting on I/O.

Flicker is often related to single buffering combined with a screen-clearing strategy. LVGL doesn't clear the whole screen by default, but if a control has a transparent background or there's a color-blending issue, ghost images from previous refreshes appear. When troubleshooting, set all control backgrounds to opaque and see if the problem disappears. Another case is a mismatch between the framebuffer driver and LCD timing, requiring adjustment of the pixel clock and blank parameters in the driver.

LVGL memory leaks mostly come from image resources and dynamically created controls not being freed. After an image resource is loaded with lv_image_set_src, the system doesn't cache by default and re-decodes it on every display; if you don't actively close it, the cache keeps growing. You can use LV_SYSMON or lv_mem_monitor to periodically print heap memory and investigate which operation causes the memory curve to keep rising.

Crashes most likely come from calling LVGL APIs directly in interrupts or asynchronous threads. LVGL's APIs aren't fully thread-safe; it's recommended to concentrate all UI operations in one thread and communicate with business threads through a queue. I use a global message queue: the business thread pushes messages like “need to update temperature value” into the queue, and the UI thread consumes them on the next lv_timer_handler and updates the controls, completely avoiding lock hell.

Slow startup is generally not LVGL's own fault, but rather slow loading of dynamic libraries in the rootfs or slow parsing of oversized font files. A stripped-down system can convert font files into C arrays loaded together with the application, reducing startup time from several hundred ms to a few tens of ms.

7. Project Extension: The Key Step from Running to Productization

Many embedded Linux projects mix LVGL together with other business threads, and the code eventually becomes a tangled mess. I recommend that all UI operations run only in the UI thread (usually the main thread), with other threads posting events to the UI thread via custom message structs. This avoids lock contention and makes logical boundaries clear.

Before each lv_timer_handler, the UI thread consumes messages in the queue and calls lv_label_set_text_fmt to update text. This pattern is especially friendly to a single-core A7, avoiding constant context switching between threads.

In this trending topic, people keep mixing up questions about porting LVGL to FreeRTOS and to embedded Linux, so I'll briefly share my comparative experience. The biggest difference between the two isn't LVGL itself, but the resources and ecosystem.

Under FreeRTOS you typically use a custom memory pool and SPI/parallel-port screen drivers; LVGL has no file system, so images are either C arrays or mapped from read-only flash. It can run LVGL 9, but memory is tight and render buffers are generally limited to a few KB. Embedded Linux, on the other hand, has a file system, framebuffer/DRM, and libinput, with external libraries available and relatively abundant resources; its advantages are the ability to load PNG/JPG, use FreeType, run MQTT, etc.; the price is increased system complexity and startup time.

If your core need is a low-end MCU, FreeRTOS plus LVGL is the classic combination; if your product runs Linux and has a network protocol stack, then LVGL on Linux is more suitable, with no need to write low-level networking and file systems yourself. The application-layer APIs of the two are the same, meaning business UI code is almost fully portable — one of LVGL's practical values.

Finally, let me talk about the changes in LVGL 9, since many people start right out with the 9.x version. LVGL 9 refactored the display objects, input devices, and renderer, and the API differs quite a bit from LVGL 8 — in particular lv_disp_drv_t is replaced by lv_display_t, and the concept of lv_disp_buf_t has also changed. When migrating, you need to change lv_disp_drv_register in old code to lv_display_create, lv_disp_buf_init to lv_display_set_buffers, and for input devices, lv_indev_drv_register likewise to lv_indev_create.

LVGL 9 offers friendlier support for PC simulators; the official lv_port_pc_eclipse project can run an SDL window directly on Windows/Linux. I recommend going straight to LVGL 9 for new projects, and for old projects, don't make big changes unless there's a clear benefit — if they can be left alone, leave them. Before upgrading, run all features through the official demo in the simulator; don't change code and upgrade at the same time.

My personal takeaway from actually doing this is that LVGL on embedded Linux is “easy to get running, hard to run beautifully.” As long as you nail these four points — trimming lv_conf.h, display buffer size, color depth consistency, and refresh timing — performance will basically reach a deliverable level. If you're wrestling with a port, don't rush to optimize the business UI; first thoroughly understand these four underlying issues and the interface will naturally become smooth. Print more, add more timestamps, watch memory more, and rely less on guessing during every debugging session — that's my most genuine takeaway from this project.

暂无评论,快来发表第一条评论吧!No comments yet. Be the first!

📮 需求咨询📮 Inquiry