// Verilog module for debouncing a switch // The clk signal should be tied to the 50 MHz clock on the DE2 board // The switch input would be tied to one of the switches or keys on the DE2 // the val output is the de-bounced version of the switch // author: janders; November 2009 module debounce(switch, val, clk); input switch; input clk; output reg val; reg [21:0] count; // 22 bits is ~4 million reg [1:0] state; reg w; reg z; always@(posedge clk) begin // this is the state machine to de-bounce the switch if (switch == 1'b1 && state == 2'b10) begin state = 2'b10; val = 1'b1; end else if (switch == 1'b0 && state == 2'b10) state = 2'b01; else if (state == 2'b01 && w == 1'b0) begin z = 1'b1; state = 2'b01; end else if (state == 2'b01 && w == 1'b1) begin state = 2'b00; end else if (state == 2'b00 && switch == 1'b1) begin z = 1'b0; state = 2'b10; end else if (state == 2'b00 && switch == 1'b0) begin z = 1'b0; state = 2'b00; val = 1'b0; end end always@(posedge clk) begin // this is the timer used by the state machine if (z == 1'b1) begin count = count + 1'b1; if (count == 22'h3FFFFF) begin w = 1'b1; end else w = 1'b0; end end endmodule