以触摸按键驱动led为例
RTL代码:
module touch_led(
input sys_clk,
input sys_rst,
input touch_key,
output reg led
);
reg touch_key_d0;
reg touch_en;
// edge detect
always @(posedge sys_clk or negedge sys_rst) begin
if (!sys_rst)
touch_key_d0 <= 1'd0;
else begin
touch_key_d0 <= touch_key; // delay one clk
touch_en <= (~touch_key_d0) & touch_key;
end
end
// led control
always @(posedge sys_clk or negedge sys_rst) begin
if (!sys_rst)
led <= 1'd1;
else begin
if (touch_en)
led <= ~ led;
end
end
endmodule
Testbench:
`timescale 1ns/1ns
module touch_led_tb();
reg sys_clk;
reg sys_rst;
reg touch_key;
reg touch_key_d0;
reg touch_en;
wire led;
parameter T = 10;
always #T sys_clk = ~ sys_clk;
initial begin
sys_rst <= 1'b0;
sys_clk <= 1'b0;
touch_key <= 1'b0;
# 20 sys_rst <= 1'b1;
# 10 touch_key <= 1'b1;
# 30 touch_key <= 1'b0;
# 110 touch_key <= 1'b1;
# 30 touch_key <= 1'b0;
end
touch_led u1(
sys_clk,
sys_rst,
touch_key,
led
);
endmodule
仿真时序分析:
检测到触摸按键的上升沿后两个时钟周期,led将被激活