1 //每隔10ms,让led灯的一个8状态循环执行一次(每个变化时间值小一点,方便测试比如设置为10us)
2 源代码
3 module counter_led_6(
4 clk,
5 reset_n,
6 Time,
7 ctrl,
8 led
9 );
10 input clk;
11 input reset_n;
12 input [31:0] Time;
13 input [7:0] ctrl;
14 output reg led;
15 reg [31:0] counter;
16 reg EN;
17 //10ms定时器
18 reg [18:0] counter0;
19 always@(posedge clk or negedge reset_n)
20 if(!reset_n)
21 counter0<=0;
22 else if(counter0==500000-1)
23 counter0<=0;
24 else
25 counter0<=counter0+1'b1;
26
27 //产生EN
28
29
30 always@(posedge clk or negedge reset_n)
31 if(!reset_n)
32 EN<=0;
33 else if(counter0==0)
34 EN<=1;
35 else if((counter2==7)&&(counter==Time-1))
36 EN<=0;
37
38 //输入时间间隔
39 always@(posedge clk or negedge reset_n)
40 if(!reset_n)
41 counter<=0;
42 else if(EN)begin
43 if(counter==Time-1)
44 counter<=0;
45 else
46 counter<=counter+1'b1;
47 end
48 else
49 counter<=0;
50 reg [2:0] counter2;
51 always@(posedge clk or negedge reset_n)
52 if(!reset_n)
53 counter2<=0;
54 else if(EN)begin
55 if(counter==Time-1)
56 counter2<=counter2+1'b1;
57 end
58 else
59 counter2<=0;
60
61 always@(posedge clk or negedge reset_n)
62 if(!reset_n)
63 led<=0;
64 else case(counter2)
65 0:led<=ctrl[0];
66 1:led<=ctrl[1];
67 2:led<=ctrl[2];
68 3:led<=ctrl[3];
69 4:led<=ctrl[4];
70 5:led<=ctrl[5];
71 6:led<=ctrl[6];
72 7:led<=ctrl[7];
73 default:led<=led;
74 endcase
75 endmodule
76 仿真代码
77 `timescale 1ns/1ns
78 module counter_led_6_tb();
79 reg clk;
80 reg reset_n;
81 reg [31:0] Time;
82 reg [7:0] ctrl;
83 wire led;
84
85 counter_led_6 counter_led_6_inst0(
86 .clk(clk),
87 .reset_n(reset_n),
88 .ctrl(ctrl),
89 .Time(Time),
90 .led(led)
91 );
92 initial clk=1;
93 always #10 clk=!clk;
94
95 initial begin
96 reset_n=0;
97 ctrl=0;
98 Time=0;
99
100 #201;
101 reset_n=1;
102 #2000;
103 Time=2500;
104 ctrl=8'b1000_0110;
105
106
107 #2000000000;
108 $stop;
109 end
110
111 endmodule