Skip to content
Digital Rhyme
FPGA board, oscilloscope waveforms, and digital logic notes on a lab bench

traffic_light_fsm.v Source

Modules, wires, regs, combinational logic, sequential logic, testbenches, and synthesis.

1// SPDX-License-Identifier: MIT
2// A small finite-state machine. Each tick advances the light state.
3module traffic_light_fsm (
4 input wire clk,
5 input wire rst,
6 output reg red,
7 output reg yellow,
8 output reg green
9);
10 localparam S_RED = 2'd0;
11 localparam S_GREEN = 2'd1;
12 localparam S_YELLOW = 2'd2;
13
14 reg [1:0] state;
15 reg [3:0] timer;
16
17 always @(posedge clk) begin
18 if (rst) begin
19 state <= S_RED;
20 timer <= 4'd0;
21 end else begin
22 timer <= timer + 1'b1;
23
24 case (state)
25 S_RED:
26 if (timer == 4'd4) begin
27 state <= S_GREEN;
28 timer <= 4'd0;
29 end
30 S_GREEN:
31 if (timer == 4'd7) begin
32 state <= S_YELLOW;
33 timer <= 4'd0;
34 end
35 S_YELLOW:
36 if (timer == 4'd2) begin
37 state <= S_RED;
38 timer <= 4'd0;
39 end
40 default: begin
41 state <= S_RED;
42 timer <= 4'd0;
43 end
44 endcase
45 end
46 end
47
48 always @(*) begin
49 red = 1'b0;
50 yellow = 1'b0;
51 green = 1'b0;
52
53 case (state)
54 S_RED: red = 1'b1;
55 S_GREEN: green = 1'b1;
56 S_YELLOW: yellow = 1'b1;
57 default: red = 1'b1;
58 endcase
59 end
60endmodule