基于STM32的低功耗DIY智能手表实战:硬件选型、软件架构与功耗优化Building a Low-Power DIY Smartwatch with STM32: Hardware Selection, Software Architecture, and Power Optimization


AI free token/AI免费积分

基于STM32的低功耗DIY智能手表实战:硬件选型、软件架构与功耗优化

本文来源:http://www.lpqz.cn/news/124554
若有版权问题,请来信告知:13951431913#139.com 或在右方提交评论。

1. 为什么我要用 STM32 从头撸一块手表第一次动了做手表的念头是看到市面上那些动辄上千的智能手表功能确实花哨但续航普遍拉胯一天一充甚至半天一充。我当时就想能不能用 STM32 做一块“够用就好”的手表——能看时间、能计步、能测个心率、续航撑个三五天关键是所有代码和硬件都攥在自己手里想改什么改什么。这个想法一旦冒出来就压不住了前后折腾了大概两个月中间踩了无数坑从选芯片到画板子、从驱动屏幕到调 RTC 走时精度每一步都有故事。STM32 做手表这件事听起来像是“用大炮打蚊子”毕竟一块手表的核心功能无非就是走时。但真正动手之后你会发现STM32 的丰富外设恰恰是它的优势所在RTC 负责走时、TIM 做按键扫描和 PWM 背光、SPI 驱动屏幕、I2C 挂传感器、ADC 读电池电量、DMA 搬运数据降低 CPU 占用、Stop 模式把功耗压到微安级。这些外设如果单独拿出来都不难难的是怎么让它

们协同工作还要在有限的电池容量下跑出可接受的续航。这篇文章适合谁看如果你已经玩过 STM32 的基础例程点过灯、调过串口、用过定时器那这篇内容就是为你准备的。我会把整个手表的开发过程拆开揉碎从硬件选型到软件架构从屏幕驱动到功耗优化每一步都讲清楚“为什么这么做”而不只是“怎么做”。如果你是完全零基础的小白建议先找块最小系统板把 GPIO、定时器、中断这些基础概念过一遍再回来不然有些地方可能会觉得跳跃。需要提前说明的是我做这块手表的目标是“实用优先”不是追求极致轻薄或者炫酷 UI。所以选型上会偏向于好焊接、好调试、资料多的方案而不是最新最贵的芯片。整个项目的核心思路是用成熟的方案快速跑通再逐步优化细节。下面就从硬件选型开始一步步展开。2. 硬件选型主控、屏幕、传感器怎么挑2.1 主控芯片为什么我最终选了 STM32L4 系列选主控是第一个岔路口。STM32 家族庞大F1、F4、L4、G0、G4

各有各的定位。我一开始用的是手头现成的 STM32F103C8T6 最小系统板就是大家常说的“蓝板”。这块板子便宜、资料多、社区活跃拿来跑通原型完全没问题。但真正要做到手表形态F103 有两个硬伤一是功耗偏高运行模式下的电流在几十毫安级别就算进 Stop 模式也有几十微安对于一块 200mAh 的小电池来说续航会很紧张二是封装偏大LQFP48 虽然不算大但放在手表 PCB 上还是占地方。后来我把目光转向了 STM32L4 系列具体型号是 STM32L431CBT6。选它的理由很直接Cortex-M4 内核带 FPU主频 80MHz性能够用LQ 系列主打低功耗运行模式约 100μA/MHzStop 2 模式可以低到 1μA 左右RTC 走时加上 LCD 刷新整体平均电流可以控制在 200μA 以内LQFP48 封装和 F103 兼容PCB 改动小Flash 128KB、RAM 64KB对于

手表固件来说绰绰有余。这里有个细节值得展开说L4 系列的 Stop 模式分 Stop 0、Stop 1、Stop 2 三档功耗依次降低但唤醒时间和保留的外设也不同。Stop 2 最省电但只有 RTC、IWDG、部分 GPIO 能唤醒SRAM2 可以保留数据。我的做法是把走时相关的变量放在 SRAM2主循环进 Stop 2靠 RTC 闹钟每秒唤醒一次刷新时间按键用 EXTI 唤醒。这样大部分时间芯片都在微安级待机只有刷新屏幕和读传感器时才短暂跑到运行模式。如果你手头只有 F103 也不想换其实也能做只是续航会打折扣。我的建议是原型阶段用 F103 跑通逻辑正式版再换 L4。这样既不耽误学习也能保证最终效果。2.2 显示屏SPI 屏还是 I2C 屏这是个问题手表屏幕的选择直接决定了 UI 能做成什么样。市面上常见的小尺寸屏幕有几种0.96 寸 OLEDSSD1306、1.3 寸 OLEDSH1

106、1.14 寸 IPSST7789、1.28 寸圆屏GC9A01。我前后试过三种最后留用的是 1.28 寸圆屏 GC9A01240x240 分辨率SPI 接口。先说 OLED。SSD1306 的 0.96 寸屏是最容易上手的I2C 接口两根线搞定驱动库满地都是。但它有两个问题一是尺寸小做手表表盘显得局促二是 OLED 长时间显示静态内容会有烧屏风险虽然手表 UI 会经常刷新但表盘边框这类固定元素还是有隐患。SH1106 的 1.3 寸屏稍大一些但本质还是 OLED烧屏问题依旧。再说 IPS 圆屏。GC9A01 这块屏是我最后选定的理由如下240x240 的分辨率在 1.28 寸上像素密度够高显示细腻圆形屏幕天然适合手表形态不用额外做遮罩SPI 接口虽然线多几根但刷新率高配合 DMA 可以做到流畅刷屏IPS 可视角度好侧看也不偏色。唯一的缺点是驱动比 OLED 复杂一些初始化序列长但网

上有现成的开源驱动可以参考。这里有个实操心得GC9A01 的 SPI 时钟可以跑到 40MHz 甚至更高但前提是接线要短、PCB 走线要等长。我一开始用杜邦线飞线时钟上到 20MHz 就开始花屏后来改成 PCB 走线40MHz 稳如老狗。所以如果你打算长期用建议直接画板子别省这一步。2.3 传感器与电源心率、加速度计、电池管理手表要有点“智能”的样子传感器少不了。我选了三个LIS3DH 三轴加速度计做计步和抬腕检测MAX30102 做心率和血氧TP4056 做锂电池充电管理。LIS3DH 是 ST 自家的加速度计I2C 接口功耗低到 2μA低功耗模式支持中断输出。计步算法我放在 MCU 里跑通过读取三轴加速度的合矢量变化来判断步伐。这里有个坑LIS3DH 的中断引脚配置比较绕需要设置阈值、持续时间、滤波参数一开始我没调好导致轻微晃动就触发中断功耗飙升。后来把阈值调到 0.3g、持续时间设为

20ms才稳定下来。MAX30102 是心率和血氧传感器I2C 接口内置 FIFO。它的难点在于光学设计和算法。LED 驱动电流、采样率、FIFO 读取时机都会影响数据质量。我的做法是用 100Hz 采样率、LED 电流 7mA 左右FIFO 半满中断读取然后在 MCU 里做简单的峰值检测算心率。精度肯定比不上专业医疗设备但日常看看趋势够用了。电源部分TP4056 负责充电DW01 加 8205A 做保护ADC 通过分压电阻读电池电压。这里要注意分压电阻的阻值选择太大则 ADC 输入阻抗不匹配读数不准太小则静态功耗高。我最后用了 100k 和 100k 分压并联 0.1μF 电容滤波读数稳定性可以接受。3. 软件架构从裸机到状态机3.1 裸机还是 RTOS我的选择与理由软件架构是第二个岔路口。裸机写手表完全可行但代码组织不好会变成一团乱麻。RTOS 能简化任务调度但会增加 RAM 开销和

上下文切换功耗。我最终选了裸机加状态机的方案理由有三一是手表的功能相对固定任务不多裸机足够二是 RTOS 的 tick 中断会频繁唤醒 CPU对低功耗不友好三是状态机让代码逻辑清晰每个状态做什么一目了然。我的主循环结构是这样的上电初始化后进入主循环主循环里先处理事件标志然后根据当前状态执行对应逻辑最后进 Stop 模式等中断唤醒。事件标志包括RTC 秒中断、按键中断、加速度计中断、充电状态变化中断。每个中断只做最少的处理置个标志就退出具体逻辑在主循环里跑。这种“中断置标志、主循环处理”的模式好处是中断响应快、主循环逻辑集中、功耗可控。坏处是如果某个事件处理时间过长会影响其他事件的响应。所以我在主循环里对耗时操作做了分片比如屏幕刷新一帧拆成多次每次刷一部分刷完再进 Stop。3.2 状态机设计待机、亮屏、菜单、充电四个状态手表的状态不多我定义了四个待机STANDBY、亮屏ACTIVE、菜单M

ENU、充电CHARGING。状态之间的切换由事件驱动。待机状态下屏幕关闭MCU 进 Stop 2只有 RTC 和 EXTI 在工作。RTC 每秒唤醒一次更新内部时间变量然后立刻回 Stop。按键中断或抬腕中断触发后切到亮屏状态。亮屏状态下屏幕打开显示表盘MCU 保持运行。如果 5 秒内没有操作自动回待机。如果有按键长按切到菜单状态。菜单状态下屏幕显示菜单项按键上下切换短按确认长按返回。菜单里可以设置时间、查看计步、启动心率测量等。充电状态下屏幕显示充电图标和电量百分比MCU 保持运行但关闭传感器减少发热。状态切换的代码我用 switch-case 实现每个状态一个函数函数里先判断是否有状态切换事件有就返回新状态没有就执行当前状态的逻辑。这样主循环里只需要调用当前状态函数根据返回值决定是否切换。3.3 时间管理RTC 走时精度与校准RTC 是手表的核心走时不准一切白搭。STM32L4 的

RTC 用外部 32.768kHz 晶振时精度取决于晶振本身的误差和负载电容的匹配。我一开始用的是普通的 32.768kHz 圆柱晶振日误差在几秒到十几秒之间。后来换了精度更高的晶振±5ppm并仔细调整了负载电容日误差降到了 1 秒以内。这里有个细节STM32 的 RTC 支持数字校准可以通过 RTC_CALR 寄存器调整时钟频率。具体做法是测量一段时间内的误差算出 ppm 值然后写入校准寄存器。比如日误差 2 秒对应约 23ppm就在 CALR 里设置相应的校准值。这个功能很实用可以把普通晶振的精度提升一个档次。另外RTC 的备份域供电也要注意。VBAT 引脚接纽扣电池或超级电容主电源掉电时 RTC 继续走时。我用的是 0.1F 超级电容充满后可以维持 RTC 走时十几个小时日常使用足够了。4. 屏幕驱动与 UI 设计让圆屏显示表盘4.1 GC9A01 初始化那些手册上没写的细节GC9A

01 的初始化序列比较长手册里给的是一套通用参数但实际用起来还需要根据屏幕厂商的差异做调整。我踩过的坑主要有两个一是颜色格式二是显示方向。颜色格式方面GC9A01 支持 RGB565 和 RGB666默认是 RGB565。但有些批次的屏幕出厂时 MADCTL 寄存器的 BGR 位没设对导致红色和蓝色互换。我一开始显示的表盘是蓝色的折腾了半天才发现是 BGR 位的问题。解决办法是在初始化序列里显式设置 MADCTL 寄存器把 BGR 位置 1 或清 0试一次就知道哪个对了。显示方向方面圆屏没有“横竖”之分但表盘的 12 点方向需要和实际佩戴方向一致。这涉及到 MADCTL 的 MX、MY、MV 三个位。我的做法是先把屏幕点亮显示一个不对称的图案比如一个箭头然后旋转屏幕看箭头指向调整 MADCTL 直到箭头朝上。初始化序列里还有几个关键参数帧率控制、电源控制、伽马校正。帧率我设的是 60Hz再

高功耗上去了收益不大。伽马校正用默认值就行除非你对色彩有特别要求。4.2 表盘绘制用 DMA 刷屏降低 CPU 占用240x240 的 RGB565 一帧是 115200 字节如果全屏刷新SPI 按 40MHz 算传输时间约 23ms。这 23ms 里如果 CPU 全程参与功耗会很高。我的做法是用 DMA 把帧缓冲搬到 SPI 数据寄存器CPU 只负责准备数据传输交给 DMA传完之后 DMA 中断唤醒 CPU 准备下一帧。帧缓冲我开了两块一块用于当前显示一块用于绘制下一帧。绘制完成后切换指针DMA 从新缓冲区搬数据。这样绘制和传输可以重叠刷屏更流畅。表盘的绘制内容分三层背景层渐变或纯色、刻度层12 个刻度点和数字、指针层时针、分针、秒针。背景层和刻度层是静态的只在切换表盘样式时重绘指针层每秒钟重绘一次。为了减少重绘面积我只重绘指针经过的区域而不是全屏刷新。具体做法是记录上一秒指针的位置擦除

旧指针绘制新指针两次绘制的区域合并后只刷这一块。这里有个实操技巧指针的绘制用画线算法Bresenham比用图形库的 drawLine 快很多。秒针我用的是 1 像素宽的线时针和分针用 3 像素宽的线视觉上更协调。4.3 低功耗刷新策略局部刷新与息屏手表的屏幕是功耗大户GC9A01 全亮时电流在 20mA 左右背光占大头。我的低功耗策略分三级全亮、半亮、息屏。全亮用于操作时背光 PWM 占空比 100%。半亮用于待机表盘占空比 30%既能看清时间又省电。息屏用于长时间无操作背光关闭屏幕进睡眠模式MCU 进 Stop 2。息屏后 RTC 每秒唤醒但屏幕不刷新只更新时间变量。按键或抬腕中断触发后先开背光再刷新屏幕然后切到亮屏状态。这样从息屏到亮屏的响应时间在 100ms 以内体感上基本是即时的。背光 PWM 我用 TIM3 的通道 1 输出频率 1kHz占空比可调。频率太低会有频闪太高则开关损耗

大1kHz 是个折中。5. 功耗优化从毫安到微安的实战5.1 实测各模式电流数据说话功耗优化不能靠猜得实测。我用万用表和电流探头测了各个模式下的电流数据如下模式电流说明运行模式全速12mA80MHz屏幕全亮传感器开启运行模式降频4mA16MHz屏幕半亮传感器间歇Stop 2RTC 走时1.8μA屏幕关闭RAM2 保留Stop 2RTC加速度计中断3.5μA加速度计低功耗模式待机屏幕息屏MCU Stop 2约 25μA含屏幕睡眠电流和 LDO 静态电流从数据看MCU 本身的 Stop 2 电流很低但屏幕睡眠电流和 LDO 静态电流加起来有 20μA 左右。所以如果想进一步压功耗得从屏幕和电源芯片下手。我后来换了一款静态电流更低的 LDOTPS7A02静态电流 25nA整体待机电流降到了 8μA 左右。5.2 外设时钟门控不用就关STM32 的外设时钟默认是开启的不用的话要手动关。我在初始化完

成后把不用的外设时钟全部关闭包括 ADC、DAC、USB、CAN 等。用到的外设也尽量在不用时关时钟比如心率传感器只在测量时开 I2C 时钟测完就关。GPIO 的处理也有讲究。未使用的 GPIO 配置为模拟输入避免浮空输入导致的漏电流。用到的 GPIO 根据场景配置输出引脚设推挽输出输入引脚设上拉或下拉中断引脚设浮空但开启中断。这里有个容易忽略的点调试接口。SWD 引脚在运行时如果保持调试模式会有额外功耗。我的做法是在正式固件里禁用 SWD需要调试时再通过特定按键组合重新使能。禁用 SWD 后待机电流能再降 1-2μA。5.3 传感器间歇工作心率与计步的功耗平衡心率和计步是两大耗电功能。心率传感器 MAX30102 工作时电流约 10mA计步用的 LIS3DH 低功耗模式约 2μA。所以策略很明确计步常开心率按需开启。计步方面LIS3DH 配置为 10Hz 采样率、低功耗模式通过中断唤醒

Building a Low-Power DIY Smartwatch with STM32: Hardware Selection, Software Architecture, and Power Optimization

本文来源:http://www.lpqz.cn/news/124554
若有版权问题,请来信告知:13951431913#139.com 或在右方提交评论。

1. Why I decided to build a watch from scratch using an STM32 The first time I had the idea of making a watch was when I saw those smartwatches on the market that often cost thousands of dollars. They have really fancy features, but their battery life is generally poor, requiring charging every day or even every half-day. At that time, I wondered if I could use an STM32 to make a watch that was "good enough" — one that could tell the time, count steps, measure heart rate, and last for three to five days. The key was that all the code and hardware would be under my control, allowing me to modify whatever I wanted. Once this idea popped into my head, I couldn't suppress it. I spent about two months working on it, falling into countless pitfalls along the way. From selecting the chip to designing the board, from driving the screen to adjusting the RTC's timekeeping accuracy, every step had its own story. Using an STM32 to make a watch sounds like "using a cannon to swat a mosquito." After all, the core function of a watch is simply to tell time. But once you actually start working on it, you'll find that the STM32's wealth of peripherals is precisely where its strength lies. The RTC handles timekeeping, the TIM manages key scanning and PWM backlight, the SPI drives the display, the I2C connects sensors, the ADC reads the battery level, the DMA transfers data to reduce CPU usage, and Stop mode reduces power consumption to the microampere level. These peripherals are not difficult when considered individually. The challenge lies in how to make them work together.

They also need to work together to achieve acceptable battery life with a limited battery capacity. Who is this article for? If you have already worked with the basic STM32 examples, turned on LEDs, configured serial ports, and used timers, then this article is for you. I will break down the entire development process of the watch, from hardware selection to software architecture, from screen driver to power consumption optimization. I will explain "why" for every step, not just "how." If you are a complete beginner with no prior knowledge, I recommend that you first get a minimum system board and go through the basic concepts of GPIO, timers, and interrupts before coming back. Otherwise, some parts might seem to jump around. I should clarify beforehand that my goal in making this watch is to "prioritize practicality," not to pursue an ultra-thin design or a flashy UI. Therefore, when selecting components, I tend to favor solutions that are easy to solder, easy to debug, and have plenty of documentation, rather than the latest and most expensive chips. The core idea of the entire project is to quickly get a proven solution up and running, and then gradually optimize the details. Next, let's start with the hardware selection and go through it step by step. 2. Hardware Selection: How to Choose the Main Controller, Display, and Sensors 2.1 Main Controller Chip Why I Ultimately Chose the STM32L4 Series Selecting the main controller is the first decision point. The STM32 family is vast: F1, F4, L4, G0, G4

Each has its own positioning. At first, I used the STM32F103C8T6 minimum system board that I had on hand, which is commonly known as the "Blue Pill." This board is inexpensive, has plenty of documentation, and has an active community. It's perfectly fine for running a prototype. However, the F103 has two major drawbacks when it comes to creating a smartwatch. Firstly, its power consumption is relatively high. The current in run mode is in the tens of milliamperes, and even in Stop mode, it's still in the tens of microamperes. For a small 200mAh battery, this means the battery life would be quite tight. Secondly, its package is relatively large. Although the LQFP48 package isn't huge, it still takes up a lot of space on a smartwatch PCB. Later, I turned my attention to the STM32L4 series, specifically the STM32L431CBT6 model. The reasons for choosing it are straightforward: It has a Cortex-M4 core with an FPU, a clock speed of 80 MHz, and sufficient performance. The LQ series is known for its low power consumption, with an operating current of about 100 μA/MHz. In Stop 2 mode, the current can be as low as around 1 μA. With the RTC running and the LCD refreshing, the overall average current can be kept below 200 μA. The LQFP48 package is compatible with the F103, requiring minimal PCB modifications. It has 128 KB of Flash and 64 KB of RAM, which is sufficient for

It's more than enough for smartwatch firmware. There is a detail here that is worth elaborating on. The Stop mode of the L4 series is divided into three levels: Stop 0, Stop 1, and Stop 2. The power consumption decreases sequentially, but the wake-up time and the peripherals that are retained also differ. Stop 2 is the most power-saving mode, but only the RTC, IWDG, and some GPIOs can wake it up. SRAM2 can retain data. My approach is to place the variables related to timekeeping in SRAM2. The main loop enters Stop 2 mode, relying on the RTC alarm to wake up once per second to refresh the time. The button uses EXTI for wakeup. This way, the chip is in microampere-level standby mode most of the time, and only briefly enters run mode when refreshing the screen and reading the sensor. If you only have an F103 on hand and don't want to switch, you can still do it, but the battery life will be compromised. My suggestion is to use the F103 to run the logic during the prototype stage and then switch to the L4 for the official version. This way, it won't delay your learning and will also ensure the final result. 2.2 Display: SPI or I2C? This is a question. The choice of watch screen directly determines what the UI can look like. There are several common small-size screens on the market: the 0.96-inch OLED SSD1306 and the 1.3-inch OLED SH1.

106. 1.14-inch IPS ST7789, 1.28-inch round screen GC9A01. I tried three different ones, and the one I ended up using was the 1.28-inch round screen GC9A01 with 240x240 resolution and an SPI interface. Let's talk about OLED first. The SSD1306's 0.96-inch screen is the easiest to get started with. It uses an I2C interface with just two wires, and there are plenty of driver libraries available. However, it has two issues. Firstly, its small size makes it look cramped as a watch face. Secondly, OLED displays are at risk of burn-in when displaying static content for extended periods. Although the watch UI is refreshed frequently, fixed elements like the watch face bezel still pose a potential risk. The 1.3-inch screen of the SH1106 is slightly larger, but it is still essentially an OLED, and the issue of screen burn-in persists. Now, let's talk about the IPS round screen. The GC9A01 display was my final choice for the following reasons: Its 240x240 resolution provides a sufficiently high pixel density on the 1.28-inch screen, resulting in a fine display. The circular shape naturally suits the form of a watch, eliminating the need for an additional mask. Although the SPI interface requires a few more wires, it offers a high refresh rate, and when combined with DMA, it can achieve smooth screen refreshes. IPS technology provides good viewing angles, and there is no color shift when viewed from the side. The only downside is that the driver is slightly more complex than OLED, and the initialization sequence is longer, but

There are ready-made open-source drivers available for reference. Here's a practical tip: The SPI clock of the GC9A01 can run at 40MHz or even higher, but only if the wiring is short and the PCB traces are of equal length. When I first used DuPont jumper wires, the screen started to flicker when the clock reached 20 MHz. Later, I switched to PCB traces, and at 40 MHz, it was as stable as a rock. So, if you plan to use it for a long time, it's recommended to design the PCB directly and not skip this step. 2.3 Sensors and Power Supply: Heart rate, accelerometer, battery management. For a watch to look a bit "smart," sensors are indispensable. I chose three LIS3DH triaxial accelerometers for step counting and wrist-raising detection, the MAX30102 for heart rate and blood oxygen, and the TP4056 for lithium battery charging management. The LIS3DH is ST's own accelerometer. Its I2C interface has a power consumption as low as 2 μA. The low-power mode supports interrupt output. I run the step-counting algorithm on the MCU, which determines the steps by reading the changes in the resultant vector of the three-axis accelerometer. Here's a pitfall: The configuration of the LIS3DH's interrupt pin is quite convoluted, requiring the setting of thresholds, durations, and filter parameters. Initially, I didn't adjust it properly, which caused even slight movements to trigger the interrupt, leading to a surge in power consumption. Later, I adjusted the threshold to 0.3g and set the duration to

It takes 20 ms to stabilize. The MAX30102 is a heart rate and blood oxygen sensor with an I2C interface and built-in FIFO. Its challenges lie in optical design and algorithms. The LED drive current, sampling rate, and FIFO read timing all affect data quality. My approach is to use a 100Hz sampling rate, an LED current of around 7mA, and a FIFO half-full interrupt read, then perform a simple peak detection in the MCU to calculate the heart rate. The accuracy is certainly not as good as that of professional medical equipment, but it is sufficient for checking trends on a daily basis. In the power supply section, the TP4056 is responsible for charging, the DW01 and 8205A provide protection, and the ADC reads the battery voltage through a voltage divider resistor. It is important to note here that if the resistance value of the voltage divider resistor is too high, the ADC input impedance will not match, resulting in inaccurate readings. If it is too low, the static power consumption will be high. In the end, I used 100k and 100k voltage dividers in parallel with a 0.1μF capacitor for filtering, and the stability of the readings was acceptable. 3. Software Architecture: From Bare-Metal to State Machine 3.1 Bare-Metal or RTOS? My Choice and Reasoning The software architecture is the second fork in the road. It is perfectly feasible to program a smartwatch using bare metal, but if the code is poorly organized, it can become a tangled mess. RTOS can simplify task scheduling, but it increases RAM overhead and

Context switch power consumption. I ultimately chose the bare-metal plus state machine solution for three reasons. First, the watch's functions are relatively fixed, with few tasks, so bare-metal is sufficient. Second, the RTOS tick interrupt frequently wakes up the CPU, which is not conducive to low power consumption. Third, the state machine makes the code logic clear, making it easy to see what each state does. My main loop structure is as follows: After power-on initialization, it enters the main loop. In the main loop, it first processes the event flags, then executes the corresponding logic based on the current state, and finally enters Stop mode, waiting for an interrupt to wake it up. Event flags include RTC second interrupts, button interrupts, accelerometer interrupts, and charging status change interrupts. Each interrupt performs only minimal processing, sets a flag, and then exits. The specific logic runs in the main loop. The advantage of this "interrupt sets flag, main loop handles" pattern is that the interrupt response is fast, the main loop logic is centralized, and power consumption is controllable. The downside is that if an event takes too long to process, it can affect the responsiveness of other events. So, in the main loop, I split time-consuming operations into smaller tasks. For example, refreshing one frame of the screen is divided into multiple steps, with each step refreshing a portion of the screen before entering the Stop mode. 3.2 State Machine Design: Standby, Screen On, Menu, and Charging – Four States. The watch doesn't have many states, so I defined four: STANDBY, ACTIVE (Screen On), MENU, and CHARGING.

ENU, CHARGING. The switching between states is event-driven. In standby mode, the screen is off and the MCU enters Stop 2, with only the RTC and EXTI operating. The RTC wakes up once per second to update the internal time variable and then immediately returns to Stop. After the button interrupt or wrist-lift interrupt is triggered, the device switches to the screen-on state. In the screen-on state, the screen turns on to display the watch face, and the MCU continues to operate. If there is no operation within 5 seconds, it will automatically return to standby mode. If a button is pressed and held, the device switches to the menu mode. In the menu mode, the screen displays the menu items. Use the up and down buttons to navigate, press briefly to confirm, and press and hold to return. In the menu, you can set the time, view the step counter, start heart rate measurement, etc. In the charging state, the screen displays the charging icon and the battery percentage. The MCU remains operational, but the sensor is turned off to reduce heat generation. For the code for state switching, I used switch-case to implement one function for each state. The function first determines whether there is a state switching event. If there is, it returns the new state; if not, it executes the logic of the current state. In this way, the main loop only needs to call the current state function and decide whether to switch based on the return value. 3.3 Time Management: RTC Timekeeping Accuracy and Calibration. The RTC is the core of the watch. If the timekeeping is inaccurate, everything else is useless. The STM32L4's

When the RTC uses an external 32.768 kHz crystal oscillator, the accuracy depends on the error of the crystal oscillator itself and the matching of the load capacitance. At first, I used an ordinary 32.768 kHz cylindrical crystal oscillator, and the daily error was between a few seconds and over ten seconds. Later, I switched to a higher-precision crystal oscillator with ±5 ppm and carefully adjusted the load capacitance, reducing the daily error to within 1 second. Here's a detail: The RTC of the STM32 supports digital calibration, and the clock frequency can be adjusted through the RTC_CALR register. Specifically, the error over a period of time is measured to calculate the ppm value, which is then written to the calibration register. For example, a daily error of 2 seconds corresponds to approximately 23 ppm, so the corresponding calibration value is set in the CALR register. This feature is very practical and can improve the accuracy of ordinary crystal oscillators by a notch. In addition, attention should also be paid to the power supply for the RTC's backup domain. The RTC continues to run when the VBAT pin is connected to a coin cell battery or supercapacitor and the main power supply is cut off. I use a 0.1F supercapacitor, which, when fully charged, can keep the RTC running for over ten hours, which is sufficient for daily use. 4. Screen Driver and UI Design for Circular Screen Display of Watch Face 4.1 GC9A01 Initialization of Details Not Mentioned in the Manual GC9A

The initialization sequence for the 01 is quite long. The manual provides a set of general parameters, but in actual use, adjustments are still needed based on differences among screen manufacturers. There are two main pitfalls I have encountered: one is the color format, and the other is the display orientation. In terms of color format, the GC9A01 supports RGB565 and RGB666, with RGB565 being the default. However, for some batches of screens, the BGR bit of the MADCTL register was not set correctly at the factory, resulting in the red and blue colors being swapped. The watch face I initially displayed was blue, and it took me a long time to figure out that it was a problem with the BGR bit. The solution is to explicitly set the MADCTL register in the initialization sequence and set the BGR bit to 1 or clear it to 0. Try it once to see which one is correct. Regarding the display orientation, the round screen does not distinguish between "landscape" and "portrait," but the 12 o'clock position on the watch face needs to align with the actual wearing orientation. This involves the three bits MX, MY, and MV of MADCTL. My approach is to first turn on the screen to display an asymmetrical pattern, such as an arrow, and then rotate the screen to see where the arrow is pointing and adjust MADCTL until the arrow points upward. There are also several key parameters in the initialization sequence: frame rate control, power control, and gamma correction. I set the frame rate to 60Hz.

There is little benefit from increasing power consumption. The default value is sufficient for gamma correction, unless you have special requirements for color. 4.2 The watch face is rendered using DMA screen refresh to reduce CPU usage. A 240x240 RGB565 frame is 115,200 bytes. If the entire screen is refreshed, the SPI transmission time is approximately 23ms, assuming a clock speed of 40MHz. If the CPU is involved throughout this 23ms period, the power consumption will be very high. My approach is to use DMA to move the frame buffer to the SPI data register. The CPU is only responsible for preparing the data transfer and handing it over to DMA. After the transfer is complete, the DMA interrupt wakes up the CPU to prepare the next frame. I have enabled two frame buffers, one for the current display and one for rendering the next frame. After the rendering is complete, switch the pointer and the DMA transfers data from the new buffer. This way, rendering and transmission can overlap, making screen refreshes smoother. The content drawn on the watch face is divided into three layers: the background layer, which is a gradient or solid color; the scale layer, which has 12 scale points and numbers; and the hand layer, which has the hour hand, minute hand, and second hand. The background layer and the scale layer are static and are only redrawn when the watch face style is changed. The pointer layer is redrawn once per second. To reduce the area that needs to be redrawn, I only redraw the area where the hands pass, rather than refreshing the entire screen. Specifically, this is done by recording the position of the hand in the previous second and erasing it.

After the areas drawn twice by the old hand and the new hand are merged, only this area is refreshed. Here's a practical tip: Drawing the hands using the Bresenham line drawing algorithm is much faster than using the drawLine function in the graphics library. For the second hand, I used a 1-pixel-wide line. For the hour and minute hands, I used a 3-pixel-wide line, which looks more visually balanced. 4.3 Low-power refresh strategy: Partial refresh and screen-off. The watch's screen is a major power consumer. When the GC9A01 is fully lit, the current is around 20mA, with the backlight accounting for the majority. My low-power strategy is divided into three levels: fully lit, half-lit, and screen off. Full brightness is used during operation, with the backlight PWM duty cycle at 100%. Half-brightness is used for the standby watch face, with a duty cycle of 30%, which allows you to clearly see the time while saving power. The screen-off state is used when there is no operation for a long time. The backlight is turned off, the screen enters sleep mode, and the MCU enters Stop 2. After the screen is turned off, the RTC wakes up every second, but the screen does not refresh; only the time variable is updated. After a button press or wrist lift interrupt is triggered, the backlight is turned on first, then the screen is refreshed, and finally, the display switches to the bright screen state. In this way, the response time from screen off to screen on is within 100 ms, which feels essentially instantaneous. For the backlight PWM, I used TIM3's Channel 1 with an output frequency of 1 kHz and an adjustable duty cycle. If the frequency is too low, there will be flickering; if it is too high, there will be switching losses.

Greater than 1 kHz is a compromise. 5. Practical Power Consumption Optimization: From Milliamperes to Microamperes 5.1 Let the Measured Current Data for Each Mode Speak for Itself Power consumption optimization cannot rely on guesswork; it must be based on actual measurements. I used a multimeter and a current probe to measure the current data in each mode, as shown below. Mode Current Description Operating Mode Full Speed 12 mA 80 MHz Screen fully lit Sensor enabled Operating Mode Frequency Reduced 4 mA 16 MHz Screen half-lit Sensor intermittent Stop 2 RTC running 1.8 μA Screen off RAM2 retained Stop 2 RTC Accelerometer interrupt 3.5 μA Accelerometer low-power mode Standby Screen off MCU Stop 2 Approximately 25 μA, including screen sleep current and LDO quiescent current. From the data, the MCU's own Stop 2 current is very low, but the screen sleep current and LDO quiescent current together amount to about 20 μA. Therefore, if you want to further reduce power consumption, you need to start with the screen and the power supply chip. Later, I switched to an LDO with a lower quiescent current, the TPS7A02, with a quiescent current of 25 nA. The overall standby current dropped to around 8 μA. 5.2 Peripheral Clock Gating: Turn off when not in use. The STM32's peripheral clocks are enabled by default. If they are not needed, they must be turned off manually. After initialization,

After completion, all unused peripheral clocks are turned off, including ADC, DAC, USB, CAN, etc. The peripherals used should also have their clocks turned off as much as possible when not in use. For example, the heart rate sensor only turns on the I2C clock during measurement and turns it off after the measurement is completed. The handling of GPIOs also requires careful consideration. Unused GPIOs are configured as analog inputs to avoid leakage current caused by floating inputs. For the GPIOs that are used, configure the output pins as push-pull outputs according to the scenario, set the input pins as pull-up or pull-down, and set the interrupt pins as floating but enable the interrupts. There is a point that is easy to overlook: the debugging interface. If the SWD pins remain in debug mode during operation, there will be additional power consumption. My approach is to disable SWD in the official firmware and re-enable it through a specific key combination when debugging is required. After disabling SWD, the standby current can be reduced by another 1–2 μA. 5.3 Intermittent operation of sensors: Balancing the power consumption of heart rate and step counting. Heart rate and step counting are the two major power-consuming functions. The heart rate sensor MAX30102 consumes about 10 mA of current when operating, while the LIS3DH used for step counting consumes about 2 μA in low-power mode. Therefore, the strategy is clear: the step counter is always on, and the heart rate monitor is turned on as needed. For step counting, the LIS3DH is configured with a 10Hz sampling rate and a low-power mode that is woken up by an interrupt.

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

📮 需求咨询📮 Inquiry