Skip navigation.
Home

State Machine

SystemVerilog provides a few enhancements to Verilog 2001 that can be utilized when coding a state machine. The following example uses the always_ff, always_comb, and unique case keywords that can help reduce simulation and synthesis mismatches. Also the enum construct is used to create the state labels. This example state machine just outputs the state number that it is currently in. It waits to be enabled and will remain in the final state until disabled. A simple test bench is also provided for reference.

module system_verilog_sm
(
   input   logic       clk,
   input   logic       reset,
   input   logic       enable,
   output  logic [1:0] system_out
 );
 
// State encodings.
enum logic [1:0] {
                  STATE_0,
                  STATE_1,
                  STATE_2,
                  STATE_3
                  } current_state, next_state;
 
// Current state register.
always_ff @(posedge clk or posedge reset)
  if (reset) current_state <= STATE_0;
  else       current_state <= next_state;
 
// Next State logic.
always_comb begin
  next_state = STATE_0;
  unique case (current_state)
    STATE_0 : if (enable)  next_state = STATE_1;
              else         next_state = STATE_0;
    STATE_1 :              next_state = STATE_2;
    STATE_2 :              next_state = STATE_3;
    STATE_3 : if (!enable) next_state = STATE_0;
              else         next_state = STATE_3;
  endcase
end
 
// Output control logic.
always_ff @(posedge clk) begin
  unique case (current_state)
    STATE_0 : system_out <= 2'b00;
    STATE_1 : system_out <= 2'b01;
    STATE_2 : system_out <= 2'b10;
    STATE_3 : system_out <= 2'b11;
  endcase
end
 
endmodule

AttachmentSize
tb_system_verilog_sm.sv388 bytes
system_verilog_sm.sv1.13 KB