1 module touch_led(
2 //input
3 input sys_clk, //时钟信号50Mhz
4 input sys_rst_n, //复位信号
5 input touch_key, //触摸按键
6
7 //output
8 output reg led //LED灯
9 );
10
11 //reg define
12 reg touch_key_d0;
13 reg touch_key_d1;
14
15 //wire define
16 wire touch_en;
17
18 //*****************************************************
19 //** main code
20 //*****************************************************
21
22 //捕获触摸按键端口的上升沿,得到一个时钟周期的脉冲信号
23 assign touch_en = (~touch_key_d1) & touch_key_d0;
24
25 //对触摸按键端口的数据延迟两个时钟周期
26 always @ (posedge sys_clk or negedge sys_rst_n) begin
27 if(!sys_rst_n) begin
28 touch_key_d0 <= 1'b0;
29 touch_key_d1 <= 1'b0;
30 end
31 else begin
32 touch_key_d0 <= touch_key;
33 touch_key_d1 <= touch_key_d0;
34 end
35 end
36
37 //根据触摸按键上升沿的脉冲信号切换led状态
38 always @ (posedge sys_clk or negedge sys_rst_n) begin
39 if (!sys_rst_n)
40 led <= 1'b1; //默认状态下,点亮LED
41 else begin
42 if (touch_en)
43 led <= ~led;
44 end
45 end
46
47 endmodule
第23行至35代码为一个经典的边沿检测电路,通过检测touch_key的上升沿来捕获按键按下的信号,一旦检测到按键按下,输出一个时钟周期的脉冲touch_en。每当检测到touch_en为高电平,led取反一次。
为了验证我们的程序,我们在modelsim内对代码进行仿真。
Test bench模块代码如下:
1 module touch_led(
2 //input
3 input sys_clk, //时钟信号50Mhz
4 input sys_rst_n, //复位信号
5 input touch_key, //触摸按键
6
7 //output
8 output reg led //LED灯
9 );
10
11 //reg define
12 reg touch_key_d0;
13 reg touch_key_d1;
14
15 //wire define
16 wire touch_en;
17
18 //*****************************************************
19 //** main code
20 //*****************************************************
21
22 //捕获触摸按键端口的上升沿,得到一个时钟周期的脉冲信号
23 assign touch_en = (~touch_key_d1) & touch_key_d0;
24
25 //对触摸按键端口的数据延迟两个时钟周期
26 always @ (posedge sys_clk or negedge sys_rst_n) begin
27 if(!sys_rst_n) begin
28 touch_key_d0 <= 1'b0;
29 touch_key_d1 <= 1'b0;
30 end
31 else begin
32 touch_key_d0 <= touch_key;
33 touch_key_d1 <= touch_key_d0;
34 end
35 end
36
37 //根据触摸按键上升沿的脉冲信号切换led状态
38 always @ (posedge sys_clk or negedge sys_rst_n) begin
39 if (!sys_rst_n)
40 led <= 1'b1; //默认状态下,点亮LED
41 else begin
42 if (touch_en)
43 led <= ~led;
44 end
45 end
46
47 endmodule
第23行至35代码为一个经典的边沿检测电路,通过检测touch_key的上升沿来捕获按键按下的信号,一旦检测到按键按下,输出一个时钟周期的脉冲touch_en。每当检测到touch_en为高电平,led取反一次。
为了验证我们的程序,我们在modelsim内对代码进行仿真。
Test bench模块代码如下: