0
0
Verilogprogramming~7 mins

State encoding (binary, one-hot, gray) in Verilog

Choose your learning style9 modes available
Introduction

State encoding helps a digital circuit remember what it is doing by assigning simple codes to each step. It makes the circuit easier to build and understand.

When designing a traffic light controller to manage different light states.
When creating a vending machine that moves through steps like waiting for money, selecting product, and giving change.
When building a simple game controller that tracks player moves.
When programming a washing machine cycle with different washing stages.
Syntax
Verilog
typedef enum logic [N-1:0] {
  STATE_0 = code_0,
  STATE_1 = code_1,
  ...
} state_type;

state_type current_state, next_state;

Binary encoding: Uses the smallest number of bits, counting up in binary.

One-hot encoding: Uses one bit per state, only one bit is '1' at a time.

Gray encoding: Changes only one bit between states to reduce errors.

Examples
This is binary encoding with 2 bits for 3 states.
Verilog
typedef enum logic [1:0] {
  IDLE = 2'b00,
  RUN = 2'b01,
  STOP = 2'b10
} state_t;
This is one-hot encoding with 3 bits, one bit per state.
Verilog
typedef enum logic [2:0] {
  IDLE = 3'b001,
  RUN = 3'b010,
  STOP = 3'b100
} state_t;
This is gray encoding where only one bit changes between states.
Verilog
typedef enum logic [1:0] {
  IDLE = 2'b00,
  RUN = 2'b01,
  STOP = 2'b11
} state_t;
Sample Program

This simple FSM cycles through three states using binary encoding. It moves from IDLE to RUN, then STOP, then back to IDLE.

Verilog
module fsm_example(
  input logic clk, reset,
  output logic [1:0] state_out
);

  typedef enum logic [1:0] {
    IDLE = 2'b00,    // binary encoding
    RUN = 2'b01,
    STOP = 2'b10
  } state_t;

  state_t current_state, next_state;

  always_ff @(posedge clk or posedge reset) begin
    if (reset)
      current_state <= IDLE;
    else
      current_state <= next_state;
  end

  always_comb begin
    case (current_state)
      IDLE: next_state = RUN;
      RUN: next_state = STOP;
      STOP: next_state = IDLE;
      default: next_state = IDLE;
    endcase
  end

  assign state_out = current_state;

endmodule
OutputSuccess
Important Notes

One-hot encoding uses more bits but can make circuits faster and simpler.

Gray encoding helps reduce errors when states change by only flipping one bit at a time.

Binary encoding is compact but may cause more complex logic for state transitions.

Summary

State encoding assigns codes to states to help digital circuits remember steps.

Binary encoding uses few bits, one-hot uses one bit per state, gray changes one bit at a time.

Choose encoding based on circuit size, speed, and complexity needs.