STM32 移植 OpenHarmony LiteOS-M 内核实战:从环境搭建到驱动开发Porting the OpenHarmony LiteOS-M Kernel to STM32: From Environment Setup to Driver Development


AI free token/AI免费积分

STM32 移植 OpenHarmony LiteOS-M 内核实战:从环境搭建到驱动开发

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

1. 项目缘起:为什么要在STM32上折腾鸿蒙?

最近在整理手头的几个STM32项目,发现一个挺有意思的现象:很多项目还在用着FreeRTOS或者干脆裸奔。不是说这些方案不好,它们稳定、成熟,是经过市场验证的。但每次看到那些为了线程同步、内存管理、驱动框架而写的胶水代码,总觉得有点“重复造轮子”的疲惫感。正好,鸿蒙(这里特指OpenHarmony的轻量系统,比如LiteOS-M内核)这两年声音不小,官方宣传其面向IoT设备,主打轻量、低功耗、高实时性。这听起来不就是为STM32这类资源受限的MCU量身定做的吗?

于是,一个念头冒了出来:能不能把手头的一块STM32F103(就是那个经典的“蓝色药丸”开发板)跑上鸿蒙系统?这不仅仅是为了“炫技”或者追热点。更深层的需求是,想亲身体验一下鸿蒙为嵌入式开发带来的那套“统一”的框架——从内核调度、设备驱动到分布式能力,看看它是否真的能简化从单片机到复杂应用的开发流程,以及它所谓的“一次开发,多端部署”在资源吃紧的MCU上究竟能实现到什么程度。毕竟,纸上得来终觉浅,代码跑起来才是硬道理。

2. 环境搭建:从零开始的“踩坑”预备役

决定动手之后,第一关就是搭建编译环境。鸿蒙的官方文档推荐使用Ubuntu作为开发主机,这对于习惯了Windows下Keil、IAR的STM32开发者来说,算是个不大不小的门槛。我选择在Windows 11上通过WSL2安装Ubuntu 20.04 LTS,这是一个折中的方案,既能用上Linux环境,又不脱离熟悉的Windows生态。

注意:OpenHarmony的编译工具链(如hb、python环境)对Linux发行版和版本有特定要求,强烈建议严格按照官方推荐的Ubuntu版本操作,避免在奇怪的环境问题上耗费时间。

安装完Ubuntu后,跟着OpenHarmony开源站的“轻量系统快速入门”指南走。核心步骤包括:获取源码、安装必要的工具(如python3.8+、pip、hb等)、配置编译工具链(这里用的是arm-none-eabi-gcc)。整个过程像在走钢丝,任何一个环节的版本不匹配都可能导致后续编译失败。我遇到的一个典型坑是 hb (OpenHarmony的构建工具)的安装。通过 pip 安装后,直接运行 hb -h 可能会报错,提示找不到模块。这是因为 hb 安装到了用户目录,但环境变量可能没正确配置。解决办法是找到 hb 的实际安装路径(通常在 ~/.local/bin/ ),并将其添加到PATH环境变量中,或者更彻底一点,用 sudo pip install 全局安装(但要注意python环境隔离)。

另一个关键是源码的获取。鸿蒙的代码仓库托管在Gitee,使用repo工具管理。在拉取代码时,需要指定 -b 分支和 --no-repo-verify 参数(有时不验证能加快速度,但安全性自己权衡)。对于STM32F103,我们关注的是 OpenHarmony-3.2-Release 或更新版本中,支持轻量系统的部分。代码量不小,首次拉取需要耐心。

工具链配置是另一个重点。OpenHarmony编译STM32需要ARM官方的GCC工具链(gnu-arm-embedded)。你需要从ARM官网或国内镜像下载,解压后,在编译配置文件(如 //build/lite/config/component/board/arm.gni 或项目级的 config.json )中正确指定工具链的路径。这里容易出错的地方是路径中包含空格或中文字符,以及工具链版本与鸿蒙源码要求的版本不匹配。我使用的是 gcc-arm-none-eabi-10-2020-q4-major 这个版本,相对稳定。

3. 内核选型与适配:LiteOS-M是如何“住进”STM32的?

鸿蒙为资源受限设备提供了LiteOS-M内核。它不是一个完全陌生的东西,你可以把它理解为一个深度定制和优化的实时操作系统内核,借鉴了类Unix的一些设计思想,但更加精简,任务调度、内存管理、中断处理、IPC机制都是为MCU量身打造的。

将LiteOS-M移植到STM32,核心工作是实现一个叫做“板级支持包”(BSP)。BSP是内核与具体硬件之间的桥梁,它需要告诉内核:这块板子的CPU是什么架构(Cortex-M3)、主频多少、内存(SRAM)从哪里开始、有多大、时钟怎么初始化、串口怎么收发一个字符等等。

OpenHarmony的源码目录 //device/board/ 下已经包含了许多厂商的BSP参考。对于STM32,特别是STM32F103系列,虽然可能没有直接的现成配置,但我们可以参考类似Cortex-M核的芯片实现(比如 //device/board/hisilicon/hispark_pegasus/ ,它基于Cortex-M4)。移植工作主要集中在这几个文件:

链接脚本(.ld文件) :定义STM32的Flash和SRAM的存储区域布局。这需要你对照STM32F103xC的数据手册,明确Flash的起始地址(0x08000000)、大小(比如256KB),SRAM的起始地址(0x20000000)、大小(比如48KB)。链接脚本会划分出代码段(.text)、数据段(.data、.bss)、堆(heap)和栈(stack)的空间。 /* 简化的链接脚本片段 */ MEMORY { FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 256K RAM (xrw) : ORIGIN = 0x20000000, LENGTH = 48K } 堆栈的大小设置需要谨慎。栈空间太小会导致任务切换或函数调用深度大时溢出;堆空间用于动态内存分配,LiteOS-M有自己的内存管理模块,但基础的C库函数如 malloc 也可能用到这里的堆。

堆栈的大小设置需要谨慎。栈空间太小会导致任务切换或函数调用深度大时溢出;堆空间用于动态内存分配,LiteOS-M有自己的内存管理模块,但基础的C库函数如 malloc 也可能用到这里的堆。

启动文件(startup_stm32f103xe.s) :这是芯片上电后运行的第一段汇编代码。它初始化堆栈指针、复位向量表,然后跳转到 main 函数(最终会跳到鸿蒙的 OHOS_SystemInit )。通常我们可以直接使用STM32CubeMX生成的启动文件,但需要确保其中断向量表与LiteOS-M的中断接管机制兼容。LiteOS-M通常需要重写 SysTick_Handler (系统滴答定时器,用于任务调度)和 PendSV_Handler (上下文切换)等中断服务程序。

系统时钟初始化 :在 //device/board/your_vendor/your_board/liteos_m/sdk/bsp/ 目录下,需要实现 board.c 和 hal_tick.c 等文件。 board.c 中的 SystemClock_Config() 函数负责配置STM32的HSI/HSE、PLL,将系统时钟设置到72MHz(以F103为例)。 hal_tick.c 则提供 HAL_InitTick() ,为HAL库(如果你用)或LiteOS-M的时钟节拍提供基准。

最小驱动实现 :至少需要实现一个串口驱动,用于调试信息输出(printf重定向到串口)。这涉及到GPIO和USART的初始化。实现 putchar() 或 HAL_UART_Transmit() 的封装,并在 //device/board/your_vendor/your_board/hals/communication/uart/ 目录下提供符合鸿蒙驱动框架的 uart.c ,实现 UartWrite 等标准接口。这样,上层的内核日志和你的应用 printf 才能看到输出。

这个过程本质上是在“教”LiteOS-M认识你的这块STM32开发板。你需要反复在芯片手册、参考BSP代码和鸿蒙的驱动框架文档之间切换。第一次编译通过,并且能通过串口看到内核启动日志(比如“OHOS Startup”)时,那种成就感是巨大的。

4. 构建与烧录:让代码在芯片上“活”过来

BSP适配得差不多后,就可以尝试编译了。OpenHarmony使用Gn和Ninja作为构建系统。你需要在你板子的目录下(比如 //device/board/your_vendor/my_stm32f103/ )创建配置文件 config.json ,指明使用的内核( liteos_m )、工具链、编译选项等。

然后,在源码根目录下,使用 hb 工具进行配置和编译:

编译过程会下载一些三方库(如lvgl、littlefs,如果配置了的话),并最终在 //out/my_stm32f103/ 目录下生成二进制文件,通常是 OHOS_Image.bin 或 OHOS_Image.hex 。

烧录环节则回到了嵌入式开发的老朋友身边。对于STM32,常用的有:

ST-Link Utility / STM32CubeProgrammer :通过ST-Link调试器连接板子的SWD接口,直接烧录 .hex 或 .bin 文件。这是最直接的方式。

OpenOCD :开源方案,配合GDB可以进行调试。在Linux环境下,用OpenOCD加载配置文件(针对STM32F1系列),然后通过 telnet 或GDB命令进行烧写。

串口ISP :通过Boot0引脚置高,利用内置Bootloader通过串口下载。这种方式不需要调试器,但速度较慢,且不适合频繁调试。

我个人的习惯是,前期调试阶段用ST-Link配合STM32CubeProgrammer,因为它速度快、可靠;当需要单步调试、查看变量时,则使用OpenOCD + VSCode(安装Cortex-Debug插件)搭建调试环境。将编译生成的 .elf 文件加载到VSCode中,可以设置断点、观察外设寄存器,对于分析启动失败、HardFault等问题至关重要。

第一次烧录后,可能面临的是串口毫无输出,或者直接进入HardFault。这时候,除了检查接线和波特率,最有效的调试手段就是利用调试器。在 Reset_Handler 入口处设断点,单步跟踪,看程序是在初始化时钟时卡住,还是在跳转到鸿蒙初始化函数时跑飞。往往问题就出在链接脚本的内存区域定义错误、堆栈指针初始化不对、或者某个关键的中断向量没有正确重定向。

5. 外设驱动与组件集成:点亮LED与更多可能

当内核成功启动,串口打印出日志后,下一步就是让板子上的外设“动”起来,验证驱动的完整性。最经典的莫过于点亮一个LED。

在鸿蒙的框架下,驱动开发遵循HDF(Hardware Driver Foundation)框架的规范,但对于轻量系统,很多时候我们可以先从简单的“裸机”式驱动集成开始,逐步向标准框架靠拢。以点亮LED为例:

硬件抽象层(HAL)实现 :在 //device/board/your_vendor/my_stm32f103/hals/gpio/ 目录下创建 gpio.c 。在这里,你需要用STM32的HAL库或者直接寄存器操作,实现 GpioSetDir (设置方向)、 GpioWrite (输出高低电平)等接口。这些接口是上层驱动服务或应用调用的标准接口。 // 示例:gpio.c 中的写函数实现 int32_t GpioWrite(uint16_t gpio, uint16_t val) { // gpio 参数可能编码了端口和引脚号,需要解析 // 例如,解析出GPIOx和Pin GPIO_TypeDef* port = GetPortFromGpioNum(gpio); uint16_t pin = GetPinFromGpioNum(gpio); HAL_GPIO_WritePin(port, pin, (GPIO_PinState)val); return 0; // 返回成功 }

驱动服务或直接调用 :在轻量系统中,你可以选择实现一个简单的驱动服务(遵循HDF),或者在应用层直接通过 DeviceIoControl 之类的接口调用HAL层函数。对于简单的LED闪烁,为了快速验证,我甚至可以在应用任务里直接调用HAL库函数(但这不符合框架规范,仅用于测试)。

编写测试应用 :在 //applications/sample/ 下创建你的demo应用。编写一个任务,在该任务中循环调用 GpioWrite 来控制LED引脚的电平,实现闪烁。同时,可以将闪烁状态通过串口打印出来。 void LedBlinkTask(void* arg) { (void)arg; uint16_t ledGpio = GetLedGpioNum(); // 获取LED对应的GPIO编号 GpioSetDir(ledGpio, GPIO_DIR_OUT); while (1) { GpioWrite(ledGpio, 1); // 亮 LOS_TaskDelay(500); // 鸿蒙的任务延时函数,单位是Tick printf("LED ON\n"); GpioWrite(ledGpio, 0); // 灭 LOS_TaskDelay(500); printf("LED OFF\n"); } } 将这个任务通过 LOS_TaskCreate 创建并启动。

将这个任务通过 LOS_TaskCreate 创建并启动。

当LED按照你的预期开始闪烁,串口同步输出信息时,说明从应用、到可能的驱动框架、再到HAL层、最终到硬件的通路已经打通。这个过程验证的不仅仅是GPIO,更是整个鸿蒙系统在你这块板子上的任务调度、延时、日志输出等基础功能是否正常。

在此基础上,你可以进一步集成更复杂的组件,比如文件系统(LittleFS)、图形库(LVGL)、网络协议栈(LwIP)等。这些组件在OpenHarmony中大多已经提供了适配层,你需要根据板子的实际情况(如Flash类型、显示屏接口、网卡型号)进行配置和移植。例如,集成LittleFS需要你实现底层Flash的读、写、擦除操作接口;集成LVGL则需要你实现屏幕的像素填充( flush_cb )和输入设备读取等回调函数。

6. 问题排查实录:那些让你头皮发麻的瞬间

移植过程绝非一帆风顺,以下是几个我遇到的典型问题及排查思路,希望能帮你避坑:

问题一:编译通过,但烧录后毫无反应,调试器发现卡在启动早期。

现象 :使用调试器单步执行,发现程序在 SystemInit (芯片自带的库函数)或刚进入 main 函数后就跑飞,甚至无法在 Reset_Handler 处停住。

排查 : 检查时钟 :首先怀疑时钟配置错误。STM32F103默认使用内部HSI(8MHz)时钟,如果你的BSP里配置了使用HSE(外部晶振),但板子上根本没焊晶振,或者晶振不起振,程序就会卡在时钟初始化等待。用示波器测量OSC_IN/OSC_OUT引脚,或者先改为使用HSI时钟测试。 检查向量表地址 :确保链接脚本中定义的Flash起始地址( ORIGIN )与STM32的启动模式匹配。对于从主Flash启动,就是0x08000000。同时,在 SystemInit 之前,需要正确初始化堆栈指针(SP),SP的值必须指向有效的RAM地址。 检查中断向量表重映射 :LiteOS-M接管了SysTick等中断。如果原有的启动文件中的中断服务程序(如 SysTick_Handler )是弱定义( weak ),而你在别处没有提供强定义实现,链接器可能会链接到错误的地址。确保你的BSP提供了这些中断处理程序的强定义,并且它们正确地调用了LiteOS-M的内核接口(如 LOS_TickHandler )。

检查时钟 :首先怀疑时钟配置错误。STM32F103默认使用内部HSI(8MHz)时钟,如果你的BSP里配置了使用HSE(外部晶振),但板子上根本没焊晶振,或者晶振不起振,程序就会卡在时钟初始化等待。用示波器测量OSC_IN/OSC_OUT引脚,或者先改为使用HSI时钟测试。

检查向量表地址 :确保链接脚本中定义的Flash起始地址( ORIGIN )与STM32的启动模式匹配。对于从主Flash启动,就是0x08000000。同时,在 SystemInit 之前,需要正确初始化堆栈指针(SP),SP的值必须指向有效的RAM地址。

检查中断向量表重映射 :LiteOS-M接管了SysTick等中断。如果原有的启动文件中的中断服务程序(如 SysTick_Handler )是弱定义( weak ),而你在别处没有提供强定义实现,链接器可能会链接到错误的地址。确保你的BSP提供了这些中断处理程序的强定义,并且它们正确地调用了LiteOS-M的内核接口(如 LOS_TickHandler )。

问题二:串口有输出,但打印乱码,或者输出一段后停止。

现象 :能看到字符输出,但全是乱码,或者只打印了“OHOS S”就没了。

排查 : 波特率 :这是最常见的原因。确认你的串口初始化代码设置的波特率(如115200)与PC端串口工具设置的波特率完全一致。STM32的时钟频率配置错误也会导致波特率计算偏差。 时钟源 :USART的时钟源(如APB2)频率是否正确?它依赖于系统时钟。如果系统时钟配置为72MHz,但你以为它是64MHz,计算出的波特率寄存器值就是错的。 缓冲区溢出 :如果输出一段后停止,可能是串口发送函数(如 putchar )没有正确处理发送完成标志,导致死等。或者,内核的日志缓冲区满了。检查你的串口发送是否是非阻塞的,或者是否有流控机制。 堆栈溢出 :打印任务或日志任务的堆栈设置太小,导致任务崩溃。可以在链接脚本中适当增大堆栈,或者在任务创建时分配更大的栈空间。

波特率 :这是最常见的原因。确认你的串口初始化代码设置的波特率(如115200)与PC端串口工具设置的波特率完全一致。STM32的时钟频率配置错误也会导致波特率计算偏差。

时钟源 :USART的时钟源(如APB2)频率是否正确?它依赖于系统时钟。如果系统时钟配置为72MHz,但你以为它是64MHz,计算出的波特率寄存器值就是错的。

缓冲区溢出 :如果输出一段后停止,可能是串口发送函数(如 putchar )没有正确处理发送完成标志,导致死等。或者,内核的日志缓冲区满了。检查你的串口发送是否是非阻塞的,或者是否有流控机制。

堆栈溢出 :打印任务或日志任务的堆栈设置太小,导致任务崩溃。可以在链接脚本中适当增大堆栈,或者在任务创建时分配更大的栈空间。

现象 :调用 LOS_TaskCreate 创建LED闪烁任务时失败。

排查 : 内存不足 :LiteOS-M需要预分配一块静态内存池供内核和任务使用。在 //kernel/liteos_m/kal/memory/ 相关的配置文件中,检查 LOSCFG_BASE_MEM_NODE_SIZE 等宏定义,确保分配的总内存足够。对于STM32F103这类RAM很小的芯片,需要精打细算。 任务栈大小 :创建任务时指定的栈大小不足。即使任务函数看起来很简单,但函数调用、局部变量、中断嵌套都可能消耗栈空间。可以先尝试将栈大小设置得大一些(比如1024字),看是否能创建成功,再逐步优化。 任务优先级冲突 :检查是否有其他任务或软件定时器占用了相同的优先级。或者,你创建的任务优先级设置过高(数字越小优先级越高),导致它立即运行并可能发生错误。

内存不足 :LiteOS-M需要预分配一块静态内存池供内核和任务使用。在 //kernel/liteos_m/kal/memory/ 相关的配置文件中,检查 LOSCFG_BASE_MEM_NODE_SIZE 等宏定义,确保分配的总内存足够。对于STM32F103这类RAM很小的芯片,需要精打细算。

任务栈大小 :创建任务时指定的栈大小不足。即使任务函数看起来很简单,但函数调用、局部变量、中断嵌套都可能消耗栈空间。可以先尝试将栈大小设置得大一些(比如1024字),看是否能创建成功,再逐步优化。

任务优先级冲突 :检查是否有其他任务或软件定时器占用了相同的优先级。或者,你创建的任务优先级设置过高(数字越小优先级越高),导致它立即运行并可能发生错误。

问题四:集成LVGL时,屏幕刷新缓慢或花屏。

现象 :LVGL示例程序能跑,但动画卡顿,或者显示内容错乱。

排查 : 帧缓冲区 :是否使用了单缓冲区?对于SPI等低速接口的屏幕,使用双缓冲区可以显著提升流畅度。确保在 lv_disp_drv_t 中正确配置了缓冲区数量和大小。 刷新区域 :在 flush_cb 回调函数中,确保只刷新指定的区域( area 参数),而不是整个屏幕。同时,该函数应是非阻塞的,发送完数据后立即返回,LVGL会在发送完成后通过 lv_disp_flush_ready 通知。 内存分配 :LVGL需要一块工作缓冲区( LV_MEM_SIZE )。如果这块内存太小,会导致渲染失败或花屏。根据你的屏幕分辨率和颜色深度,适当增大 LV_MEM_SIZE 。同时,确保这块内存是从堆中成功分配的(检查 lv_init() 的返回值)。 任务优先级与延时 :LVGL的 lv_timer_handler() 需要被定期调用(例如在 while(1) 循环中,或在一个单独的高优先级任务中)。确保调用间隔足够短(如5-10ms),并且该任务不会被长时间阻塞。

帧缓冲区 :是否使用了单缓冲区?对于SPI等低速接口的屏幕,使用双缓冲区可以显著提升流畅度。确保在 lv_disp_drv_t 中正确配置了缓冲区数量和大小。

刷新区域 :在 flush_cb 回调函数中,确保只刷新指定的区域( area 参数),而不是整个屏幕。同时,该函数应是非阻塞的,发送完数据后立即返回,LVGL会在发送完成后通过 lv_disp_flush_ready 通知。

内存分配 :LVGL需要一块工作缓冲区( LV_MEM_SIZE )。如果这块内存太小,会导致渲染失败或花屏。根据你的屏幕分辨率和颜色深度,适当增大 LV_MEM_SIZE 。同时,确保这块内存是从堆中成功分配的(检查 lv_init() 的返回值)。

任务优先级与延时 :LVGL的 lv_timer_handler() 需要被定期调用(例如在 while(1) 循环中,或在一个单独的高优先级任务中)。确保调用间隔足够短(如5-10ms),并且该任务不会被长时间阻塞。

7. 总结与展望:STM32遇上鸿蒙,是噱头还是未来?

完成一次完整的STM32鸿蒙移植,其价值远不止于让一块开发板跑起一个新的OS。这个过程迫使你深入理解芯片的启动流程、内存布局、中断机制,同时也让你窥见了鸿蒙系统在嵌入式层面的设计思路——通过标准化的HDF驱动框架、组件化的内核设计,试图降低设备开发的碎片化。

从实用角度看,对于资源极其紧张(Flash<64KB, RAM<20KB)的STM32F0/F1系列项目,坚持使用裸机或FreeRTOS可能仍是更务实的选择,因为鸿蒙LiteOS-M内核本身以及其配套框架会带来一定的开销。但对于STM32F4、H7等系列,或者需要连接丰富外设、涉及复杂业务逻辑、未来可能与其他鸿蒙设备(通过软总线)互联的项目,提前布局鸿蒙生态,利用其统一的驱动模型、安全的进程间通信、以及潜在的分布式能力,或许能带来长期的可维护性和扩展性优势。

这次移植更像是一次技术探路。它证明了在流行的MCU平台上运行鸿蒙是可行的,但距离真正的生产级应用,还有大量的稳定性测试、功耗优化、驱动完善工作要做。社区生态的成熟度、官方对更多芯片型号的BSP支持、以及开发工具的易用性提升,将是决定其能否在STM32开发者群体中广泛落地的关键。对于个人开发者或小团队而言,将其用于创新产品原型开发或技术储备,是一个颇具吸引力的方向;而对于大规模量产项目,则需要更审慎的评估。无论如何,亲手让两个活跃的生态发生碰撞,这个过程本身带来的学习和思考,就已经值回票价了。

Porting the OpenHarmony LiteOS-M Kernel to STM32: From Environment Setup to Driver Development

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

STM32 Porting of the OpenHarmony LiteOS-M Kernel in Practice: From Environment Setup to Driver Development

1. Project Origin: Why Bother with HarmonyOS on the STM32?

Recently, while sorting out several STM32 projects at hand, I noticed a rather interesting phenomenon: many projects are still using FreeRTOS or simply running bare-metal. That's not to say these solutions are bad—they are stable, mature, and market-proven. But every time I see the glue code written for thread synchronization, memory management, and driver frameworks, I can't help but feel a bit weary of 'reinventing the wheel.' Coincidentally, HarmonyOS (here specifically referring to OpenHarmony's mini system, such as the LiteOS-M kernel) has been making quite a bit of noise these past two years, with official publicity targeting IoT devices and emphasizing lightweight design, low power consumption, and high real-time performance. Doesn't that sound tailor-made for resource-constrained MCUs like the STM32?

So an idea occurred to me: could I get HarmonyOS running on an STM32F103 I had on hand (the classic 'Blue Pill' development board)? This isn't just about showing off technical skills or chasing trends. The deeper need is to personally experience that 'unified' framework HarmonyOS brings to embedded development—from kernel scheduling and device drivers to distributed capabilities—to see whether it can truly simplify the development process from a microcontroller to complex applications, and to what extent its so-called 'develop once, deploy on multiple devices' can actually be realized on a resource-strapped MCU. After all, knowledge gained on paper is always shallow; getting the code running is what really counts.

2. Environment Setup: A 'Pitfall' Reserve Starting from Scratch

After deciding to get hands-on, the first hurdle was setting up the build environment. HarmonyOS's official documentation recommends using Ubuntu as the development host, which is a moderate barrier for STM32 developers accustomed to Keil and IAR on Windows. I chose to install Ubuntu 20.04 LTS via WSL2 on Windows 11—a compromise that lets me use a Linux environment without leaving the familiar Windows ecosystem.

Note: OpenHarmony's compilation toolchain (such as hb and the Python environment) has specific requirements for Linux distributions and versions. It is strongly recommended to strictly follow the officially recommended Ubuntu version to avoid wasting time on odd environment issues.

After installing Ubuntu, follow the 'Mini System Quick Start' guide on the OpenHarmony open-source site. The core steps include: obtaining the source code, installing necessary tools (such as python3.8+, pip, hb, etc.), and configuring the compilation toolchain (here arm-none-eabi-gcc is used). The whole process is like walking a tightrope—a version mismatch in any step can cause subsequent compilation failures. One typical pitfall I encountered was the installation of hb (OpenHarmony's build tool). After installing via pip, running hb -h directly may throw an error saying a module cannot be found. This is because hb is installed to the user directory, but the environment variables may not be configured correctly. The solution is to find hb's actual installation path (usually in ~/.local/bin/) and add it to the PATH environment variable, or, more thoroughly, install it globally with sudo pip install (but be mindful of Python environment isolation).

Another key point is obtaining the source code. HarmonyOS's code repository is hosted on Gitee and managed with the repo tool. When pulling the code, you need to specify the -b branch and the --no-repo-verify parameter (skipping verification can sometimes speed things up, but weigh the security implications yourself). For the STM32F103, we're interested in the parts of OpenHarmony-3.2-Release or newer versions that support the mini system. The codebase is substantial, so the first pull requires patience.

Toolchain configuration is another key point. Compiling the STM32 with OpenHarmony requires ARM's official GCC toolchain (gnu-arm-embedded). You need to download it from ARM's official site or a domestic mirror, extract it, and then correctly specify the toolchain path in the build configuration files (such as //build/lite/config/component/board/arm.gni or the project-level config.json). Common pitfalls here include spaces or Chinese characters in the path, and a toolchain version that doesn't match the version required by the HarmonyOS source. I used the version gcc-arm-none-eabi-10-2020-q4-major, which is relatively stable.

3. Kernel Selection and Adaptation: How Does LiteOS-M 'Move Into' the STM32?

HarmonyOS provides the LiteOS-M kernel for resource-constrained devices. It's not entirely unfamiliar—you can think of it as a deeply customized and optimized real-time operating system kernel that draws on some Unix-like design ideas but is much more streamlined, with task scheduling, memory management, interrupt handling, and IPC mechanisms all tailored for MCUs.

The core work of porting LiteOS-M to the STM32 is implementing something called a 'Board Support Package' (BSP). The BSP is the bridge between the kernel and the specific hardware; it needs to tell the kernel: what architecture this board's CPU uses (Cortex-M3), what its clock frequency is, where memory (SRAM) starts and how large it is, how the clock is initialized, how the serial port sends and receives a character, and so on.

OpenHarmony's source directory //device/board/ already contains BSP references from many vendors. For the STM32, especially the STM32F103 series, although there may not be a direct ready-made configuration, we can reference implementations for chips with similar Cortex-M cores (such as //device/board/hisilicon/hispark_pegasus/, which is based on Cortex-M4). The porting work mainly focuses on these files:

Linker script (.ld file): Defines the memory region layout of the STM32's Flash and SRAM. This requires you to consult the STM32F103xC datasheet to determine the Flash start address (0x08000000), size (e.g., 256KB), SRAM start address (0x20000000), and size (e.g., 48KB). The linker script partitions the space for the code segment (.text), data segments (.data, .bss), the heap, and the stack. /* Simplified linker script snippet */ MEMORY { FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 256K RAM (xrw) : ORIGIN = 0x20000000, LENGTH = 48K } The stack and heap sizes must be set carefully. Too little stack space will cause overflow during task switching or deep function call chains; the heap is used for dynamic memory allocation—LiteOS-M has its own memory management module, but basic C library functions such as malloc may also use this heap.

The stack and heap sizes must be set carefully. Too little stack space will cause overflow during task switching or deep function call chains; the heap is used for dynamic memory allocation—LiteOS-M has its own memory management module, but basic C library functions such as malloc may also use this heap.

Startup file (startup_stm32f103xe.s): This is the first piece of assembly code that runs after the chip powers on. It initializes the stack pointer and the reset vector table, then jumps to the main function (which eventually jumps to HarmonyOS's OHOS_SystemInit). Usually we can directly use the startup file generated by STM32CubeMX, but we need to ensure its interrupt vector table is compatible with LiteOS-M's interrupt-taking-over mechanism. LiteOS-M typically needs to rewrite interrupt service routines such as SysTick_Handler (the system tick timer, used for task scheduling) and PendSV_Handler (context switching).

System clock initialization: Under the directory //device/board/your_vendor/your_board/liteos_m/sdk/bsp/, you need to implement files such as board.c and hal_tick.c. The SystemClock_Config() function in board.c is responsible for configuring the STM32's HSI/HSE and PLL, setting the system clock to 72MHz (taking the F103 as an example). hal_tick.c provides HAL_InitTick(), which supplies the time base for the HAL library (if you use it) or for LiteOS-M's clock tick.

Minimal driver implementation: At the very least, you need to implement a serial port driver for debug information output (printf redirected to the serial port). This involves initializing GPIO and USART. Implement a wrapper for putchar() or HAL_UART_Transmit(), and provide a uart.c under the directory //device/board/your_vendor/your_board/hals/communication/uart/ that conforms to the HarmonyOS driver framework, implementing standard interfaces such as UartWrite. Only then can upper-layer kernel logs and your application's printf produce visible output.

This process is essentially 'teaching' LiteOS-M to know your STM32 development board. You'll need to repeatedly switch between the chip manual, the reference BSP code, and the HarmonyOS driver framework documentation. When the first compilation succeeds and you can see the kernel boot log over the serial port (such as 'OHOS Startup'), the sense of accomplishment is enormous.

4. Build and Flashing: Bringing the Code to 'Life' on the Chip

Once the BSP adaptation is more or less done, you can try compiling. OpenHarmony uses Gn and Ninja as its build system. You need to create a configuration file config.json under your board's directory (such as //device/board/your_vendor/my_stm32f103/), specifying the kernel to use (liteos_m), the toolchain, compilation options, and so on.

Then, in the source root directory, use the hb tool to configure and compile:

The compilation process will download some third-party libraries (such as lvgl and littlefs, if configured) and ultimately generate a binary file in the //out/my_stm32f103/ directory, usually OHOS_Image.bin or OHOS_Image.hex.

The flashing stage brings us back to an old friend of embedded development. For the STM32, common options are:

ST-Link Utility / STM32CubeProgrammer: Connect to the board's SWD interface via an ST-Link debugger and directly flash the .hex or .bin file. This is the most straightforward method.

OpenOCD: An open-source solution that can be used with GDB for debugging. In a Linux environment, load a configuration file with OpenOCD (targeting the STM32F1 series), then flash via telnet or GDB commands.

Serial ISP: Set the Boot0 pin high and use the built-in Bootloader to download over the serial port. This method requires no debugger, but it is slow and not suitable for frequent debugging.

My personal habit is to use ST-Link with STM32CubeProgrammer during the early debugging stage because it is fast and reliable; when I need single-step debugging and variable inspection, I set up a debugging environment with OpenOCD + VSCode (with the Cortex-Debug plugin installed). Loading the compiled .elf file into VSCode lets you set breakpoints and observe peripheral registers, which is crucial for analyzing issues such as boot failures and HardFault.

After the first flash, you may face a completely silent serial port or a direct jump into HardFault. At this point, besides checking the wiring and baud rate, the most effective debugging tool is the debugger. Set a breakpoint at the Reset_Handler entry, single-step through, and see whether the program gets stuck initializing the clock or runs wild when jumping to the HarmonyOS initialization function. Often the problem lies in an incorrect memory region definition in the linker script, improper stack pointer initialization, or a key interrupt vector not being correctly remapped.

5. Peripheral Drivers and Component Integration: Lighting Up an LED and More Possibilities

Once the kernel boots successfully and the serial port prints logs, the next step is to get the board's peripherals 'moving' to verify driver integrity. The most classic example is lighting up an LED.

Under the HarmonyOS framework, driver development follows the specifications of the HDF (Hardware Driver Foundation) framework, but for the mini system, we can often start with simple 'bare-metal' style driver integration and gradually move toward the standard framework. Taking lighting up an LED as an example:

Hardware Abstraction Layer (HAL) implementation: Create gpio.c under the directory //device/board/your_vendor/my_stm32f103/hals/gpio/. Here, you need to use the STM32's HAL library or direct register operations to implement interfaces such as GpioSetDir (set direction) and GpioWrite (output high/low level). These interfaces are the standard interfaces called by upper-layer driver services or applications. // Example: implementation of the write function in gpio.c int32_t GpioWrite(uint16_t gpio, uint16_t val) { // The gpio parameter may encode the port and pin number, which needs to be parsed // For example, parse out GPIOx and Pin GPIO_TypeDef* port = GetPortFromGpioNum(gpio); uint16_t pin = GetPinFromGpioNum(gpio); HAL_GPIO_WritePin(port, pin, (GPIO_PinState)val); return 0; // return success }

Driver service or direct call: In the mini system, you can choose to implement a simple driver service (following HDF), or directly call HAL-layer functions at the application layer through interfaces like DeviceIoControl. For simple LED blinking, for quick verification, I can even call HAL library functions directly in the application task (but this does not conform to the framework specifications and is only for testing).

Writing a test application: Create your demo application under //applications/sample/. Write a task that calls GpioWrite in a loop to control the LED pin's level, achieving blinking. At the same time, you can print the blink status over the serial port. void LedBlinkTask(void* arg) { (void)arg; uint16_t ledGpio = GetLedGpioNum(); // Get the GPIO number corresponding to the LED GpioSetDir(ledGpio, GPIO_DIR_OUT); while (1) { GpioWrite(ledGpio, 1); // on LOS_TaskDelay(500); // HarmonyOS task delay function, unit is Tick printf("LED ON\n"); GpioWrite(ledGpio, 0); // off LOS_TaskDelay(500); printf("LED OFF\n"); } } Create and start this task via LOS_TaskCreate.

Create and start this task via LOS_TaskCreate.

When the LED starts blinking as you expected and the serial port outputs information synchronously, it means the path from the application, through the possible driver framework, to the HAL layer, and finally to the hardware has been opened up. This process verifies not only GPIO, but also whether fundamental functions of the entire HarmonyOS system on your board—such as task scheduling, delay, and log output—are working properly.

On this basis, you can further integrate more complex components, such as a file system (LittleFS), a graphics library (LVGL), a network protocol stack (LwIP), and so on. Most of these components already have adaptation layers provided in OpenHarmony; you need to configure and port them according to your board's actual situation (such as Flash type, display interface, and network card model). For example, integrating LittleFS requires you to implement the low-level Flash read, write, and erase operation interfaces; integrating LVGL requires you to implement callback functions such as screen pixel filling (flush_cb) and input device reading.

6. Troubleshooting Notes: Those Moments That Make Your Scalp Tingle

The porting process is by no means smooth sailing. The following are a few typical problems I encountered and my troubleshooting approaches, hoping to help you avoid pitfalls:

Problem 1: Compilation succeeds, but there is no response after flashing, and the debugger finds it stuck in the early boot stage.

Symptom: Stepping through with the debugger, the program is found to run wild in SystemInit (the chip's built-in library function) or right after entering the main function, and may even fail to stop at Reset_Handler.

Troubleshooting: Check the clock: First suspect a clock configuration error. The STM32F103 uses the internal HSI (8MHz) clock by default. If your BSP is configured to use HSE (external crystal) but the board has no crystal soldered on, or the crystal fails to oscillate, the program will get stuck waiting during clock initialization. Measure the OSC_IN/OSC_OUT pins with an oscilloscope, or first switch to the HSI clock for testing. Check the vector table address: Ensure the Flash start address (ORIGIN) defined in the linker script matches the STM32's boot mode. For booting from main Flash, it is 0x08000000. At the same time, before SystemInit, the stack pointer (SP) must be initialized correctly, and the SP value must point to a valid RAM address. Check interrupt vector table remapping: LiteOS-M takes over interrupts such as SysTick. If the interrupt service routines in the original startup file (such as SysTick_Handler) are weakly defined (weak) and you haven't provided a strong definition elsewhere, the linker may link to the wrong address. Make sure your BSP provides strong definitions of these interrupt handlers and that they correctly call LiteOS-M's kernel interfaces (such as LOS_TickHandler).

Check the clock: First suspect a clock configuration error. The STM32F103 uses the internal HSI (8MHz) clock by default. If your BSP is configured to use HSE (external crystal) but the board has no crystal soldered on, or the crystal fails to oscillate, the program will get stuck waiting during clock initialization. Measure the OSC_IN/OSC_OUT pins with an oscilloscope, or first switch to the HSI clock for testing.

Check the vector table address: Ensure the Flash start address (ORIGIN) defined in the linker script matches the STM32's boot mode. For booting from main Flash, it is 0x08000000. At the same time, before SystemInit, the stack pointer (SP) must be initialized correctly, and the SP value must point to a valid RAM address.

Check interrupt vector table remapping: LiteOS-M takes over interrupts such as SysTick. If the interrupt service routines in the original startup file (such as SysTick_Handler) are weakly defined (weak) and you haven't provided a strong definition elsewhere, the linker may link to the wrong address. Make sure your BSP provides strong definitions of these interrupt handlers and that they correctly call LiteOS-M's kernel interfaces (such as LOS_TickHandler).

Problem 2: The serial port has output, but it prints garbled characters, or stops after outputting a segment.

Symptom: You can see character output, but it's all garbled, or only 'OHOS S' is printed and then nothing.

Troubleshooting: Baud rate: This is the most common cause. Confirm that the baud rate set in your serial initialization code (e.g., 115200) is exactly the same as the baud rate set in the PC-side serial tool. An incorrect STM32 clock frequency configuration can also cause deviations in baud rate calculation. Clock source: Is the USART's clock source (e.g., APB2) frequency correct? It depends on the system clock. If the system clock is configured to 72MHz but you assume it's 64MHz, the calculated baud rate register value will be wrong. Buffer overflow: If output stops after a segment, the serial transmit function (such as putchar) may not correctly handle the transmit-complete flag, causing an infinite wait. Alternatively, the kernel's log buffer is full. Check whether your serial transmission is non-blocking, or whether there is a flow control mechanism. Stack overflow: The stack of the printing task or the logging task is set too small, causing the task to crash. You can appropriately increase the stack in the linker script, or allocate a larger stack space when creating the task.

Baud rate: This is the most common cause. Confirm that the baud rate set in your serial initialization code (e.g., 115200) is exactly the same as the baud rate set in the PC-side serial tool. An incorrect STM32 clock frequency configuration can also cause deviations in baud rate calculation.

Clock source: Is the USART's clock source (e.g., APB2) frequency correct? It depends on the system clock. If the system clock is configured to 72MHz but you assume it's 64MHz, the calculated baud rate register value will be wrong.

Buffer overflow: If output stops after a segment, the serial transmit function (such as putchar) may not correctly handle the transmit-complete flag, causing an infinite wait. Alternatively, the kernel's log buffer is full. Check whether your serial transmission is non-blocking, or whether there is a flow control mechanism.

Stack overflow: The stack of the printing task or the logging task is set too small, causing the task to crash. You can appropriately increase the stack in the linker script, or allocate a larger stack space when creating the task.

Symptom: Calling LOS_TaskCreate to create the LED blinking task fails.

Troubleshooting: Insufficient memory: LiteOS-M needs to pre-allocate a static memory pool for the kernel and tasks. In the configuration files related to //kernel/liteos_m/kal/memory/, check macro definitions such as LOSCFG_BASE_MEM_NODE_SIZE to ensure the total allocated memory is sufficient. For chips with very little RAM like the STM32F103, you need to budget carefully. Task stack size: The stack size specified when creating the task is insufficient. Even if the task function looks simple, function calls, local variables, and interrupt nesting can all consume stack space. You can first try setting the stack size larger (e.g., 1024 words) to see if creation succeeds, then optimize gradually. Task priority conflict: Check whether other tasks or software timers occupy the same priority. Or, the priority you set for the created task is too high (a smaller number means a higher priority), causing it to run immediately and possibly error out.

Insufficient memory: LiteOS-M needs to pre-allocate a static memory pool for the kernel and tasks. In the configuration files related to //kernel/liteos_m/kal/memory/, check macro definitions such as LOSCFG_BASE_MEM_NODE_SIZE to ensure the total allocated memory is sufficient. For chips with very little RAM like the STM32F103, you need to budget carefully.

Task stack size: The stack size specified when creating the task is insufficient. Even if the task function looks simple, function calls, local variables, and interrupt nesting can all consume stack space. You can first try setting the stack size larger (e.g., 1024 words) to see if creation succeeds, then optimize gradually.

Task priority conflict: Check whether other tasks or software timers occupy the same priority. Or, the priority you set for the created task is too high (a smaller number means a higher priority), causing it to run immediately and possibly error out.

Problem 4: When integrating LVGL, the screen refreshes slowly or displays a garbled, fragmented image.

Symptom: The LVGL sample program runs, but animations stutter, or the displayed content is disordered.

Troubleshooting: Frame buffer: Are you using a single buffer? For screens with low-speed interfaces such as SPI, using double buffering can significantly improve smoothness. Ensure the number and size of buffers are correctly configured in lv_disp_drv_t. Refresh area: In the flush_cb callback, make sure to refresh only the specified area (the area parameter), not the entire screen. At the same time, this function should be non-blocking—return immediately after sending data; LVGL will notify via lv_disp_flush_ready when sending is complete. Memory allocation: LVGL needs a working buffer (LV_MEM_SIZE). If this memory is too small, it will cause rendering failures or a garbled screen. Depending on your screen resolution and color depth, appropriately increase LV_MEM_SIZE. Also, make sure this memory is successfully allocated from the heap (check the return value of lv_init()). Task priority and delay: LVGL's lv_timer_handler() needs to be called periodically (e.g., in a while(1) loop, or in a separate high-priority task). Ensure the call interval is short enough (e.g., 5-10ms) and that the task is not blocked for long periods.

Frame buffer: Are you using a single buffer? For screens with low-speed interfaces such as SPI, using double buffering can significantly improve smoothness. Ensure the number and size of buffers are correctly configured in lv_disp_drv_t.

Refresh area: In the flush_cb callback, make sure to refresh only the specified area (the area parameter), not the entire screen. At the same time, this function should be non-blocking—return immediately after sending data; LVGL will notify via lv_disp_flush_ready when sending is complete.

Memory allocation: LVGL needs a working buffer (LV_MEM_SIZE). If this memory is too small, it will cause rendering failures or a garbled screen. Depending on your screen resolution and color depth, appropriately increase LV_MEM_SIZE. Also, make sure this memory is successfully allocated from the heap (check the return value of lv_init()).

Task priority and delay: LVGL's lv_timer_handler() needs to be called periodically (e.g., in a while(1) loop, or in a separate high-priority task). Ensure the call interval is short enough (e.g., 5-10ms) and that the task is not blocked for long periods.

7. Summary and Outlook: When STM32 Meets HarmonyOS—A Gimmick or the Future?

Completing a full STM32–HarmonyOS port is worth far more than just getting a new OS running on a development board. This process forces you to deeply understand the chip's boot flow, memory layout, and interrupt mechanisms, while also giving you a glimpse of HarmonyOS's design philosophy at the embedded level—through a standardized HDF driver framework and a componentized kernel design, it attempts to reduce the fragmentation of device development.

From a practical standpoint, for STM32F0/F1 series projects with extremely tight resources (Flash<64KB, RAM<20KB), sticking with bare-metal or FreeRTOS may still be the more pragmatic choice, because the HarmonyOS LiteOS-M kernel itself and its supporting framework introduce some overhead. But for series such as the STM32F4 and H7, or projects that need to connect rich peripherals, involve complex business logic, and may interconnect with other HarmonyOS devices (via the soft bus) in the future, laying out the HarmonyOS ecosystem early—leveraging its unified driver model, secure inter-process communication, and potential distributed capabilities—may bring long-term advantages in maintainability and scalability.

This porting effort is more like a technological pathfinding exercise. It proves that running HarmonyOS on a popular MCU platform is feasible, but there is still a great deal of work to be done—stability testing, power consumption optimization, and driver refinement—before it reaches true production-grade applications. The maturity of the community ecosystem, official BSP support for more chip models, and improvements in the ease of use of development tools will be key to determining whether it can be widely adopted among STM32 developers. For individual developers or small teams, using it for innovative product prototyping or as a technology reserve is an attractive direction; for large-scale mass-production projects, a more prudent evaluation is needed. In any case, personally bringing two active ecosystems into collision—the learning and thinking this process itself brings has already been worth the price of admission.

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

📮 需求咨询📮 Inquiry