Counter that loops through 6 values and then resets

Viewed 43

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
2 Answers

Use another if/else to check if count is 5, then set it to 0:

reg [2:0] count;

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

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
Related