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

// Exercise B5 in the hackathon setup of Basics-Graphics-Music (BGM):
// https://github.com/yuri-panchul/basics-graphics-music
//
// Copy hackathon/problems/4_binary_counter, replace its hackathon_top.sv
// with this file and add up_down_counter.sv.
//
// The counter runs from slow_clock, one beat per second, like the
// breadboard with the 555 module.  It counts up, or down while key 0 is
// pressed; it counts 0-9, or 0-15 while key 1 is pressed.  The LEDs show
// the count and ~CARRY OUT, the rightmost digit shows the count, and the
// screen shows four bars, one per bit, Q4 on the left.

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
);

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

    logic [3:0] q;
    logic       carry_out_n;

    up_down_counter i_up_down_counter
    (
        .clk         ( slow_clock  ),
        .rst         ( reset       ),
        .up          ( ~ key [0]   ),
        .binary      ( key [1]     ),
        .q           ( q           ),
        .carry_out_n ( carry_out_n )
    );

    assign led = { 3'b0, carry_out_n, q };

    seven_segment_display # (.w_digit (8)) i_7segment
    (
        .clk      ( clock          ),
        .rst      ( reset          ),
        .number   ( 32' (q)        ),
        .dots     ( '0             ),
        .abcdefgh ( abcdefgh       ),
        .digit    ( digit          )
    );

    //------------------------------------------------------------------------
    // Four bars on the 480 x 272 screen, one per bit of the count: bright
    // green for 1, dim for 0.  Bit 3 is on the left, as on the LEDs.

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

        for (int i = 0; i < 4; i ++)
            if (x >= 9' (72 + i * 96) & x < 9' (144 + i * 96) & y >= 60 & y < 212)
                green = q [3 - i] ? 63 : 12;
    end

endmodule
