State Machine
Submitted by abettino on Thu, 02/25/2010 - 21:59
A Verilog state machine can be coded very clearly and concisely with separate always blocks for the next state combinational logic and the current state registers. It is also convenient to split other sequential logic, such as for output signals or other data processing, into a separate always block. This makes it easy to visually identify the state transitions and to modify the state machine without much hassle.
This state machine performs the same behaviour as the one described in the SystemVerilog section. Please see SystemVerilog State Machine.
module verilog_sm ( input clk, input reset, input enable, output reg [1:0] system_out ); // State encodings. parameter [1:0] STATE_0 = 2'b00, STATE_1 = 2'b01, STATE_2 = 2'b10, STATE_3 = 2'b11; reg [1:0] current_state, next_state; // Current state register. always @(posedge clk or posedge reset) if (reset) current_state <= STATE_0; else current_state <= next_state; // Next State logic. always @* begin next_state = 'bx; 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 @(posedge clk) begin 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
| Attachment | Size |
|---|---|
| verilog_sm.sv | 1.08 KB |

encoding
Keep in mind that you can encode the state machine in any fashion you see fit. one-hot is a popular choice for moderately large state machines. the idea is that much of the logic can use a single "this is my state" control bit.
further logic optimization can be made by partitioning the state machine with state groups. eg, if state1 = 1001, state2 = 0010, state3 = 1100 then at any given cycle, logic has access to "in state N", as well as "in state1 or state3".