Every embedded product eventually needs to run on batteries. The difference between firmware that drains a CR2032 in a week and firmware that runs for a year comes down to understanding sleep modes, wakeup sources, and peripheral power management. In this final lesson you will build a data logger that spends 99.9% of its time asleep, waking briefly to read a sensor, write to SPI flash, and go back to sleep. You will also learn the production firmware essentials: flash programming, option bytes, read protection, and bootloader basics. #STM32 #LowPower #Production
What We Are Building
Battery-Powered Data Logger
A self-contained data logger powered by a CR2032 coin cell (3V, ~220 mAh). The STM32 sleeps in Stop mode between measurements. Every 60 seconds, the RTC alarm wakes the MCU. It reads the BME280 sensor over I2C, writes the timestamped data to a W25Q SPI flash chip, and returns to Stop mode. A serial command (via UART wakeup) lets you dump all logged data to a terminal for retrieval. The target is at least 6 months of operation on a single CR2032.
Project specifications:
Parameter
Value
Board
Blue Pill (STM32F103C8T6)
Power source
CR2032 coin cell (3V, ~220 mAh)
Sleep mode
Stop mode (1.4 uA typical, RTC running)
Wakeup source
RTC Alarm A, every 60 seconds
Sensor
BME280 on I2C1 (forced mode, then sleep)
Storage
W25Q32 SPI flash (4 MB, ~330,000 log entries)
Log entry size
12 bytes (timestamp + temp + pressure + humidity)
Serial interface
USART1 for data retrieval (wakeup on RX activity)
Target battery life
6+ months on CR2032
Bill of Materials
Component
Quantity
Notes
Blue Pill (STM32F103C8T6)
1
From previous lessons
ST-Link V2 clone
1
For programming (disconnect for battery operation)
CR2032 battery holder
1
Through-hole or SMD
CR2032 coin cell
1
3V lithium, ~220 mAh
W25Q32 SPI flash module
1
4 MB, 3.3V compatible
BME280 breakout
1
From Lesson 5
Breadboard + jumper wires
1 set
From previous lessons
STM32 Low-Power Modes
The data logger’s operating cycle consists of brief active periods separated by long Stop mode sleep intervals. This duty-cycling strategy is what makes months of battery life possible.
The STM32F103 offers three low-power modes with different tradeoffs between power consumption and wakeup time. Choosing the right mode depends on how often you need to wake up and how fast the MCU must respond after waking. For a data logger that wakes every 60 seconds, Stop mode provides the best balance: very low current consumption with all SRAM and register contents preserved.
Mode Comparison
Mode
Current (typical)
Wakeup Time
RAM Preserved
Peripherals
Wakeup Sources
Sleep
~2 mA
Immediate
Yes
All running
Any interrupt
Stop
~1.4 uA
~5 us
Yes
Stopped (RTC runs)
EXTI, RTC alarm
Standby
~1.7 uA
~50 us (reset)
No (lost)
All off (RTC optional)
WKUP pin, RTC, IWDG
Why Stop Mode
SRAM preserved: All variables, peripheral configurations, and the stack survive sleep. After wakeup, execution continues from the WFI instruction. No need to reinitialize everything.
RTC keeps running: The LSE crystal (32.768 kHz) powers the RTC during Stop mode. RTC alarms can wake the MCU at precise intervals.
Fast wakeup: The MCU wakes in microseconds and resumes execution. Compare this to Standby mode, which triggers a full reset.
Low enough: 1.4 uA is sufficient for months of CR2032 operation.
Power Budget Calculation
Sleep current: 1.4 uA (Stop mode)
Active current: ~15 mA for ~50 ms (sensor read + flash write)
Wakeup interval: 60 seconds
Average current = (1.4 uA * 59.95 s + 15 mA * 0.05 s) / 60 s
= (83.93 uAs + 750 uAs) / 60 s
= 833.93 uAs / 60 s
= ~13.9 uA average
CR2032 capacity: 220 mAh = 220,000 uAh
Battery life: 220,000 uAh / 13.9 uA = ~15,827 hours = ~1.8 years
Even with real-world inefficiencies (voltage regulator quiescent current, flash leakage, self-discharge), 6+ months is achievable.
RTC Configuration and Alarm Wakeup
The RTC runs from the 32.768 kHz LSE crystal even during Stop mode. The RTC alarm wakes the CPU by triggering EXTI line 17, which is one of the few interrupt sources active in Stop mode.
The RTC on the STM32F103 is a simple 32-bit counter clocked by the LSE oscillator (32.768 kHz). It has a prescaler that divides 32768 Hz down to 1 Hz, incrementing the counter every second. The RTC alarm register triggers an interrupt when the counter matches the alarm value. During Stop mode, the RTC continues running on LSE power, which draws only a few hundred nanoamps.
PWR->CR|= PWR_CR_LPDS; /* Low-power regulator in Stop */
/* Clear wakeup flag */
PWR->CR|= PWR_CR_CWUF;
/* Enter Stop mode (WFI = Wait For Interrupt) */
__WFI();
/* Execution resumes here after RTC alarm wakes us */
/* Reconfigure clock (HSE + PLL, since Stop mode reverts to HSI) */
clock_init();
/* Clear deep sleep bit */
SCB->SCR&=~SCB_SCR_SLEEPDEEP_Msk;
}
W25Q SPI Flash Driver
The W25Q flash stores log entries sequentially. When a sector boundary is reached, the firmware erases the next 4 KB sector before writing. The write pointer wraps around to the beginning when the end of flash is reached.
The W25Q32 is a 32 Mbit (4 MB) SPI NOR flash memory. It supports standard SPI at up to 104 MHz clock speed. Flash memory has a write constraint: you can only change bits from 1 to 0 by writing. To change bits from 0 to 1, you must erase an entire sector (4 KB). For data logging, you write sequentially through the flash, erasing sectors ahead of the write pointer when needed. The W25Q also has a power-down mode that reduces standby current from ~1 uA to ~0.1 uA.
Flash Commands
Command
Opcode
Description
Write Enable
0x06
Must precede every write/erase
Page Program
0x02
Write up to 256 bytes
Read Data
0x03
Read any number of bytes
Sector Erase (4KB)
0x20
Erase 4096-byte sector
Read Status Reg 1
0x05
Check busy flag (bit 0)
Power Down
0xB9
Enter low-power mode
Release Power Down
0xAB
Wake from power-down
Read JEDEC ID
0x9F
Manufacturer and device ID
Driver Implementation
#defineW25Q_CS_LOW() GPIOA->BRR= (1<<4)
#defineW25Q_CS_HIGH() GPIOA->BSRR= (1<<4)
voidw25q_write_enable(void) {
W25Q_CS_LOW();
spi1_transfer(0x06);
W25Q_CS_HIGH();
}
voidw25q_wait_busy(void) {
W25Q_CS_LOW();
spi1_transfer(0x05);
while (spi1_transfer(0xFF)&0x01); /* Wait until BUSY clears */
W25Q_CS_HIGH();
}
voidw25q_sector_erase(uint32_taddr) {
w25q_write_enable();
W25Q_CS_LOW();
spi1_transfer(0x20);
spi1_transfer((addr >>16) &0xFF);
spi1_transfer((addr >>8) &0xFF);
spi1_transfer(addr &0xFF);
W25Q_CS_HIGH();
w25q_wait_busy(); /* Sector erase takes 30-400 ms */
The STM32F103 option bytes control read protection, write protection, watchdog configuration, and boot settings. They are stored in a special area of flash at address 0x1FFF_F800. Modifying option bytes requires unlocking the flash, erasing the option byte area, and writing new values. The most important option byte for production is read protection (RDP), which prevents the firmware from being read out through SWD.
/* Enable read protection (Level 1) */
voidenable_read_protection(void) {
/* WARNING: This prevents SWD readout of flash.
* Reverting to Level 0 erases all flash contents. */
FLASH->CR|= FLASH_CR_OPTPG; /* Option byte program */
/* Write RDP key for Level 1 (any value except 0xA5) */
*(volatileuint16_t*)0x1FFFF800=0x00FF;
while (FLASH->SR& FLASH_SR_BSY);
FLASH->CR&=~FLASH_CR_OPTPG;
}
Bootloader Basics
The STM32F103 has a built-in system bootloader in ROM that supports UART firmware updates. By pulling Boot0 high and resetting, the MCU enters bootloader mode and accepts new firmware over USART1. For production, you might want a custom bootloader that lives in the first few KB of flash, verifies firmware integrity (CRC check), and jumps to the application. This lets you update firmware in the field without an ST-Link.
/* Jump to system bootloader from application code */
The Blue Pill board has components that draw current even when the MCU is asleep: the power LED (~2 mA), the 3.3V voltage regulator quiescent current (~5 mA for the AMS1117), and the USB pull-up resistor. For true low-power operation, you need to either desolder the power LED and regulator (powering the MCU directly from the CR2032 at 3V) or use a custom PCB with a low-quiescent-current LDO like the MCP1700 (~1.6 uA).
Component
Current Draw
Action
AMS1117 regulator
~5 mA quiescent
Replace with MCP1700 or power MCU directly
Power LED
~2 mA
Desolder or cut trace
USB pull-up (R10)
~2 mA when USB connected
Disconnect USB for battery operation
STM32 in Stop mode
~1.4 uA
Already optimized
What You Have Learned
Lesson 9 Complete
Low-power design:
STM32 Sleep, Stop, and Standby modes with current consumption and tradeoffs
RTC alarm configuration for periodic wakeup from Stop mode
Power budget calculation for battery life estimation
Peripheral clock and GPIO management for minimum leakage
Flash storage:
W25Q SPI flash commands (read, write, erase, power down)
Sequential write strategy with sector erase for data logging
Write pointer storage in backup registers (survives sleep)
Data retrieval over serial as CSV
Production firmware:
Flash and option byte programming
Read protection (RDP) to prevent firmware extraction
System bootloader access for field firmware updates
Production checklist for reliable deployed firmware
Brown-out detection and battery voltage monitoring
Course summary:
Over nine lessons you have built a complete STM32 skill set: from toolchain setup and bare-register GPIO to FreeRTOS multitasking and battery-powered production firmware. Every peripheral on the Blue Pill has been exercised, debugged, and understood at the register level. These foundations transfer directly to any STM32 family (F4, L4, H7) and to other ARM Cortex-M microcontrollers.
Comments
Loading comments...
Predict first
A logger is awake for 50 ms in each minute and draws 15 mA. For the rest of the minute it sleeps and draws 14 µA, about 1000 times less. Which part uses more of the battery?
See it: where the battery goes
Average current
Life of a 220 mAh cell
Share used while asleep
The bar is the charge used in one cycle: the part used while asleep and the part used in the 50 ms awake at 15 mA. The awake part is the same at every setting. In a real Standby design it would be longer, because the chip starts again from reset at each wake.
Check yourself
Three questions. Each wrong choice is a mistake people really make, so read the note after you answer.
1. The customer wants a reading every 10 seconds, not every 60. Nothing else changes: 14 µA in Stop mode, 15 mA for 50 ms at each reading, a 220 mAh cell. With 60 seconds the calculated life was about 11 months. What is it now?
2. A student loads the logger program on a Blue Pill board as it comes from the shop and powers it from a new 220 mAh battery. The log is correct, but the battery is empty after about 30 hours. What is the most likely cause?
3. A program sets its UART for 115,200 baud with the 72 MHz clock, then enters Stop mode. After the wake, the programmer forgets to set up the clock again and sends a line of text. What does a terminal set to 115,200 baud show?
Watch it build: asleep for 60 s, then awake
In Stop the main clocks are off. The RTC keeps counting on its own 32.768 kHz crystal, the LSE.
32768 Hz / 32768 = 1 Hz: CNT rises once a second. CNT = ALR signals EXTI line 17.
The RTC is write-protected: set DBP to unlock it and CNF to change it.
First the alarm: CNT 120, so ALR = 120 + 60 = 180. Then the sensor and the flash sleep.
SLEEPDEEP = 1 and PDDS = 0 choose Stop, not Standby. At __WFI() the chip draws about 14 µA.
CNT reaches 180: EXTI 17 wakes the chip on the 8 MHz HSI. clock_init() returns it to 72 MHz.
Found this useful?
Discussion
No comments yet. Questions, results from your own build, a better way to explain it: all welcome.
Text size
←→
Previous and next card. On a turned card: Not yet, I knew it
SpaceEnter
Turn the card, show the answer
123
Overview, Recap, Test me
HomeEnd
First and last card
Esc
Close
← → or scroll · N notes · F full screen · B blank0:00
My notes on this page
Kept on this device only. Nothing is sent anywhere.
Tip: select words in the lesson, or tap a figure or an equation, to put a note right there.
Notes on earlier wording
The lesson has changed and these words are no longer in it. Your notes are kept, with the words you chose.
Comments