timeverilogdelayfsmstate-machine

How to implement time delay into Verilog FSM


always @(posedge clock)
    case(state)
        `STATE0: begin
            state <= `STATE1;
            // Code here
            // Wait 5ms before advancing 
        end
        `STATE1: begin 
            state <= `STATE2;
            // Code here
            // Wait 5ns before advancing 
        end
        `STATE2: begin 
            state <= `STATE0;
            // Code here
            // Wait 5s before advancing 
        end
        default:begin
            state <= `STATE0;
            // Code here
        end
    endcase
end

Is it possible to add wait statements into the design where it must wait x amount of time units before it can proceed to the next state? I know it can be manually done in my testbench using # but my design requires that there needs to be a certain wait time before I can proceed.


Solution

  • For short delays (a few clock cycles), it might be easiest to implement a few "dummy" states as intermediaries between the intended states.

    For longer delays, use a counter as the enable signal to transfer between the states:

    reg [31:0] count;
    always@(posedge clock)
        if (SOME RESET) count <=0;
        else count <= count + 1;
    
    always @(posedge clock)
    //...
       STATE_N: if (count == SOME_NUMBER_OF_CYCLES) state <= STATE_NPLUSONE;
                else state <= STATE_N;