Switch Debouncer

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.

Parameters

ParameterDefaultMeaning
N4Number 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.

Ports

PortDirWidthMeaning
clkinput1Clock.
rstinput1Synchronous, active-high reset (takes effect only at a rising edge of clk).
dininput1Noisy input (already synchronized to clk), sampled at every rising edge.
doutoutput1Debounced output (registered).

Behavior

The debouncer keeps a count c of how many consecutive samples have differed from the current dout. At every rising edge:

  1. If rst = 1: dout <= 0 and c <= 0. (The sample taken at a reset edge never counts.)
  2. Else if din == dout: c <= 0 (any sample equal to dout restarts the count).
  3. Else (din != dout): the count increases. If this is the N-th consecutive

differing 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.

Example (N = 4)

edge0123456789101112
rst1000000000000
din sampled0110 (bounce)111110000
count after the edge0120123001230
dout after the edge0000000111110

Sign up free to solve Switch Debouncer in your browser.

More Counters & Timers problems