Verilog Crash Course code / traffic_light_fsm.v
Code Sample

traffic_light_fsm.v

The worked example in Lesson 5 — Finite State Machines, tested by the testbench in Lesson 6. Original source: code/traffic_light_fsm.v.

// Traffic light controller FSM. See Lesson 5 (Finite State Machines).
// Moore machine: outputs depend only on the current state.
// Three-block style: state register, next-state logic, output logic.
module traffic_light_fsm (
    input  wire clk,
    input  wire rst,
    input  wire tick,
    output reg  red,
    output reg  yellow,
    output reg  green
);
    localparam [1:0] S_RED = 2'd0, S_GREEN = 2'd1, S_YELLOW = 2'd2;
    reg [1:0] state, next_state;

    // Block 1: the state register -- the only sequential element here.
    always @(posedge clk) begin
        if (rst) state <= S_RED;
        else     state <= next_state;
    end

    // Block 2: next-state logic -- purely combinational.
    always @(*) begin
        case (state)
            S_RED:    next_state = tick ? S_GREEN  : S_RED;
            S_GREEN:  next_state = tick ? S_YELLOW : S_GREEN;
            S_YELLOW: next_state = tick ? S_RED     : S_YELLOW;
            default:  next_state = S_RED;
        endcase
    end

    // Block 3: output logic (Moore -- depends only on state).
    always @(*) begin
        {red, yellow, green} = 3'b000;   // defensive default -- avoids latches
        case (state)
            S_RED:    red    = 1'b1;
            S_GREEN:  green  = 1'b1;
            S_YELLOW: yellow = 1'b1;
            default:  red    = 1'b1;
        endcase
    end
endmodule

← Back to home