一、原理
环形计数器,0001→0010→0100→1000→0001
二、代码
//环形计数器
module ring_counter#(parameter word_size=4)(
input clk,
input rst_n,
input enable,
output reg [word_size-1:0]count
);
always@(posedge clk,negedge rst_n)
if(!rst_n)
count<={{(word_size-1){1'b0}},1'b1}; // 0001
else if(enable==1'b1)
count<={count[word_size-2:0],count[word_size-1]};
//在使能后,来一个时钟上升沿,则把低3位移到高,把高位移到低
// 0001 0010 0100 1000 0001 ...
endmodule
异步置位 ,rst_n=0时,则D触发器的Q端是 0001 ,即 count = 4'b0001 。
同步使能,即有使能信号也还不行,还要有时钟上升沿,在enable=1 之后的第一个上升沿才会进行环形计数
三、测试代码
module ring_counter_tst #(parameter word_size=4)();
reg clk;
reg rst_n;
reg enable;
wire [word_size-1:0]count;
ring_counter U_ring_counter(
.clk(clk),
.rst_n(rst_n),
.enable(enable),
.count(count)
);
initial
begin
clk=0;
rst_n=0;
enable=0;
#20;
rst_n=1;
#20;
enable=1;
end
always #10 clk=~clk;
endmodule