/*
 * Exercise BB10 on Tiny Tapeout: a 4-bit adder and subtractor, as built
 * from the 40181 ALU.  The 7-segment display of the demo board shows the
 * result as a hexadecimal digit.
 *
 * Add add_sub.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
);

    // DIP switches 0-3 are A and switches 4-7 are B.  All eight are taken,
    // so SUB comes from BIDIR pin 0: connect it to VCC to subtract.  The
    // circuit has no clock and no reset.

    wire [3:0] f;
    wire       carry_n, all_ones;

    add_sub i_add_sub (
        .a        ( ui_in  [3:0] ),
        .b        ( ui_in  [7:4] ),
        .sub      ( uio_in [0]   ),
        .f        ( f            ),
        .carry_n  ( carry_n      ),
        .all_ones ( all_ones     )
    );

    // 7-segment display: uo_out [0] is segment a, ..., uo_out [6] is g,
    // uo_out [7] is the dot.  F as a hexadecimal digit: 0-9, then A, b, C,
    // d, E, F.  The dot is Cn+4: dark when the sum has a fifth bit, lit in
    // a subtraction when A < B.

    reg [6:0] gfedcba;

    always @(*)
        case (f)
        4'h0: gfedcba = 7'b0111111;
        4'h1: gfedcba = 7'b0000110;
        4'h2: gfedcba = 7'b1011011;
        4'h3: gfedcba = 7'b1001111;
        4'h4: gfedcba = 7'b1100110;
        4'h5: gfedcba = 7'b1101101;
        4'h6: gfedcba = 7'b1111101;
        4'h7: gfedcba = 7'b0000111;
        4'h8: gfedcba = 7'b1111111;
        4'h9: gfedcba = 7'b1101111;
        4'ha: gfedcba = 7'b1110111;
        4'hb: gfedcba = 7'b1111100;
        4'hc: gfedcba = 7'b0111001;
        4'hd: gfedcba = 7'b1011110;
        4'he: gfedcba = 7'b1111001;
        4'hf: gfedcba = 7'b1110001;
        endcase

    assign uo_out  = { carry_n, gfedcba };

    // F, Cn+4 and A=B on BIDIR pins 2-7; pin 0 is the SUB input

    assign uio_out = { f, carry_n, all_ones, 2'b0 };
    assign uio_oe  = 8'b1111_1100;

    // List all unused inputs to prevent warnings

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

endmodule
