IO4: Reliable firmware: interrupts, RTOS tasks, watchdogs and safe state

Lesson 4 of 5 · reading 15–25 minutes; practice and project time is on the module page

Keeping state safe: RTC memory, flash and power cuts

🎯You'll be able to

Save state so it survives what it should, detect damaged state with a checksum, and write flash so a power cut can't corrupt it.

🏠The everyday picture

A shopkeeper writes each sale in a ledger. If the pen runs out halfway through a line, that line is crossed out, but every earlier line is still good. They never rub out yesterday's page to write today's.

📘What it really is

📝A worked example

Input: JalSetu's state: {"wakes": 312, "fail_count": 0, ...}.

Steps:

  1. Encode: JS1 + the JSON + CRC32 of the JSON, 4 bytes.
  2. On wake: if the first three bytes aren't JS1, or the CRC doesn't match, start from defaults and count a cold boot.
  3. Test: write garbage into RTC memory and check the firmware starts cleanly (Project 1's test 6).

Expected output: state that survives deep sleep and recovers safely from a power cut or corruption.

🌍Where it's used

📝Case scenario

A device saved its settings by overwriting one file. A power cut halfway through left a half-written file, and the device wouldn't start. Writing a new file and renaming it meant the old settings stayed until the new ones were complete.

🖱️Try it

Write down what JalSetu should do if it wakes and finds: no state; valid state; state with a wrong CRC. Success: three cases, none of which crash.

⚠️Common mistakes

🛠️For your project

Project 1's test 6 checks RTC state with JS1 and a CRC; Project 2's tests 1 and 2 check readings in flash survive power cuts.

✅Quick check

Why add a CRC to saved data?

Show the answer

To detect data damaged by a power cut or corruption, and fall back to safe defaults.

Why write a new file and then rename it?

Show the answer

The rename happens at once, so the old file stays intact until the new one is complete.

← PreviousWatchdogs and recovering by yourself
ProLearners Assist