注:更多精彩请看:面试常问的verilog代码汇总 一文
简介
计数器的用处很多,比如在设计分频器时,需要用到计数器对每个时钟边沿进行计数,当记到某个数时,时钟翻转。同样在设计FIFO时,读写指针也需要没读或写一次,就需要讲计数器加1。下面我介绍一些简单的8位计数器的Verilog设计,仿真结果在文末。
8位计数器
计数器的设计如下:在每个时钟商上升沿到来时,计数器就加1。
module counter(clk,rstn,dout);input clk,rstn;output [7:0]dout;reg [7:0]dout;wire [7:0]sum;assign sum = dout + 1;//组合逻辑部分always@(posedge clk or negedge rstn) beginif(!rstn)begindout <= 0;endelse begindout <= sum;endend endmodule `timescale 1ns/1ps module TB;regclk,rstn;wire[7:0]dout;counter dut (.clk(clk), .rstn(rstn), .dout(dout));initial begin clk <= 0; forever begin #5 clk <= !clk; end #500 $finish;endinitial begin #10 rstn <= 0; repeat(10) @(posedge clk); rstn <= 1;end endmodule
123456789101112131415161718192021222324252627282930313233343536373839404142434445另外一种简单的写法就是:
等到它计数计到溢出(8’hff)时,还是会自动的返回到0开始重新计数。只不过当你不是讲计数器计满时,就需要设置注释部分,讲计数器的值归0。
module counter(clk,rstn,dout);input clk,rstn;output [7:0]dout;reg [7:0]dout;always@(posedge clk or negedge rstn) beginif(!rstn) begindout <= 0;end/*else if(dout == 8'hff) begindout <= 0;end*/else begindout <= dout + 1;endend endmodule
123456789101112131415161718192021