状态机按键消抖(学习笔记)
状态转移图:
module key_filter(
Clk,
Reset_n,
Key,
// Key_P_Flag,
// Key_R_Flag,
Key_Flag,
Key_state
);
input Clk;
input Reset_n;
input Key;
// output reg Key_P_Flag;
// output reg Key_R_Flag;
output Key_Flag;
output reg Key_state;
reg Key_P_Flag;
reg Key_R_Flag;
assign Key_Flag = Key_P_Flag | Key_P_Flag;
reg [1:0] r_Key;
always@(posedge Clk)
r_Key <= {r_Key[0],Key};
// always@(posedge Clk)begin
// r_Key[0] <= Key;
// r_Key[1] <= r_Key[0];
// end
//上升沿下降沿
wire pedge_key;
assign pedge_key = r_Key == 2'b01;
wire nedge_key;
assign nedge_key = r_Key == 2'b10;
reg [19:0] cnt;
reg [1:0] state;
always@(posedge Clk or negedge Reset_n)
if(!Reset_n)begin
state <= 0;
Key_R_Flag <= 1'b0;
Key_P_Flag <= 1'b0;
cnt <= 0;
Key_state <= 1;
end
else begin
case(state)
0:
begin
Key_R_Flag <= 1'b0;
if(nedge_key)
state<=1;
else
state<=0;
end
1:
if( (pedge_key)&&(cnt < 1000000-1))
state<=0;
else if(cnt >= 1000000-1)begin
state<=2;
cnt <= 0;
Key_P_Flag <= 1;
Key_state <=0;
end
else begin
cnt <= cnt + 1'b1;
state<=1;
end
2:
begin
Key_P_Flag <= 0;
if(pedge_key)
state <= 3;
else
state <= 2;
end
3:
if((nedge_key)&&(cnt<1000000-1))
state<=2;
else if(cnt>=1000000-1)begin
state<=0;
cnt <= 0;
Key_R_Flag <= 1'b1;
Key_state<=1;
end
else begin
cnt <= cnt +1'b1;
state <=3;
end
endcase
end
endmodule
`timescale 1ns / 1ns
//
module key_filter_tb();
reg Clk;
reg Reset_n;
reg Key;
// wire Key_P_Flag;
// wire Key_R_Flag;
wire Key_Flag;
wire Key_state;
key_filter key_filter(
Clk,
Reset_n,
Key,
// Key_P_Flag,
// Key_R_Flag,
Key_Flag,
Key_state
);
initial Clk = 1;
always#10 Clk = ~Clk;
initial begin
Reset_n = 0;
Key = 1;
#201;
Reset_n = 1;
#3000;
Key = 0;
#20000;
Key = 1;
#30000;
Key = 0;
#20000;
Key = 1;
#30000;
Key = 0;
#20000;
Key = 1;
#30000;
Key = 0;
#20000;
Key = 1;
#30000;
Key = 0;
#50000000;
Key = 1;
#30000;
Key = 0;
#20000;
Key = 1;
#30000;
Key = 0;
#20000;
Key = 1;
#500000000;
Key = 0;
#20000;
Key = 1;
#30000;
Key = 0;
#20000;
Key = 1;
#30000;
Key = 0;
#20000;
Key = 1;
#30000;
Key = 0;
#20000;
Key = 1;
#30000;
Key = 0;
#50000000;
Key = 1;
#30000;
Key = 0;
#20000;
Key = 1;
#30000;
Key = 0;
#20000;
Key = 1;
#500000000;
$stop;
end
endmodule