module debounce ( input rst_i, input clk_i, input signal_i, output reg signal_o ); // number of rising clock edges a signal needs to be stable // for it to be output. // (+1 for propagation). parameter STABLE_PERIOD = 50; parameter INIT_SIG_STATE = 1'b1; reg [31:0] clk_counter; reg prev_state; always @(posedge clk_i or negedge rst_i) begin if (!rst_i) begin // Learning: I would like to set the output to the input on reset // but then I get // Warning: Async reset value `\signal_i' is not constant! // and a synthesis error. clk_counter <= 0; prev_state <= INIT_SIG_STATE; signal_o <= INIT_SIG_STATE; end else begin clk_counter <= clk_counter + 1; if (signal_i != prev_state) begin clk_counter <= 0; prev_state <= signal_i; end if (clk_counter === STABLE_PERIOD) begin signal_o <= signal_i; end end end // Learning? // Apparently, (and obviously, when you think about it), // it's not possible to drive a signal by two blocks // always @(signal_i) begin // if (signal_i != prev_state) begin // clk_counter <= 0; // prev_state <= signal_i; // end // end endmodule