Capstone · #17 of 48
Firmware Architecture
Task Loop, State Machine, Error Budget
Why it matters
Good firmware architecture makes code maintainable, testable, and reliable. A clear state machine prevents bugs.
The idea
State Machine
The capstone has clear states:
- INIT: Setup GPIO, I²C, Wi‑Fi
- READ_SENSOR: Read temperature/humidity
- CONNECT_WIFI: Establish Wi‑Fi connection
- TRANSMIT: Send data to server
- SLEEP: Enter deep sleep, wait for wake
Error Handling
Every operation can fail:
- Sensor read fails → retry (with limit), then sleep
- Wi‑Fi connect fails → retry (with limit), then sleep
- Transmit fails → retry (with limit), then sleep
- Error budget: Max retries before giving up
Task Loop
Main loop structure:
- Restore state from RTC memory
- Read sensor (with retries)
- Connect Wi‑Fi (with timeout)
- Transmit data (with retries)
- Save state to RTC memory
- Enter deep sleep
Power Optimization
Minimize active time:
- Turn off Wi‑Fi when not needed
- Use fast I²C speed (400kHz)
- Batch operations (read all sensor data at once)
- Enter sleep immediately after transmit
Demo
Firmware architecture is code structure, not visual. Review this before writing the capstone code.
Key takeaways
- Use a state machine to organize firmware logic
- Every operation can fail — implement error handling
- Error budget: max retries before giving up
- Minimize active time to save power
Going deeper
For production firmware, use an RTOS (Real-Time Operating System) like FreeRTOS for task scheduling. For simple projects, a state machine in the main loop is sufficient. Always implement watchdog timers to recover from hangs. Use structured logging (not just print statements) for debugging.
Math details
Timing budget (5-minute cycle):
Sensor read: ~100ms
Wi‑Fi connect: ~2s (first time), ~500ms (reconnect)
Transmit: ~200ms
Sleep entry: ~50ms
Total active: ~3s (worst case)
Error budget:
Max retries per operation: 3
Total max active time: ~10s (if all retries fail)
Still acceptable for 5-minute cycle
Power impact:
Normal cycle: 80mA × 3s = 240mAs
Error cycle: 80mA × 10s = 800mAs
Impact: ~3× power consumption (acceptable for rare errors)
Implementation
LLM Prompt: Firmware State Machine
Write Rust code for ESP32 firmware state machine.
States: Init, ReadSensor, ConnectWifi, Transmit, Sleep.
Include: error handling with retry limits, RTC memory for state,
watchdog timer, structured logging. Use esp-hal and esp-wifi crates.
Lab Exercise
- Design state machine diagram (states, transitions, errors)
- Implement state enum and transition logic
- Add error handling with retry limits
- Test each state transition — verify error recovery
- Measure timing for each operation — verify power budget
Mastery