Medium · Counters & Timers · Sequential Logic
Mechanical switches "bounce": for a short time after being pressed or released, the contact opens and closes rapidly. A debouncer filters this out. Its output only follows the input once the input has held a new value for long enough.
Design a debouncer whose output changes only after the input has been sampled at the new value on N consecutive rising edges.
| Parameter | Default | Meaning |
|---|---|---|
N | 4 | Number of consecutive samples required, 1 <= N <= 255. Your design must work for every value in this range: the hidden tests also use non-default values, including the smallest and the largest. |
| Port | Dir | Width | Meaning |
|---|---|---|---|
clk | input | 1 | Clock. |
rst | input | 1 | Synchronous, active-high reset (takes effect only at a rising edge of clk). |
din | input | 1 | Noisy input (already synchronized to clk), sampled at every rising edge. |
dout | output | 1 | Debounced output (registered). |
The debouncer keeps a count c of how many consecutive samples have differed from the current dout. At every rising edge:
rst = 1: dout <= 0 and c <= 0. (The sample taken at a reset edge never counts.)din == dout: c <= 0 (any sample equal to dout restarts the count).din != dout): the count increases. If this is the N-th consecutivediffering sample, dout takes the value of din at this edge, and the count restarts from 0 (the next samples are compared against the new dout).
So if din changes and then stays stable, with its first new-value sample at edge k, dout changes at edge k + N − 1 and is visible in the cycle after that edge. With N = 1, dout is simply din delayed by one register.
N = 4)| edge | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
rst | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
din sampled | 0 | 1 | 1 | 0 (bounce) | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 |
| count after the edge | 0 | 1 | 2 | 0 | 1 | 2 | 3 | 0 | 0 | 1 | 2 | 3 | 0 |
dout after the edge | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
Sign up free to solve Switch Debouncer in your browser.