//控制一个led灯 4状态闪烁
module led_run4_en(
clk,
control,
reset_n,
led
);
input clk;
input [3:0]control;
input reset_n;
output reg led;
reg [18:0]counter1;
reg [1:0]counter2;
reg [14:0]counter3;
reg en;
//10ms的定时器
always@(posedge clk or negedge reset_n)begin
if(reset_n==0)
counter1<=0;
else if(counter1==19’d500000-1’b1)
counter1<=0;
else
counter1<=counter1+1’b1;
end
//状态机en的上升和下降沿的判断
always@(posedge clk or negedge reset_n)begin
if(reset_n==0)
en<=0;
else if(counter1==0)
en<=1;
else if((counter2==3)&&(counter3==15’d31250-1’b1))
en<=0;
end
//0.625ms的定时器
always@(posedge clk or negedge reset_n)begin
if(reset_n==0)
counter3<=0;
else if(en==1)begin
if(counter3==15’d31250-1’b1)
counter3<=0;
else
counter3<=counter3+1’b1;
end
else counter3<=0;
end
//0.625ms的定时器的个数的计数器
always@(posedge clk or negedge reset_n)begin
if(reset_n==0)
counter2<=0;
else if(en==1)begin
if(counter2==2’d3)
counter2<=0;
else if(counter3==15’d31250-1’b1)
counter2<=counter2+1’b1;
end
else counter2<=0;
end
//led闪烁模块
always@(posedge clk or negedge reset_n)begin
if(reset_n==0)
led<=0;
else if(en==1)begin
case(counter2)
2’d0:led<=control[0];
2’d1:led<=control[1];
2’d2:led<=control[3];
2’d3:led<=control[4];
endcase
end
else
led<=0;
end
endmodule
counter2进程计数器的值几乎都为0,所以变量en不满足counter2==3这个条件,就跳变不到0.
//0.625ms的定时器的个数的计数器
always@(posedge clk or negedge reset_n)begin
if(reset_n==0)
counter2<=0;
else if(en==1)begin
if(counter2==2’d3)
counter2<=0;
else if(counter3==15’d31250-1’b1)
counter2<=counter2+1’b1;
end
//else counter2<=0; //这个语句会使counter2+1后下一个上升沿执行。
end