0
0
Verilogprogramming~5 mins

Modulo-N counter in Verilog

Choose your learning style9 modes available
Introduction

A modulo-N counter counts from 0 up to N-1 and then starts over at 0. It helps keep track of cycles or events in a fixed range.

To count clock pulses up to a certain number and then reset.
To create a timer that repeats every N cycles.
To cycle through states in a finite state machine with N states.
To divide a clock frequency by N in digital circuits.
Syntax
Verilog
module modulo_n_counter #(parameter N = 4) (
    input wire clk,
    input wire reset,
    output reg [$clog2(N)-1:0] count
);

    always @(posedge clk or posedge reset) begin
        if (reset) begin
            count <= 0;
        end else if (count == N-1) begin
            count <= 0;
        end else begin
            count <= count + 1;
        end
    end

endmodule

N is the maximum count value (modulus).

$clog2(N) calculates the number of bits needed to represent N-1.

Examples
This counts from 0 to 3 (mod 4) using 2 bits.
Verilog
module modulo_4_counter (
    input wire clk,
    input wire reset,
    output reg [1:0] count
);

    always @(posedge clk or posedge reset) begin
        if (reset) count <= 0;
        else if (count == 3) count <= 0;
        else count <= count + 1;
    end

endmodule
This counts from 0 to 9 (mod 10) using 4 bits.
Verilog
module modulo_10_counter (
    input wire clk,
    input wire reset,
    output reg [3:0] count
);

    always @(posedge clk or posedge reset) begin
        if (reset) count <= 0;
        else if (count == 9) count <= 0;
        else count <= count + 1;
    end

endmodule
Sample Program

This testbench runs a modulo-5 counter. It toggles the clock every 5 time units and resets the counter at start. The counter counts from 0 to 4 repeatedly.

Verilog
module testbench();
    reg clk = 0;
    reg reset = 1;
    wire [2:0] count;

    // Instantiate modulo-5 counter
    modulo_n_counter #(.N(5)) counter (
        .clk(clk),
        .reset(reset),
        .count(count)
    );

    // Clock generation
    always #5 clk = ~clk;

    initial begin
        $monitor($time, " ns: count = %d", count);
        #10 reset = 0;
        #100 $finish;
    end
endmodule

module modulo_n_counter #(parameter N = 5) (
    input wire clk,
    input wire reset,
    output reg [$clog2(N)-1:0] count
);

    always @(posedge clk or posedge reset) begin
        if (reset) count <= 0;
        else if (count == N-1) count <= 0;
        else count <= count + 1;
    end
endmodule
OutputSuccess
Important Notes

Use $clog2(N) to automatically size the counter bits.

Resetting the counter ensures it starts from zero.

The counter resets to zero after reaching N-1.

Summary

A modulo-N counter counts from 0 to N-1 and then restarts at 0.

It is useful for repeating cycles or dividing frequencies.

Use always @(posedge clk or posedge reset) to update the count safely.