|
源代码如下:
module sw_debounce(
clk,rst_n,
sw0_n,sw1_n,sw2_n,sw3_n,
led_d2,led_d3,led_d4,led_d5
);
input clk; //主时钟信号,50MHz
input rst_n; //复位信号,低有效
input sw0_n,sw1_n,sw2_n,sw3_n; //三个独立按键,低表示按下
output led_d2,led_d3,led_d4,led_d5; //发光二极管,分别由按键控制
//---------------------------------------------------------------------------
reg[3:0] key_rst;
always @(posedge clk or negedge rst_n)
if (!rst_n) key_rst <= 4'b1111;
else key_rst <= {sw3_n,sw2_n,sw1_n,sw0_n};
reg[3:0] key_rst_r; //每个时钟周期的上升沿将low_sw信号锁存到low_sw_r中
always @ ( posedge clk or negedge rst_n )
if (!rst_n) key_rst_r <= 4'b1111;
else key_rst_r <= key_rst;
//当寄存器key_rst由1变为0时,led_an的值变为高,维持一个时钟周期
wire[3:0] key_an = key_rst_r & ( ~key_rst);
//---------------------------------------------------------------------------
reg[19:0] cnt; //计数寄存器
always @ (posedge clk or negedge rst_n)
if (!rst_n) cnt <= 20'd0; //异步复位
else if(key_an) cnt <=20'd0;
else cnt <= cnt + 1'b1;
reg[3:0] low_sw;
always @(posedge clk or negedge rst_n)
if (!rst_n) low_sw <= 4'b1111;
else if (cnt == 20'hfffff) //满20ms,将按键值锁存到寄存器low_sw中 cnt == 20'hfffff
low_sw <= {sw3_n,sw2_n,sw1_n,sw0_n};
//---------------------------------------------------------------------------
reg [3:0] low_sw_r; //每个时钟周期的上升沿将low_sw信号锁存到low_sw_r中
always @ ( posedge clk or negedge rst_n )
if (!rst_n) low_sw_r <= 4'b1111;
else low_sw_r <= low_sw;
//当寄存器low_sw由1变为0时,led_ctrl的值变为高,维持一个时钟周期
wire[3:0] led_ctrl = low_sw_r[3:0] & ( ~low_sw[3:0]);
reg d0;
reg d1;
reg d2;
reg d3;
always @ (posedge clk or negedge rst_n)
if (!rst_n) begin
d0 <= 1'b0;
d1 <= 1'b0;
d2 <= 1'b0;
d3 <= 1'b0;
end
else begin //某个按键值变化时,LED将做亮灭翻转
if ( led_ctrl[0] ) d0 <= ~d0;
if ( led_ctrl[1] ) d1 <= ~d1;
if ( led_ctrl[2] ) d2 <= ~d2;
if ( led_ctrl[3] ) d3 <= ~d3;
end
assign led_d2 = d0 ? 1'b1 : 1'b0;
assign led_d3 = d1 ? 1'b1 : 1'b0; //LED翻转输出
assign led_d4 = d2 ? 1'b1 : 1'b0;
assign led_d5 = d3 ? 1'b1 : 1'b0;
endmodule
就是这条语句
wire[3:0] key_an = key_rst_r & ( ~key_rst);
谢谢大家 |
阿莫论坛20周年了!感谢大家的支持与爱护!!
该献的血还是要献的。你不献他不献。难道让我去献? --- 出自坛友:lovejp1981
|