Asia/Kolkata
Posts

Dual-Core FreeRTOS Task Pinning and NVS Wear-Leveling on ESP32

November 22, 2026

Why One loop() Breaks Real-Time Builds

An ESP32 often has to juggle two jobs at once. It runs a fast hardware loop, like an MPPT PWM tracker or a meter counter, while also pushing data over Wi-Fi. Putting both jobs inside Arduino's single loop() causes timing jitter. A TLS handshake or Wi-Fi drop can stall the CPU for hundreds of milliseconds. That gap is long enough to miss ripple samples or trip a relay late. In both my Smart Prepaid Energy Meter and Adaptive MPPT builds, I split tasks across both Xtensa cores and gated NVS flash writes. That fixed both timing jitter and flash wear.

1. Pin Hardware and Network Tasks to Different Cores

On ESP32, the Wi-Fi and TCP/IP stack runs on Core 0 by default. Your own code often runs on Core 1. Any core that handles network traffic will face sudden pauses from radio interrupts. Keep fast ADC and PWM loops on Core 1, and push MQTT or HTTP work onto Core 0. Pass data between them with a portMUX_TYPE lock or a FreeRTOS queue so neither task stalls the other. Use vTaskDelayUntil() instead of delay(). It locks the loop to a steady 50 ms pace even when task work takes a few extra microseconds.

2. Save Your NVS Flash From Early Wear

ESP32 NOR flash pages last for roughly 10,000 to 100,000 write cycles. Saving a meter balance to Preferences (NVS) once per second means 86,400 writes a day. Even with NVS page rotation, that pace burns through a flash sector in weeks or months.

Step A: Write Only After Real Change

Keep the live balance in RAM. Write to NVS only when energy drops by a set step, such as 0.1 Wh or 1 Wh, or right after a user tops up credit.

Step B: Flush on Power Loss

To avoid losing that last 0.1 Wh when mains power cuts out, watch the raw DC rail ahead of your main bulk cap with a simple divider and a GPIO pin: A 470 µF to 1000 µF cap on the 5 V rail keeps the chip alive for tens of milliseconds after AC drops. That gives you plenty of time to save one clean NVS entry before brownout reset.