Smart lock: relock after 30 seconds
Relock automatically, with time arithmetic that survives the millisecond counter wrapping. A medium embedded C problem (Timing, interrupts and concurrency),…
medium · Timing, interrupts and concurrency · millis · rollover · product
Product: Smart lock (Smart home)
Requirement. After an unlock the bolt relocks by itself once the door is closed and at least 30 seconds have passed since the unlock. The lock runs for years, so its 32-bit millisecond counter wraps round every 49.7 days.
now and unlocked_at are counter values in milliseconds. Return whether to relock now.
Starter code
bool should_relock(uint32_t now, uint32_t unlocked_at, bool door_closed) {
return door_closed && now >= unlocked_at + 30000;
}Example tests
Waits for the time and the door
printf("%d %d %d\n", should_relock(40000, 5000, true), should_relock(20000, 5000, true), should_relock(40000, 5000, false));Expected output:
1 0 0Unlocked just before the counter wraps
printf("%d %d\n", should_relock(4294965000u, 4294960000u, true), should_relock(30000u, 4294960000u, true));Expected output:
0 1Learn it first
- Interrupts, timing and concurrency · How interrupts work on a Cortex-M, priorities, latency, races, rollover-safe time, non-blocking code and debouncing.
More Timing, interrupts and concurrency problems
- Elapsed time across rollover · Compute how many ticks have passed, even when the counter has wrapped.
- Rollover-safe timeout · Decide whether a timeout has expired without being fooled by wrap-around.
- Non-blocking blink · Derive an LED state from the current time instead of calling delay.
- Milliseconds to ticks · Convert a delay in milliseconds to RTOS ticks, rounding up.
- Debounce a button · Accept a new button state only after it has been stable for several samples.
- Periodic software timer · Fire once per period without drift and across counter rollover.
- Protect a shared variable · Make a read-modify-write safe from interrupts, and safe to nest.
- Cooperative scheduler · Run periodic tasks from a table, the core of a super-loop.
- Driver: measure worst-case time with the cycle counter · Enable the Cortex-M cycle counter and time a function across many runs, wraparound included.