/////////////////////
//www.hellofpga.com//
/////////////////////
`timescale 1ns / 1ps
module KEY_TEST(
    input CLK,
    input RSTn,
    output LED,
    input KEY
);

reg [1:0]debounce_mode=2'd0;
reg [19:0]debounce_count=20'd0;

reg [1:0]KEY_r=0;
always@(posedge CLK or negedge RSTn)begin
    if(!RSTn)begin
        KEY_r[1] <= 0;
        KEY_r[0] <= 0;
    end
    else begin
        KEY_r[1] <= KEY_r[0];
        KEY_r[0] <= KEY;
    end
end
wire KEY_NEGEDGE = (KEY_r[1] & ~KEY_r[0]) ? 1'b1 : 1'b0;

reg KEY_value = 0;
always@(posedge CLK or negedge RSTn)begin
    if(!RSTn)begin
        debounce_count <= 20'd0;
        debounce_mode <= 2'd0;
        KEY_value <= 0;
    end
    else if(debounce_mode == 0)begin
        debounce_count <= 20'd0;
        debounce_mode <= 2'd1;
        KEY_value <= 0;
    end
    else if(debounce_mode == 1)begin
        if(KEY_NEGEDGE == 1)begin
            debounce_count <= 20'd0;
            debounce_mode <= 2'd2;
        end
    end
    else if(debounce_mode == 2)begin
        if(debounce_count >= 20'd1_000_000) debounce_mode <= 2'd3;
        else begin
            if(KEY == 1) debounce_mode <= 2'd0;
            debounce_count <= debounce_count + 1'b1;
        end 
    end
    else begin
        if(KEY == 1) debounce_mode <= 2'd0;
        KEY_value <= 1'b1;
    end
end

assign LED = KEY_value;

endmodule