// Exercise M11a: Timofei Nikiforov's traffic light, as he built it:
// 3 clock cycles green, 1 yellow, 3 red.  On the breadboard a 4017 decade
// counter steps through the states, Q7 resets it, and the four 2-input OR
// gates of a 4071 make two 3-input OR gates for the lights.
//
// Generic version that matches schematic 1: five D flip-flops and gates,
// not tied to any chip.  Synthesizable.

module traffic_light
(
    input  logic       clk,
    input  logic       rst,     // 1 = go to state 0 at once, like RESET of the 4017

    output logic [6:0] q,       // q [k] = 1 in state k, like outputs Q0-Q6 of the 4017
    output logic       red,
    output logic       yellow,
    output logic       green
);

    //------------------------------------------------------------------------
    // State register: the 5-bit Johnson counter of the 4017 (a twisted ring
    // counter).  Every clock it shifts left and feeds the inverted top bit
    // into bit 0, one bit changes per clock:
    //
    // state  0     1     2     3     4     5     6
    // r      00000 00001 00011 00111 01111 11111 11110
    //
    // The ring has seven states.  On the breadboard the 4017 goes on to
    // state 7, and its output Q7, wired to RESET, clears the counter at once.
    // Here the step from state 6 to state 0 happens at the clock edge, as it
    // should in a synchronous design: after 11110 the shift would give 11100,
    // so in state 6 three AND gates put 0 into r [2], r [3] and r [4].
    // The new r [1] and r [0] are 0 anyway, because r [0] = 0 and r [4] = 1.

    logic [4:0] r;

    always_ff @ (posedge clk or posedge rst)
        if (rst)
            r <= '0;
        else
            r <= { r [3] & ~ q [6],
                   r [2] & ~ q [6],
                   r [1] & ~ q [6],
                   r [0],
                   ~ r [4] };

    //------------------------------------------------------------------------
    // Decoder: seven 2-input AND gates.  Two neighbouring bits identify each state.

    assign q [0] = ~ r [4] & ~ r [0];
    assign q [1] =   r [0] & ~ r [1];
    assign q [2] =   r [1] & ~ r [2];
    assign q [3] =   r [2] & ~ r [3];
    assign q [4] =   r [3] & ~ r [4];
    assign q [5] =   r [4] &   r [0];
    assign q [6] = ~ r [0] &   r [1];

    //------------------------------------------------------------------------
    // Output logic: each 3-input OR is two 2-input OR gates, as on the 4071;
    // yellow needs no gate

    assign green  = (q [0] | q [1]) | q [2];  // 3 clock cycles
    assign yellow =  q [3];                   // 1 clock cycle
    assign red    = (q [4] | q [5]) | q [6];  // 3 clock cycles

endmodule
