Simvik

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 0

Learn it first

More ISR-to-task patterns problems