Skip to content
Tactiverge

△ Embedded systems · state and counters

Debounce a noisy button

Clean up a bouncing push-button signal so one press counts as one press.

  • Level 2 · Builder
  • 5 tests
  • 🐞 debug variant
  • technically checked

Your task

When a mechanical button closes, its contacts bounce for a few milliseconds, so the input flickers between 0 and 1. Firmware debounces it: the output only changes after the input has disagreed with it for stable samples in a row.

Write debounce(samples, stable) that returns an array the same length as samples:

  • Start with state = 0 and a counter = 0.
  • For each sample: if it differs from state, add 1 to the counter, and when the counter reaches stable, switch state and reset the counter. If it equals state, reset the counter to 0.
  • Push the state after handling each sample.

Hints (0 of 3 shown)

    What gets checked

    • debounce([0, 1, 0, 1, 1, 1, 0, 0], 3) → [0, 0, 0, 0, 0, 1, 1, 1]
    • debounce([1, 1, 1, 1], 2) → [0, 1, 1, 1]

    Plus 3 hidden tests for edge cases. They run in the sandbox like the others; only the result is shown.

    Tab indents · Esc then Tab leaves the editor · Ctrl/⌘ Enter runs · Ctrl/⌘ Shift Enter checks · Ctrl/⌘ / comments

    Starting the sandbox…

    Press Run to see what your program prints.

    Your code runs only in this browser, inside an isolated sandbox with no network access, and stops after 3 s. Nothing you type is sent to Tactiverge; drafts and progress are saved in this browser only.