|
module example3(clk_50MHz,rst_n,Led,Key);
input clk_50MHz;
input rst_n;
input [2:0] Key;
reg [3:0] KeyLast;
output [7:0] Led;
reg [7:0] Led;
reg [23:0] count1;
reg [23:0] count2;
reg Led_on ;
reg Led_dir ;
//--------------------------------------------------
always@(posedge clk_50MHz or posedge rst_n)
begin
if(rst_n)
count1 <= 'd0;
else
count1 <= count1 + 'd1;
end
always@(posedge clk_50MHz or posedge rst_n)
begin
if(rst_n)
Led <= 'b00000000;
else if(count1 == 'hFFFFFF && Led_on)
if(Led == 'b00000000)
Led <= 'b00000001;
else
if(Led_dir == 'b1)
Led <= {Led[6:0],Led[7]};
else
Led <= {Led[0],Led[7:1]};
end
//--------------------------------------------------
always@(count2 or rst_n)
begin
if(rst_n)
begin
Led_on <= 'b1;
Led_dir <= 'b0;
KeyLast <= Key;
end
else if(count2 == 'd5000000)
begin
KeyLast <= Key;
if(KeyLast != 'b000)
begin
if(KeyLast[0] == 'b1)
Led_on <= ~Led_on;
else if(KeyLast[1] == 'b1)
Led_dir <= 'b1;
else if(KeyLast[2] == 'b1)
Led_dir <= 'b0;
end
end
end
always@(posedge clk_50MHz or posedge rst_n)
begin
if(rst_n)
count2 <= 'd0;
else
if(KeyLast != Key && count2 <= 'd5000000)
count2 <= count2 + 'd1;
else
count2 <= 'd0;
end
endmodule
将跑马灯和按键去抖相结合。这次是按键按下去就改变状态,所以判断了一下KeyLast的值。
存在2个问题
1 按下KEY1 如果时间很短的话,可能跑马灯的方向发生了2次改变,即反向只跑了一个灯,就又按原来的顺序跑了
2 按下KEY0,从运行到停止立刻相应,从停止到启动需要一个时间才能启动。
估计这2个问题也可能都涉及到按键去抖部分,也就是这部分可能有问题。需要先分析去抖。