Switch Debouncer

Medium

Problem Statement

Mechanical switches and buttons physically "bounce" — producing several spurious transitions over a few milliseconds before settling to their final value. Design a digital debouncer that filters this noise out. Ports: - `clk` — input, 1 bit, clock - `rst` — input, 1 bit, synchronous active-high reset - `btn_in` — input, 1 bit, the raw, potentially noisy/bouncing input signal, sampled once per clock cycle - `btn_out` — output, 1 bit, registered, the clean debounced output To keep this problem's timing simulation-friendly, use a debounce window of exactly **4 consecutive clock cycles** (in a real design this window is normally implemented with a much larger counter clocked at a slow tick, but the underlying mechanism is identical). On every rising edge of `clk`: 1. If `rst` is high, `btn_out` synchronously clears to 0, and any in-progress debounce counting is also cleared. Reset overrides everything else. 2. Otherwise, compare the current `btn_in` to the current `btn_out`: - If `btn_in` already equals `btn_out` (the input agrees with the currently accepted, stable output), the internal debounce counter resets to 0 — there is no pending change. - If `btn_in` differs from `btn_out`, the internal debounce counter increments by 1 on this edge — *unless* this increment would be the **4th consecutive cycle** of disagreement, in which case `btn_out` instead updates to the new value of `btn_in` on this very edge, and the counter resets to 0. In other words: `btn_out` only changes after `btn_in` has disagreed with it for 4 consecutive clock cycles in a row. If `btn_in` flips back to match `btn_out` at any point before reaching the 4th consecutive disagreeing cycle, the counter resets and no change to `btn_out` occurs — exactly the behavior needed to reject short noise glitches while still tracking a genuine, sustained button press or release.

Verilog