(1)设计定义:设计一个按键消抖模块,实现消除按键机械抖动的影响, 并实现以下功能:
- 按下S1,LED1、LED8点亮,否则熄灭
- 按下S2,LED2、LED7点亮,否则熄灭
- 按下S3,LED3、LED6点亮,否则熄灭
- 按下S4,LED4、LED5点亮,否则熄灭
(2)代码设计:
1.首先是20ms的计数器,一般来说,机械抖动的时间不会超过20ms。
2.状态机的定义和设计
//状态机定义
always@(posedge clk or negedge reset_n)
if(!reset_n)begin
state <= IDLE;
en_cnt <= 1'd0;
end
else begin
case(state)
IDLE:begin
if(key_in == 1'd0)begin
state <= PRESS;
en_cnt <= 1'd1;
end
else begin
state <= state;
en_cnt <= 1'd0;
end
end
PRESS:begin
if(cnt == MCNT - 20'd1 && key_in == 1'd0)begin
state <= DOWN;
en_cnt <= 1'd0;
end
else if(key_in == 1'd1)begin
state <= IDLE;
en_cnt <= 1'd0;
end
else begin
state <= state;
en_cnt <= en_cnt;
end
end
DOWN:begin
if(key_in == 1'd1)begin
state <= REPRESS;
en_cnt <= 1'd1;
end
else begin
state <= state;
en_cnt <= 1'd0;
end
end
REPRESS:begin
if(cnt == MCNT - 20'd1 && key_in == 1'd1)begin
state <= IDLE;
en_cnt <= 1'd0;
end
else if(key_in == 1'd0)begin
state <= DOWN;
en_cnt <= 1'd0;
end
else begin
state <= state;
en_cnt <= en_cnt;
end
end
default:begin
state <= IDLE;
en_cnt <= 1'd0;
end
endcase
end
附上顶层文件:
module key_filter_top
(
input wire clk ,
input wire reset_n ,
input wire [3:0] key_in , //{S4,S3,S2,S1}
output wire [7:0] LED
);
key_filter key_filter_inst0
(
.clk (clk ),
.reset_n (reset_n ),
.key_in (key_in[0]),
.key_out (),
.LED1 (LED[0]),
.LED2 (LED[7])
);
key_filter key_filter_inst1
(
.clk (clk ),
.reset_n (reset_n ),
.key_in (key_in[1]),
.key_out (),
.LED1 (LED[1]),
.LED2 (LED[6])
);
key_filter key_filter_inst2
(
.clk (clk ),
.reset_n (reset_n ),
.key_in (key_in[2]),
.key_out (),
.LED1 (LED[2]),
.LED2 (LED[5])
);
key_filter key_filter_inst3
(
.clk (clk ),
.reset_n (reset_n ),
.key_in (key_in[3]),
.key_out (),
.LED1 (LED[3]),
.LED2 (LED[4])
);
endmodule
(3)实验现象:
- 按下S1
- 按下S2
- 按下S4
- 同时按下S2,S3
- 同时按下S1、S4