计数器的Verilog实现(时序逻辑)

//计数器
//led每500ms状态翻转一次
//系统时钟为50m,对应周期为20ns,
//500ms=500_000_000ns(ms μs ns) /20  =  25_000_000次 
module counter(clk50m, rst_n, led_out);    

    input clk50m;    //系统时钟 50M
    input rst_n;    //全局复位,n表示低电平复位
    
    output reg led_out;    //led输出
    
    reg [24:0]cnt;        //定义计数器寄存器
    
    //时序逻辑常用写法,以时钟上升沿和复位下降沿为敏感信号
    //计数进程
    always@(posedge clk50m or negedge rst_n) 
    if(rst_n == 1'b0)
        cnt <= 25'd0;
    else if (cnt == 25'd24_999_999)
        cnt <= 25'd0;
    else 
        cnt <= cnt + 1'b1;
        
    //led输出进程控制
    always@(posedge clk50m or negedge rst_n)
    if(rst_n == 1'b0)
        led_out <=1'b1;
    else if (cnt == 25'd24_999_999)
        led_out <= ~led_out;        //按位取反0-1  1-0
    
endmodule
`timescale 1ns/1ns
`define clock_period 20        //宏定义一个时钟参数20ns,方便更改代码时钟参数
module counter_tb;
    
    //两个激励信号源
    reg clk1;
    reg rst_n1;
    
    wire led_out1;

    counter u1(
    .clk50m(clk1), 
    .rst_n(rst_n1), 
    .led_out(led_out1)
    );
    
    initial clk1 = 1;
    
    //代码中时钟为20ns,这里延时半个周期是为了凑整个周期的信号变化
    always #(`clock_period/2) clk1 = ~clk1;    //调用宏定义的参数
    
    initial begin
        rst_n1 = 1'b0;
        #(`clock_period * 200);
        rst_n1 = 1'b1;
        #2000_000_000    //延时2s
        $stop;
    end
    
endmodule

电路视图:

原文地址:https://www.cnblogs.com/wjwjs/p/15230619.html