Search code examples
verilogcounterclock

Counter that loops through 6 values and then resets


This is a counter that loops through only 6 values over and over again (0, 1, 2, 3, 4, 5, 0, 1, ...). The counter should include a “reset” signal that will cause the counter value to reset to 0 when reset goes high (asynchronous reset), and the counter value should increment on the rising edge of clock.

Here is the code I have. But, how would I make it reset once it reaches the number 5?

always @(posedge CLOCK_50 or negedge reset_n) begin
           if (!reset_n)
               count <= 0;
           else if (enable)
               count <= count + 1;
end

Solution

  • simply use

    always @(posedge CLOCK_50 or negedge reset_n) begin
        if (!reset_n)
            count <= 0;
        else if (enable)
            count <= (count == 5)? 'd0 : count + 1;
    end
    

    or split comb and seq

    assign count_next = (count == 5)? 0 : count + 1;
    always @(posedge CLOCK_50 or negedge reset_n) begin
        if (!reset_n)
            count <= 0;
        else if (enable)
            count <= count_next;
    end