Search code examples
verilogsystem-verilog

How do I loop states with clock signal?


I need en to loop between 4 specific given states: 4'b0111 , 4'b1011, 4'b1101, and 4'b1110

This is my code so far

// enable pin cycle
    always_ff @(posedge clk) en <=
       4'b0111 ? 4'b1011 : 
       4'b1011 ? 4'b1101 : 
       4'b1101 ? 4'b1110 :
       4'b1110 ? 4'b0111 : en;

From what I can tell, through the hardware, it passes the first stage onto 4'b1011 then stops entirely.

This is most likely caused by the fact that it is a conditional operator; however, from what I understand, it should still loop.

How can I get this working?

And if it's not possible, what's a better way of doing this loop?


Solution

  • The problem with your code is that you need to compare en against all those values.

    For example, you need to do something like:

    (en == 4'b0111) ? 4'b1011 :
    

    In your code, the first condition is (4'b0111), which is always true. So, en gets the value 4'b1011. en then remains at 4'b1011 on all subsequent clock edges because the first condition ((4'b0111)) always evaluates to true. No other condition is ever evaluated.

    You could continue to use the conditional operator, but I think the code would be a lot easier to understand using a case:

    always_ff @(posedge clk) begin
        case (en)
            4'b0111: en <= 4'b1011;
            4'b1011: en <= 4'b1101;
            4'b1101: en <= 4'b1110;
            4'b1110: en <= 4'b0111;       
            default: en <= 4'b0111;       
        endcase
    end