/********************************************************************
* Module Name : key_debounce
* Engineer : wan xin
* Target Device : EP2C35F672C8
* Tool versions : Quartus II 7.0
* Revision : W1.0
//说明:当三个独立按键的某一个被按下后,相应的LED被点亮;
// 再次按下后,LED熄灭,按键控制LED亮灭
*********************************************************************/
module key_debounce(clock,key,dout,rst_n);
input clock; //系统时钟(50MHz)
input rst_n;
input [2:0] key; //按键输入(KEY1~KEY3)
output [2:0] dout;
//内部寄存器
reg[17:0]count; //时钟分频计数器
reg [2:0] dout1,dout2,dout3; //消抖寄存器
reg [2:0] buff; //边沿检测寄存器
reg [2:0] d;
wire div_clk; //分频时钟
wire [2:0] key_edge;
assign dout =d;
//时钟分频部分
always @(posedge clock or negedge rst_n)
begin
if(!rst_n)
count<=18'd0;
else begin
if (div_clk)
count <= 18'd0;
else
count <= count + 1'b1;
end
end
assign div_clk = (count > 18'd250000);//5ms
//按键消抖部分
always @(posedge clock or negedge rst_n)
begin
if(!rst_n)
{dout1,dout2,dout3}<=9'b111_111_111;
else begin
dout1 <= key;
dout2 <= dout1;
dout3 <= dout2;
end
end
//按键边沿检测部分
always @(posedge clock or negedge rst_n)
begin
if(!rst_n)
buff <=3'b111;
else
buff <= dout1 | dout2 | dout3;
end
assign key_edge = ~(dout1 | dout2 | dout3) & buff;//延时15毫秒(3个时钟)后边沿检测从0变为1
always @(posedge clock or negedge rst_n) //上升沿检测
begin
if (!rst_n) begin
d[0] <= 1'b0;
d[1]<= 1'b0;
d[2]<= 1'b0;
end
else begin
if(key_edge[0]) d[0]<=~d[0];
if(key_edge[1]) d[1]<=~d[1];
if(key_edge[2]) d[2]<=~d[2] ;
end
end
endmodule
按键部分的延时时间和按键数大家可以灵活更改!
用户416031 2012-6-28 11:18
不错哦