Watchdog reload value
Turn a timeout in milliseconds into the reload count of a prescaled watchdog clock. An easy embedded C problem (Watchdogs), run and graded in the browser.
easy · Watchdogs · watchdog · timers · arithmetic
A watchdog counts down from a 12-bit reload value (1 to 4095) on its own clock, divided by a prescaler:
reload = timeout_ms * clock_hz / (prescaler * 1000)
Write wdt_reload(timeout_ms, clock_hz, prescaler). Round down. If the result is 0 (too short to measure) or above 4095 (does not fit), return 0 so the caller knows the timeout cannot be set.
Starter code
uint16_t wdt_reload(uint32_t timeout_ms, uint32_t clock_hz, uint32_t prescaler) {
return (uint16_t)(timeout_ms * clock_hz / (prescaler * 1000u));
}Example tests
One second from a 32 kHz clock
show(wdt_reload(1000, 32000, 16));Expected output:
2000Too long does not fit
show(wdt_reload(10000, 32000, 16));Expected output:
0Learn it first
- Watchdog timer · Independent and windowed watchdogs, and feeding them correctly.
More Watchdogs problems
- Kick only when everyone is alive · Feed the watchdog only if every required task has checked in since the last kick.
- Greenhouse: report why it restarted · Read the reset-cause flags and report the one that matters.