Yes, you can create a fully functional traffic light controller in Verilog. This logic operates by taking a fixed time unit (the clock) and using counters to cycle through specific states—Red, Yellow, and Green—before switching to the next one. This guide provides a complete, step-by-step implementation using a standard 4-bit counter and synchronous logic, which is the most reliable method for FPGA hardware.

What You'll Need

  • Verilog Simulation Tool: A simulator like ModelSim, QuestaSim, or Icarus Verilog. This allows you to test the code logic before burning it to hardware.
  • FPGA Development Board: A board compatible with your Verilog toolchain (e.g., Xilinx Vivado for Artix-7 boards, Intel Quartus for Cyclone IV boards). You will need LEDs to represent the lights.
  • Text Editor: A code editor such as Notepad++, VS Code, or vim to write your Verilog source files.
  • Basic Understanding of Digital Logic: Familiarity with concepts like states, clock cycles, and active-low logic is helpful.

Step-by-Step

1. Define the Module Interface

Start by creating a new Verilog file. The first step is to define the inputs and outputs of your module. You will typically need a system clock input to drive the timing, and three output ports to represent the three lights. Note that on most hardware, LEDs are active-low, meaning they turn on when the signal is logic 0. We will define the outputs as reg (registers) because their values change over time.

  1. Open your text editor and create a new file named traffic_light.v.
  2. Begin the module declaration with the keyword module, name it traffic_light, and list the ports.
  3. Use the following code as your starting point for the interface:
module traffic_light (
    input wire clk,        // System clock
    input wire reset,      // Reset button (active high)
    output reg red,        // Red light output
    output reg yellow,     // Yellow light output
    output reg green       // Green light output
);

2. Implement the Counter Logic

The core of the traffic light controller is a counter that counts the number of clock cycles. Each clock cycle represents a specific time unit (e.g., 1 second). To make the system robust, this counter should be synchronous, meaning it updates only on the rising edge of the clock signal. We will use a 4-bit counter because it can count up to 15. This provides enough range to handle the timing for each light phase.

  1. Inside the module, declare a 4-bit register to hold the counter value. You can name it counter or tick_count.
  2. Add an always block that triggers on the positive edge of the clock. This block will contain the counter logic.
  3. Use a conditional statement (if) to check if the reset signal is active. If it is, set the counter to 0. Otherwise, increment the counter by 1.
  4. Implement a modulo operation or a conditional check to reset the counter to 0 once it reaches the maximum value (e.g., 15). This ensures it wraps around and starts counting again.
reg [3:0] tick_count; // 4-bit counter

always @(posedge clk or posedge reset) begin
    if (reset)
        tick_count <= 4'b0; // Clear counter on reset
    else if (tick_count == 4'd15)
        tick_count <= 4'b0; // Reset after counting to 15
    else
        tick_count <= tick_count + 1; // Increment counter
end

3. Define the Traffic Light States

Now that we have a counter, we need to determine which light should be on for each count value. We will define a simple state machine with three main states: Red, Green, and Yellow. The transition between these states will be based on the counter value.

  1. Inside the same always block, add a series of if-else if statements to check the value of tick_count.
  2. For the first state, set the Green light to 1 and the other lights to 0 when the counter is between 0 and 9. This gives a duration of 10 clock cycles.
  3. For the second state, set the Yellow light to 1 when the counter is between 10 and 12. This gives a duration of 3 clock cycles.
  4. For the third state, set the Red light to 1 when the counter is between 13 and 15. This gives a duration of 3 clock cycles.
always @(posedge clk or posedge reset) begin
    if (reset) begin
        tick_count <= 4'b0;
        red <= 1'b0;
        yellow <= 1'b0;
        green <= 1'b0;
    end
    else begin
        // Counter Logic
        if (tick_count == 4'd15)
            tick_count <= 4'b0;
        else
            tick_count <= tick_count + 1;

        // State Logic
        if (tick_count <= 4'd9) begin
            green <= 1'b1; // Green is ON
            red <= 1'b0;
            yellow <= 1'b0;
        end
        else if (tick_count <= 4'd12) begin
            yellow <= 1'b1; // Yellow is ON
            red <= 1'b0;
            green <= 1'b0;
        end
        else begin
            red <= 1'b1; // Red is ON
            yellow <= 1'b0;
            green <= 1'b0;
        end
    end
end

4. Handle the Physical LEDs

Most LEDs on development boards are active-low. This means that to turn the LED on, you must drive the corresponding pin to logic 0, and to turn it off, you must drive it to logic 1. In our Verilog code, we have assumed the lights are active-high, so we set the signal to 1 to turn them on. To make this work with real hardware, you need to invert these signals in your code.

  1. Modify the output assignments in the always block.
  2. Assign the logical value to an intermediate signal or directly invert the output.
  3. For example, instead of red <= 1'b1;, you would write red <= 1'b0; to turn the LED on.
else begin
    // Counter Logic
    if (tick_count == 4'd15)
        tick_count <= 4'b0;
    else
        tick_count <= tick_count + 1;

    // State Logic
    if (tick_count <= 4'd9) begin
        green <= 1'b0; // LED is ON
        red <= 1'b1;
        yellow <= 1'b1;
    end
    else if (tick_count <= 4'd12) begin
        yellow <<= 1'b0; // LED is ON
        red <= 1'b1;
        green <= 1'b1;
    end
    else begin
        red <= 1'b0; // LED is ON
        yellow <= 1'b1;
        green <= 1'b1;
    end
end

5. Test the Code in Simulation

Before you can trust the code, you must simulate it. Simulation allows you to see the internal values of the signals over time without needing physical hardware. Most simulators require a testbench file to generate the clock and reset signals.

  1. Create a new file named tb_traffic_light.v. This is your testbench.
  2. In the testbench, instantiate the traffic_light module.
  3. Create a continuous clock signal in the testbench. A common technique is to use an initial block that toggles a signal every 10 time units.
  4. Create a reset signal that is high for a short period and then low. This will force the system into the initial state.
  5. Run the simulation for a sufficient amount of time (e.g., 1000 time units) to see all the light states cycle through.
  6. Check the waveform window to ensure the Green light stays on for the correct duration, followed by the Yellow light, and then the Red light.

6. Program the FPGA Board

Once the simulation is successful, you can move on to programming the physical hardware. The exact process varies by board vendor, but the general steps are the same.

  1. Open your FPGA vendor's software (e.g., Vivado, Quartus).
  2. Create a new project and add your Verilog source file (traffic_light.v). Follow any prompts to generate constraints files if necessary.
  3. Implement the design by running the synthesis and place & route tools. This converts your Verilog code into a bitstream that the FPGA can understand.
  4. Open the Hardware Manager.
  5. Connect your board to your computer via USB.
  6. Program the device by selecting the generated bitstream and clicking "Program Device". The LEDs should now cycle through Red, Yellow, and Green.

Common Mistakes

  • Using Non-Synchronous Logic: A common mistake is to try to control the lights directly inside an always block without a counter. This leads to unpredictable behavior because the logic is not synchronized to the clock. Always use a counter for timing.
  • Forgetting Active-Low Logic: As mentioned, many LEDs are active-low. If you forget to invert the signal, the lights will appear to be always on or never turn on, depending on the default state of the pin.
  • Incorrect Counter Width: If you choose a counter that is too small (e.g., 2-bit), it will not be able to hold the required number of cycles for a full traffic light cycle. A 4-bit counter is typically sufficient, but you may need to adjust it based on your clock speed.
  • Missing Reset Logic: The reset logic is crucial for bringing the system to a known state. If you forget it, the system may start in an undefined state or get stuck in a loop.

Tips

  • Use a Constant for the Clock Period: If you are using a simulator, it is helpful to define a constant at the top of your file (e.g., parameter CLK_PERIOD = 10;) to make your code more readable and easier to modify.
  • Start Simple: Before adding complex features like pedestrian buttons or sensors, ensure the basic Red-Green-Yellow cycle works perfectly. This makes debugging much easier.
  • Check the Timing: The duration of each light depends entirely on your clock frequency. If the lights are flashing too fast or too slow, check the clock speed and adjust your counter values accordingly.
  • Use a State Machine: As the logic becomes more complex, consider using a more formal state machine approach. This can make the code easier to read and maintain, especially when adding new states or transitions.

Troubleshooting

If your traffic light controller is not working as expected, follow these steps to diagnose the problem.

1. Check the Simulation Waveform

Before doing anything else, check your simulation waveform. This is the most effective way to find bugs in your code. Look for the following:

  • Is the counter incrementing correctly?
  • Are the outputs changing at the right time?
  • Is the reset signal working as expected?

If the simulation is wrong, the hardware will also be wrong. Fix the code in the simulator until the waveform matches your expectations.

2. Verify the Clock Signal

If the simulation looks correct but the hardware is not working, the problem is likely with the clock. Check that the clock signal is connected to the correct pin on the FPGA. You can also use an oscilloscope or a logic analyzer to verify the clock frequency and signal integrity.

3. Check the Pin Constraints

If the simulation and clock are correct, the problem may be with the pin constraints. This file tells the FPGA software which physical pin on the board corresponds to which logical signal. If the constraints are wrong, the signals will be routed to the wrong pins, and the LEDs will not light up. Open your constraints file and verify that the red, yellow, and green signals are assigned to the correct LED pins.

If that did not work, try a simple blinking LED.

If you are still having trouble, disconnect all the traffic light logic and program the board with a simple blinking LED program. This will help you determine if the problem is with the board itself or with your traffic light code.

Frequently Asked Questions

How do I change the duration of the lights?

You can change the duration by adjusting the counter values in the state logic. For example, to make the green light last for 20 clock cycles, change the condition from if (tick_count <= 4'd9) to if (tick_count <= 4'd19).

Can I use a 2-bit counter?

A 2-bit counter can only count up to 3. This is not enough for a standard traffic light cycle, which requires at least 10 clock cycles (3 for green, 3 for yellow, and 4 for red). You should use a 4-bit counter or higher.

Why are my LEDs not lighting up?

There are a few common reasons for this. First, check if your LEDs are active-low. If they are, you need to invert the signal in your code. Second, check your pin constraints to ensure the signals are assigned to the correct pins. Third, check the power supply to the board.

What is the purpose of the reset signal?

The reset signal is used to bring the system to a known state. When the reset signal is high, the counter is cleared, and all lights are turned off. This is important for initializing the system and preventing it from starting in an undefined state.

Can I add pedestrian sensors to this code?

Yes, you can add pedestrian sensors by adding an additional input to the module. You would then modify the state logic to check the sensor input and override the default cycle if the sensor is triggered.

How do I handle the case where the clock is too fast?

If your clock is too fast, the lights will flash too quickly to see. You can solve this by either slowing down the clock or increasing the counter values to count for more clock cycles.