The mechanical toggle switch on FPGA board may have switch bouncing issue when toggled. When we attempt to toggle the switch, it may vibrate for a short period of time before settle at a state.

For example, when we change the switch from state 0 to state 1. The switch will alternate between 0 and 1 for a short period of time before it settled to become 1.

The input from the switch will look like following:

initial | after toggle to 1 ->
..00000 | 1001010110100 | 11111111111111...

As you can see, the middle section is the brief period where the switch bounces between 0 and 1. This could mess around with the function of our verilog code, especially for state machine.

Thus, we need to implement a debounce switch verilog module which take in the toggle switch as an input and output the corrected switch state.

When the switch is toggled, the module contains logic to ignore the middle section (alternating 1 & 0), and continue to output the initial sate (0 in this case). Only when the switch has settled to state 1 at the third section, the module will output state 1 which will flow into our verilog code logic.

Following is the code:

// iclk = clock input
// in_bit = input from toggle switch
// out_state = output that flows into program
module switchDebounce(iclk, in_bit, out_state);

    input iclk;
    input in_bit;
    output reg out_state; 
    reg current_bit;
    reg prev_bit;
    reg [15:0] count_bit_diff;
    always @(posedge iclk) begin
        // store current and previous input bit from switch 
        current_bit <= in_bit; 
        prev_bit <= current_bit;
        // if previous input bit is different from current 
        if(out_state != prev_bit) begin
            // increment the count
            count_bit_diff <= count_bit_diff + 1'b1;  
            // When count has reached 2^16 - 1, 
            // toggle the current state 
            if(count_bit_diff == 16'hffff) 
                out_state <= ~out_state;  
        else begin
            // reset count to 0 
            // when state equal to previous input bit
            count_bit_diff <= 0;

Switch bouncing issue is particularly obvious on older FPGA board, where there is more "friction" when toggling the switch. To test that the debounce module is working, an old FPGA board with "hard" and "friction" switch is ideal.

New FPGA board switch has less "friction" when toggling. It may not be able to reproduce the switch bouncing issue. Thus, it is not useful to test our switchDebounce module.

Thank you so much for reading!  😊 Feel free to follow us on twitter and like our fb page for more articles like this. 😉