每隔10ms,让led灯的8个状态循环执行一次(每个状态的变化时间值小一点,即使8个状态运行完10ms还没到如每个状态变化为10us)
`timescale 1ns / 1ps
module cnt_led_6(
clk ,
rst_n,
ctrl,
TIME,
led
);
input clk;
input rst_n;
input [7:0] ctrl;
input [31:0] TIME;
output reg led;
parameter MCNT=500_000; //10ms
reg [26:0] cnt0;
reg EN;
reg [31:0] cnt1;
always @(posedge clk or negedge rst_n)begin
if(!rst_n)
cnt0<=0;
else if(cnt0==MCNT-1)
cnt0<=0;
else
cnt0 <= cnt0 +1;
end
always @(posedge clk or negedge rst_n)begin
if(!rst_n)
EN<=0;
else if (cnt0==0)
EN <= 1;
else if((cnt2==7)&&(cnt1==TIME-1))
EN <= 0;
end
always @(posedge clk or negedge rst_n)begin
if(!rst_n)
cnt1<=0;
else if (EN==1)begin
if(cnt1==TIME-1)
cnt1<=0;
else
cnt1 <= cnt1 +1;
end
end
reg [2:0] cnt2;
always @(posedge clk or negedge rst_n)begin
if(!rst_n)
cnt2<=0;
else if(EN==1)
if (cnt1==TIME-1)
cnt2<=cnt2+1;
end
always @(posedge clk or negedge rst_n) begin
if(!rst_n)
led<=0;
else case(cnt2)
0:led <=ctrl[0];
1:led <=ctrl[1];
2:led <=ctrl[2];
3:led <=ctrl[3];
4:led <=ctrl[4];
5:led <=ctrl[5];
6:led <=ctrl[6];
7:led <=ctrl[7];
default:led<=led;
endcase
end
endmodule
测试代码
module tb_cnt_led_6;
reg clk ;
reg rst_n ;
reg [7:0] ctrl ;
reg [31:0] TIME ;
wire led ;
cnt_led_6 uus(
.clk (clk ),
.rst_n (rst_n),
.ctrl (ctrl ),
.TIME (TIME ),
.led (led )
);
defparam uus.MCNT=500;
initial
clk=0;
always #20 clk=~clk;
initial begin
rst_n=0;
ctrl=8'b0000_0000;
TIME=0;
#200
rst_n=1;
TIME=10;
#2000;
ctrl=8'b1100_1010;
#2000;
ctrl=8'b1011_1100;
#2000000000;
$stop;
end
endmodule
仿真图