Fix: fast presses are lost
A button counter misses presses when they come faster than the main loop. An easy embedded C problem (ISR-to-task patterns), run and graded in the browser.
easy · ISR-to-task patterns · find-the-bug · isr · semaphore
Bug report. A device counts button presses. The button interrupt runs press_isr, which is known to be correct. The main loop calls task_poll once per pass, and each call handles at most one press, because the loop has other work to do.
Pressing slowly works. Pressing three times quickly, while the loop is busy, counts only one press. Find the defect in task_poll and fix it by changing one line.
Starter code
bool task_poll(presses_t *p) {
if (p->pending == 0) return false;
p->pending = 0;
p->handled++;
return true;
}Example tests
Three quick presses, then five loop passes
presses_t p = {0};
press_isr(&p);
press_isr(&p);
press_isr(&p);
run_loop(&p, 5);Expected output:
handled 3, pending 0Learn it first
- ISR-to-task patterns · Deferring work out of interrupts with semaphores, queues and notifications.
More ISR-to-task patterns problems
- Deferred interrupt lines · Record interrupts in a pending mask and let the task handle them in priority order.
- Interrupt-safe byte queue · A single-producer, single-consumer queue with 8-bit free-running indices that must survive wrapping.