1 //让LED灯按照指定的亮灭模式亮灭,亮灭模式未知,由用户随机指定。以0.25秒为一个变换
2 //周期,8个周期为一个循环。8*0.25=2,2s➗20ns=100 000 000
3 源代码
4 module counter_led_3(
5 clk,
6 reset_n,
7 ctrl,
8 led
9 );
10 input clk;
11 input reset_n;
12 input [7:0] ctrl;
13 output reg led;
14 parameter MCNT=100 000 000;
15 reg [25:0] counter;
16 always@(posedge clk or negedge reset_n)
17 if(!reset_n)
18 counter<=0;
19 else if(counter==MCNT-1)
20 counter<=0;
21 else
22 counter<=counter+1'b1;
23 // always@(posedge clk or negedge reset_n)//这种是为了方便理解,实际用下面那一种写法。
24 // if(!reset_n)
25 // led<=0;
26 // else if(counter==MCNT/8-1)
27 // led<=ctrl[0];
28 // else if(counter==MCNT*2/8-1)
29 // led<=ctrl[1];
30 // else if(counter==MCNT*3/8-1)
31 // led<=ctrl[2];
32 // else if(counter==MCNT*4/8-1)
33 // led<=ctrl[3];
34 // else if(counter==MCNT*5/8-1)
35 // led<=ctrl[4];
36 // else if(counter==MCNT*6/8-1)
37 // led<=ctrl[5];
38 // else if(counter==MCNT*7/8-1)
39 // led<=ctrl[6];
40 // else if(counter==MCNT-1)
41 // led<=ctrl[7];
42 always@(posedge clk or negedge reset_n)
43 if(!reset_n)
44 led<=0;
45 else case(counter)
46 MCNT*1/8-1:led<=ctrl[0];
47 MCNT*2/8-1:led<=ctrl[1];
48 MCNT*3/8-1:led<=ctrl[2];
49 MCNT*4/8-1:led<=ctrl[3];
50 MCNT*5/8-1:led<=ctrl[4];
51 MCNT*6/8-1:led<=ctrl[5];
52 MCNT*7/8-1:led<=ctrl[6];
53 MCNT*8/8-1:led<=ctrl[7];
54 default led<=led;
55 endcase
56 endmodule
57 仿真代码
58 `timescale 1ns/1ns
59 module counter_led_3_tb();
60 reg clk;
61 reg reset_n;
62 reg [7:0] ctrl;
63 wire led;
64 defparam counter_led_3_inst0.MCNT=100000;
65 counter_led_3 counter_led_3_inst0(
66 .clk(clk),
67 .reset_n(reset_n),
68 .ctrl(ctrl),
69 .led(led)
70 );
71 initial clk=1;
72 always #10 clk=!clk;
73
74 initial begin
75 reset_n=0;
76 ctrl=0;
77
78 #201;
79 ctrl=8'b1101_0110;
80 reset_n=1;
81 #2000000000;
82 $stop;
83 end
84
85 endmodule
86