Menu
Coddy logo textTech

State Machine Logic

Part of the Fundamentals section of Coddy's Verilog journey — lesson 80 of 90.

challenge icon

Challenge

In this lesson, you will add the state transition logic to the traffic light controller. The state machine determines when to move from one state to the next.

The state machine logic controls when and how the traffic light changes states.

State Sequence

Green → Yellow → Red → Green → …

Your task is to add the state machine logic to the module.

What to do:

  1. Add an always @(posedge clk or posedge reset) block
  2. On reset, set state to Red (2)
  3. When next is 1, move to the next state:
    • If state is Green (0): change to Yellow
    • If state is Yellow (1): change to Red
    • If state is Red (2): change to Green

Try it yourself

module traffic_light (
  input clk,
  input reset,
  input next,           // Trigger to change state
  output reg red,
  output reg yellow,
  output reg green
);

  reg [1:0] state;

  // Output assignments
  always @(*) begin
    case (state)
      0: begin green = 1; yellow = 0; red = 0; end
      1: begin green = 0; yellow = 1; red = 0; end
      2: begin green = 0; yellow = 0; red = 1; end
      default: begin green = 0; yellow = 0; red = 1; end
    endcase
  end

  // TODO: Add state machine logic (without timing)
  // always @(posedge clk or posedge reset) begin
  //   if (reset) begin
  //     state <= 2;
  //   end else if (next) begin
  //     case (state)
  //       0: state <= 1;
  //       1: state <= 2;
  //       2: state <= 0;
  //     endcase
  //   end
  // end

endmodule

All lessons in Fundamentals