// Board configuration: tang_nano_9k_lcd_480_272_tm1638_hackathon
// This module uses few parameterization and relaxed typing rules

// Exercise B4 in the hackathon setup of Basics-Graphics-Music (BGM):
// https://github.com/yuri-panchul/basics-graphics-music
//
// Copy hackathon/problems/3_d_flip_flop, replace its hackathon_top.sv with
// this file and add d_flip_flop.sv.
//
// The flip-flop runs from slow_clock, one beat per second, like the
// breadboard with the 555 module.  Any key is D.  The LEDs show the clock,
// D, Q and NOT Q, and so does the screen, as four lamps.

module hackathon_top
(
    input  logic       clock,
    input  logic       slow_clock,
    input  logic       reset,

    input  logic [7:0] key,
    output logic [7:0] led,

    // A dynamic seven-segment display

    output logic [7:0] abcdefgh,
    output logic [7:0] digit,

    // LCD screen interface

    input  logic [8:0] x,
    input  logic [8:0] y,

    output logic [4:0] red,
    output logic [5:0] green,
    output logic [4:0] blue,

    inout  logic [3:0] gpio
);

    //------------------------------------------------------------------------

    wire  d = | key;
    logic q, q_n;

    d_flip_flop i_d_flip_flop
    (
        .clk ( slow_clock ),
        .rst ( reset      ),
        .d   ( d          ),
        .q   ( q          ),
        .q_n ( q_n        )
    );

    assign led      = { 4'b0, q_n, q, d, slow_clock };

    assign abcdefgh = '0;
    assign digit    = '0;

    //------------------------------------------------------------------------
    // Four square lamps on the 480 x 272 screen: clock and D in blue,
    // Q and NOT Q in green.  Bright when 1, dim when 0.

    wire [3:0] lamp = { q_n, q, d, slow_clock };

    always_comb
    begin
        red   = 0;
        green = 0;
        blue  = 0;

        for (int i = 0; i < 4; i ++)
            if (x >= 9' (88 + i * 80) & x < 9' (136 + i * 80) & y >= 112 & y < 160)
            begin
                if (i < 2)
                    blue  = lamp [i] ? 31 : 6;
                else
                    green = lamp [i] ? 63 : 12;
            end
    end

endmodule
