Timing The Transitions
Part of the Fundamentals section of Coddy's Verilog journey. Lesson 81 of 90.
Challenge
In this lesson, you will add the counter logic that controls how long each light stays on. The counter counts down from a preset value to zero, then triggers the next state change.
Timing Requirements
| State | Duration | Counter Value |
|---|---|---|
| Green | 30 seconds | 30 |
| Yellow | 10 seconds | 10 |
| Red | 40 seconds | 40 |
How the Counter Works
- When a state begins, the counter is loaded with the duration value
- On each clock tick, the counter decreases by 1
- When the counter reaches 0, it is time to change to the next state
Your task is to add the missing counter logic to the state machine.
What to do:
- Add a
reg [5:0] counterdeclaration - On reset, set
counterto 0 - When
counter == 0:- Load the next state's duration into the counter
- Change to the next state
- Otherwise, decrement the counter by 1 on each clock
Try it yourself
module traffic_light (
input clk,
input reset,
output reg red,
output reg yellow,
output reg green
);
reg [1:0] state;
// TODO: Declare counter register (6 bits)
// 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
// State machine with timing
always @(posedge clk or posedge reset) begin
if (reset) begin
state <= 2; // Start at Red
// TODO: Set counter to 0
end else begin
if (counter == 0) begin
case (state)
0: begin
state <= 1;
// TODO: Load counter for Yellow (10 seconds)
end
1: begin
state <= 2;
// TODO: Load counter for Red (40 seconds)
end
2: begin
state <= 0;
// TODO: Load counter for Green (30 seconds)
end
endcase
end else begin
// TODO: Decrement counter by 1
end
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 LogicPractice on your own: Online Verilog compiler