// debounce.sv // Push-button debouncer. The raw input is synchronised with two flip-flops, // then the output changes only after the synchronised input has differed // from the output for STABLE_CYCLES consecutive clock cycles. // Example: 10 ms at 100 MHz is STABLE_CYCLES = 1_000_000. module debounce #( parameter int STABLE_CYCLES = 1_000_000 ) ( input logic clk, input logic rst, // synchronous, active high input logic btn_raw, // asynchronous, bouncing input (active high) output logic btn // clean level, synchronous to clk ); localparam int W = (STABLE_CYCLES > 1) ? $clog2(STABLE_CYCLES) : 1; logic [1:0] sync; // two-flip-flop synchroniser logic [W-1:0] cnt; always_ff @(posedge clk) sync <= {sync[0], btn_raw}; always_ff @(posedge clk) begin if (rst) begin btn <= 1'b0; cnt <= '0; end else if (sync[1] == btn) begin cnt <= '0; // input agrees with output end else if (cnt == W'(STABLE_CYCLES - 1)) begin btn <= sync[1]; // stable long enough: accept cnt <= '0; end else begin cnt <= cnt + W'(1); end end endmodule