FPGA学习笔记之按键控制

时间:2022-04-13 15:07:50

参考:

【黑金原创教程】【FPGA那些事儿-驱动篇I 】实验二:按键模块① - 消抖

源码如下:

key_funcmod.v

 module key_funcmod(clk, rst, key, led, debug_led);

 input clk, rst, key;

 `define DEG

 `ifndef DEG
output reg [:] led;
`else
output [:] led;
`endif output reg debug_led; //`define DEBUG debug_led <= 1'b1; parameter T10MS='d500_000; reg F1, F2; always @(posedge clk or negedge rst)
begin
if (!rst)
{F2, F1} <= 'b11;
else
{F2, F1} <= {F1, key};
end wire isH2L;
wire isL2H; assign isH2L = (F2 == 'b1 && F1 == 1'b0);
assign isL2H = (F2 == 'b0 && F1 == 1'b1); reg[:] i;
reg[:] C1;
reg isPress, isRelease; always @(posedge clk or negedge rst)
begin
if (!rst)
begin
i <= 'd0;
{isPress, isRelease} <= 'b00;
C1 <= 'd0;
end
else
begin
case(i)
:
begin
if (isH2L)
i <= i + 'b1;
//`DEBUG
end
:
begin
if (C1 == T10MS) begin C1 <= 'd0; i <= i + 1'b1; end
else begin C1 <= C1 + 'b1; end
end
:
begin
isPress <= 'b1;
i <= i + 'b1;
end
:
begin
isPress <= 'b0;
i <= i + 'b1;
end
:
begin
if(isL2H)
i <= i + 'b1;
end
:
begin
if (C1 == T10MS) begin C1 <= 'd0; i <= i + 1'b1; end
else begin C1 <= C1 + 'b1; end
end
:
begin
isRelease <= 'b1;
i <= i + 'b1;
end
:
begin
isRelease <= 'b0;
i <= 'd0;
//`DEBUG
end
endcase
end
end reg[:] D1; always @(posedge clk or negedge rst)
begin
if (!rst)
`ifdef DEG
D1 <= 'b00;
`else
led <= 'b00;
`endif
else
if (isPress)
begin
`ifdef DEG
D1[] <= ~D1[];
`else
led[] <= ~led[];
`endif
//`DEBUG
end
else if (isRelease)
`ifdef DEG
D1[] <= ~D1[];
`else
led[] <= ~led[];
`endif
end `ifdef DEG
assign led = D1;
`endif endmodule

下载: http://files.cnblogs.com/files/pengdonglin137/key_demo1.zip

学到的知识:

1、Verilog下条件编译以及宏定义的使用;

2、一种调试方法:判断代码是不是执行到了,可以在关键位置加一个点灯的语句;

3、刚开始我把led设置为了 output reg [1:0] led,然后再最后assign led = D1,结果不管怎么按键,灯不亮。问题是:assign 语句后的led的类型应该是wire,而不应该是reg类型;

4、{isPress, isRelease} <= 2'b00; 其中, 不能写成 2'd11