按键消抖

module key_debounce
#(parameter KEY_WIDTH = 4)
(
    input                   clk,
    input                   rst_n,
    input   [KEY_WIDTH:1]   i_key,
    output reg [KEY_WIDTH:1] key_out
);

reg [KEY_WIDTH:1] key_sample1,key_samp1_locked;

always @ (posedge clk,negedge rst_n)
begin
    if(!rst_n)
        key_sample1 <= {KEY_WIDTH{1'b1}};
    else
        key_sample1 <= i_key;
end 

always @ (posedge clk,negedge rst_n)
begin
    if(!rst_n)
        key_samp1_locked <= {KEY_WIDTH{1'b1}};
    else
        key_samp1_locked <= key_sample1;
end 

wire [KEY_WIDTH:1] key_changed1 = key_samp1_locked &(~key_sample1);

reg [19:0] cnt;

always @ (posedge clk,negedge rst_n)
begin
    if(!rst_n)
        cnt <= 20'b0;
    else if(key_changed1)
        cnt <= 20'b0;
    else
        cnt <= cnt + 1'b1;
end 

reg [KEY_WIDTH:1] key_samp2,key_samp2_locked;

always @ (posedge clk,negedge rst_n)
begin
    if(!rst_n)
        key_samp2 <= {KEY_WIDTH{1'b1}};
    else if(cnt == 20'hF_FFFF)
        key_samp2 <= i_key;
end 

always @ (posedge clk,negedge rst_n)
begin
    if(!rst_n)
        key_samp2_locked <= {KEY_WIDTH{1'b1}};
    else
        key_samp2_locked <= key_samp2;
end 

wire [KEY_WIDTH:1] key_changed2 =key_samp2_locked &(~key_samp2);

always @ (posedge clk,negedge rst_n)
begin
    if(!rst_n)
        key_out <= {KEY_WIDTH{1'b1}};
    else
        key_out <= ~key_changed2;
end

endmodule 

 

按键消抖_第1张图片

 

module key_debounce
( 
    input clk, 
    input rst_n,
    input data_in, 
    output keyctr 
);

reg [19:0] cnt;

always @ (posedge clk,negedge rst_n)
  if(!rst_n)
    cnt<=20'd0;
  else
    cnt<=cnt+1'b1;
    
reg low_sw;

always @ (posedge clk,negedge rst_n)
    if(!rst_n)
        low_sw<=1'b1;
    else if(cnt==20'hfffff)
        low_sw<=data_in;
        
reg low_sw_r;

always @(posedge clk,negedge rst_n)
    if(!rst_n)
        low_sw_r<=1'b1;
    else
        low_sw_r<=low_sw;
        
wire keyctr_r = low_sw_r & (~low_sw);

assign keyctr = keyctr_r;

endmodule 

 

按键消抖_第2张图片

原理图模块消抖电路,利用已经优化好了的LPM库,节省资源,建模速度快。

按键消抖_第3张图片

按键消抖_第4张图片

 

你可能感兴趣的:(按键消抖)