State Machine Logic
Part of the Fundamentals section of Coddy's Verilog journey — lesson 80 of 90.
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:
- Add an
always @(posedge clk or posedge reset)block - On reset, set
stateto Red (2) - When
nextis 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
endmoduleAll lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorComparison OperatorsRecap - Simple MathBitwise Operators7Assign And Gates
Continuous AssignmentAssign With OperatorsBuilt In Gate PrimitivesAND OR NOT GatesXOR XNOR GatesRecap - Logic Gate Circuit10Decision Making
If StatementIf - ElseRecap - Simple ComparatorCase StatementCasex And CasezRecap - ALU Design5Operators Part 2
Logical OperatorsReduction OperatorsShift OperatorsConcatenation OperatorConditional OperatorRecap - Operator Challenge3Number System
Binary RepresentationSized NumbersUnsized NumbersNegative NumbersSpecial Values X And ZRecap - Number Formats6Modules
Module StructureInput And Output PortsInout PortsModule InstantiationPort Mapping By NamePort Mapping By OrderRecap - Build A Module9Procedural Blocks
Always BlockInitial BlockSensitivity ListBlocking AssignmentNon Blocking AssignmentRecap - Always vs Initial15Traffic Light Controller
Defining The StatesState Machine Logic