fpga4fun.comwhere FPGAs are fun

Counters 2 - Modulus counters

A modulus counter is a binary counter that rolls back before its natural end value. For example, let's say you want a modulus 10 counter (counts from 0 to 9), you can write this.

reg [3:0] cnt = 0;  // we need 4 bits to be able to reach the value 9

always @(posedge clk)
if(cnt==9)
    cnt <= 0;
else
    cnt <= cnt+1;
or this (a little more compact)
reg [3:0] cnt = 0;
always @(posedge clk) cnt <= (cnt==9) ? 0 : cnt+1;

Now a little of (free) optimization is available if you realize that we don't actually need to compare all the 4 bits of the counter to 9. The code below uses only bit 0 and bit 3 in the comparison.

always @(posedge clk) cnt <= ((cnt & 9)==9) ? 0 : cnt+1;