触摸按键控制Led灯touch_ctrl_led
当触碰电容开关时小灯点亮,再次触碰小灯熄灭。
实验框图和波形图
边沿检测
边沿检测电路主要作用是在 clk 的驱使下,检测另一个信号的上升/下降沿电路
由于输入信号touch_key是随机输入不一定与时钟同步,设置变量touch_key_1用来同步时钟,将touch_key_1延迟一拍得到touch_key_2,再将两个信号相与得到touch_flag,led根据标志信号进行控制。
实验代码
module touch_ctrl_led
(
input wire sys_clk,
input wire sys_rst_n,
input wire touch_key,
output reg led
);
reg touch_key_1;
reg touch_key_2;
wire touch_flag;
//新知识:边沿检测:该案例中flag信号采集到了输入信号的下降沿
always@(posedge sys_clk or negedge sys_rst_n)
if(sys_rst_n==1'b0)
begin
touch_key_1<=1'b1;
touch_key_2<=1'b1;
end
else
begin
touch_key_1<=touch_key;
touch_key_2<=touch_key_1;
end
assign touch_flag=((touch_key_1==1'b0)&&(touch_key_2==1'b1)) ;//当同时满足时,即两个条件都为1,相与拉高电平
//这里使用assign组合逻辑电路,flag信号没有延时
always@(posedge sys_clk or negedge sys_rst_n)
if(sys_rst_n==1'b0)
led<=1'b1;
else if(touch_flag==1'b1)
led<=~led;
else led<=led;
endmodule
边沿采集也可以使用always
语句,不过会产生一个时钟的时延
always@(posedge sys_clk or negedge sys_rst_n)
if(sys_rst_n==1'b0)
touch_flag<=1'b0;
else if((touch_key_1==1'b0)&&(touch_key_2==1'b1))
touch_flag<=1'b1;
else touch_flag<=1'b0;
仿真代码
`timescale 1ns/1ns
module tb_touch_ctrl_led();
reg sys_clk;
reg sys_rst_n;
reg touch_key;
wire led;
initial
begin
sys_clk=1'b1;
sys_rst_n<=1'b0;
touch_key<=1'b1;
#20
sys_rst_n<=1'b1;
#200
touch_key<=1'b0;
#2000
touch_key<=1'b1;
#1000
touch_key<=1'b0;
#3000
touch_key<=1'b1;
end
always #10 sys_clk=~sys_clk;
touch_ctrl_led touch_ctrl_led_inst
(
. sys_clk(sys_clk),
. sys_rst_n(sys_rst_n),
. touch_key(touch_key),
. led(led)
);
endmodule