ESP32 stack overflow in a task

A FreeRTOS task used more stack than it was given. ESP-IDF catches it in a few ways, each with its own message, and the fix is the same: find how much the task really needs.

Guru Meditation Error: Core  0 panic'ed (Unhandled debug exception).
Debug exception reason: Stack canary watchpoint triggered (sensor)

or, from FreeRTOS's own check:

***ERROR*** A stack overflow in task sensor has been detected.

On RISC-V chips the watchpoint shows up as Guru Meditation Error: Core 0 panic'ed (Breakpoint), and chips with a hardware stack guard report Stack protection fault.

What it means

The name in the message is the task that overflowed. ESP-IDF watches the last 32 bytes of the running task's stack and FreeRTOS checks a canary at its end; when either is touched, the task has used (almost) all of its stack. A stack overflow that skips past both does not get caught this way and shows up later as LoadProhibited, InstrFetchProhibited or a corrupt heap.

The usual causes

Size it instead of guessing

uxTaskGetStackHighWaterMark(NULL) called from the task returns how much of its stack has never been used. Run the task through its heaviest path, read the number, and leave a margin. In Arduino, the loop() task has 8 KB by default; SET_LOOP_TASK_STACK_SIZE(16 * 1024); at the top of the sketch raises it.

Pinscope reports every task's free stack over time, so a task slowly running out shows up before it crashes: heap and stack monitoring.

When it happens in the field

On your desk the crash prints to the serial monitor. On a device in someone else's building it prints to a port nobody is reading, the chip restarts, and all you hear is that it "sometimes hangs". Pinscope keeps the panic reason and backtrace across the restart, sends them on the next connection and decodes them with the ELF of the build that crashed, so you get the function and line without anyone at the device. Free for three devices. How crash reporting from the field works.

Related errors: CORRUPT HEAP · InstrFetchProhibited · LoadProhibited · Task watchdog got triggered. All ESP32 errors: the list. Messages and causes from ESP-IDF's panic handler and Espressif's Fatal Errors guide.

More