/*
 * Exercise B5 on Tiny Tapeout: an up/down counter shown as a hexadecimal
 * digit on the 7-segment display of the demo board.
 *
 * Add up_down_counter.sv to source_files in info.yaml next to project.v.
 * Rename the module to tt_um_<your GitHub name>_<project name> and use the
 * same name as top_module in info.yaml.
 */

`default_nettype none

module tt_um_example (
    input  wire [7:0] ui_in,    // DIP switches, INPUT Pmod, RP2350 GPIO17-24
    output wire [7:0] uo_out,   // 7-segment display, OUTPUT Pmod, RP2350 GPIO33-40
    input  wire [7:0] uio_in,   // BIDIR Pmod, RP2350 GPIO25-32
    output wire [7:0] uio_out,  //   (same pins)
    output wire [7:0] uio_oe,   //   1 = your design drives the pin
    input  wire       ena,      // set by the on-chip project mux, not a board pin
    input  wire       clk,      // RP2350 GPIO16
    input  wire       rst_n     // RP2350 GPIO14
);

    // Set the project clock to 1 Hz (clock_hz: 1 in info.yaml): the demo
    // board makes it, and clk drives the counter directly, like the 555
    // module on the breadboard.  Switch 0 = count up, switch 1 = binary
    // (0-15) instead of decade (0-9).  The reset button of the board is rst_n.

    wire [3:0] q;
    wire       carry_out_n;

    up_down_counter i_up_down_counter (
        .clk         ( clk         ),
        .rst         ( ~ rst_n     ),
        .up          ( ui_in [0]   ),
        .binary      ( ui_in [1]   ),
        .q           ( q           ),
        .carry_out_n ( carry_out_n )
    );

    // 7-segment display: uo_out [0] is segment a, ..., uo_out [6] is g,
    // uo_out [7] is the dot.  The digit shows the count in hexadecimal, the
    // dot lights at the last count (CARRY OUT is active low).

    reg [6:0] gfedcba;

    always @(*)
        case (q)
        4'h0: gfedcba = 7'b011_1111;
        4'h1: gfedcba = 7'b000_0110;
        4'h2: gfedcba = 7'b101_1011;
        4'h3: gfedcba = 7'b100_1111;
        4'h4: gfedcba = 7'b110_0110;
        4'h5: gfedcba = 7'b110_1101;
        4'h6: gfedcba = 7'b111_1101;
        4'h7: gfedcba = 7'b000_0111;
        4'h8: gfedcba = 7'b111_1111;
        4'h9: gfedcba = 7'b110_1111;
        4'ha: gfedcba = 7'b111_0111;
        4'hb: gfedcba = 7'b111_1100;
        4'hc: gfedcba = 7'b011_1001;
        4'hd: gfedcba = 7'b101_1110;
        4'he: gfedcba = 7'b111_1001;
        4'hf: gfedcba = 7'b111_0001;
        endcase

    assign uo_out  = { ~ carry_out_n, gfedcba };

    assign uio_out = 8'b0;
    assign uio_oe  = 8'b0;

    // List all unused inputs to prevent warnings

    wire _unused = & { ena, ui_in [7:2], uio_in, 1'b0 };

endmodule
