← all lessons
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:

Error Handling

Every operation can fail:

Task Loop

Main loop structure:

  1. Restore state from RTC memory
  2. Read sensor (with retries)
  3. Connect Wi‑Fi (with timeout)
  4. Transmit data (with retries)
  5. Save state to RTC memory
  6. Enter deep sleep

Power Optimization

Minimize active time:

Demo

Firmware architecture is code structure, not visual. Review this before writing the capstone code.

Key takeaways

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

  1. Design state machine diagram (states, transitions, errors)
  2. Implement state enum and transition logic
  3. Add error handling with retry limits
  4. Test each state transition — verify error recovery
  5. Measure timing for each operation — verify power budget

full glossary →