FPGA——按键消抖常用模板代码

模板如下:

//`define UD #1
module key_jitter(
     input         clkin,
     
     input         key_in,
     output        key_value
  //   output [15:0] tout
);

// inner signal
reg [1:0] key_in_r;
wire pp;
reg [19:0] cnt_base;
reg key_value_r;

always @(posedge clkin)
    key_in_r<=  {key_in_r[0],key_in};

assign pp = key_in_r[0]^key_in_r[1]; 

always @(posedge clkin)
    if(pp==1'b1)
       cnt_base <=  20'd0;
    else
       cnt_base <=  cnt_base + 1;

always @(posedge clkin)
   if(cnt_base==20'hf_ffff)
        key_value_r <=  key_in_r[0];

assign key_value = key_value_r;
endmodule

使用时只需要将clkin替换成系统时钟,key_in替换成你要消抖的按键,再用key_value作为判断条件即可。


比如下面这个DA写入代码,为复位键(rst)消抖。在NL_SYNC置0的时候,写入NL_SDIN。

`timescale 1ns/1ns
`include "CLK_divide.v"

module AD5543_Nonlinear(clk,rst,NL_SCLK,NL_SDIN,NL_SYNC);
    input clk,rst;
    output NL_SCLK;
    output reg NL_SDIN,NL_SYNC;
    
    reg [1:0]NLcount;
    reg NLflag;
    wire [3:0]NL_SDIN_ALL;
    assign NL_SDIN_ALL  = 4'b0101;
    CLK_divide dvd1(clk,rst,NL_SCLK);
    
    reg [1:0] key_in_r;
wire pp;
reg [19:0] cnt_base;
reg key_value_r;
wire key_value;

//????
always @(posedge clk)
    key_in_r<=  {key_in_r[0],rst};

// ??????????
assign pp = key_in_r[0]^key_in_r[1]; 
//?????
always @(posedge clk)
    if(pp==1'b1)
       cnt_base <=  20'd0;
    else
       cnt_base <=  cnt_base + 1;

//??
always @(posedge clk)
   if(cnt_base==20'hf_ffff)
        key_value_r <=  key_in_r[0];

assign key_value = key_value_r;

    always @(posedge NL_SCLK or posedge key_value)           
    begin
        if(key_value) begin
            NL_SYNC <= 1; 
            NLcount <= 0; 
            NLflag  <= 0; 
            NL_SDIN <= 0;
        end
        else if(NLflag==0)begin  
            case(NLcount)
                4'b00: begin NL_SDIN = NL_SDIN_ALL[3] ; NLcount <= NLcount +1; NL_SYNC <= 0; end 
                4'b01: begin NL_SDIN = NL_SDIN_ALL[2] ; NLcount <= NLcount +1; NL_SYNC <= 0; end
                4'b10: begin NL_SDIN = NL_SDIN_ALL[1] ; NLcount <= NLcount +1; NL_SYNC <= 0; end
                4'b11: begin NL_SDIN = NL_SDIN_ALL[0]  ; NLcount <= 0;          NL_SYNC <= 0; NLflag<=1; end
                default: begin NL_SDIN = 0;              NLcount <= 0;          NL_SYNC <= 0; NLflag<=1; end
            endcase
        end
        else begin
            NL_SYNC <= 1; 
            NL_SDIN <= 0;
        end
    end
endmodule 

你可能感兴趣的:(Verilog)