Menu
Coddy logo textTech

Timing The Transitions

Part of the Fundamentals section of Coddy's Verilog journey. Lesson 81 of 90.

challenge icon

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

StateDurationCounter Value
Green30 seconds30
Yellow10 seconds10
Red40 seconds40

How the Counter Works

  1. When a state begins, the counter is loaded with the duration value
  2. On each clock tick, the counter decreases by 1
  3. 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:

  1. Add a reg [5:0] counter declaration
  2. On reset, set counter to 0
  3. When counter == 0:
    • Load the next state's duration into the counter
    • Change to the next state
  4. 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

endmodule

All lessons in Fundamentals

Practice on your own: Online Verilog compiler