Mini ALU

A 4-bit ALU with four operations selected by op, plus a zero flag that is high whenever result is 0.

op operation
00 a + b (wrapping)
01 a - b (wrapping)
10 a & b
11 a ^ b
Port Dir Width
a, b in 4
op in 2
result out 4
zero out 1

Refresher: the ALU capstone lesson.

Show the testbench (the grader)
tb.v — locked
`timescale 1ns/1ps
module tb;
    reg [3:0] a, b; reg [1:0] op; wire [3:0] result; wire zero;
    integer i, errors=0; reg [3:0] want;
    challenge dut (.a(a), .b(b), .op(op), .result(result), .zero(zero));
    initial begin
        $dumpfile("wave.vcd"); $dumpvars(0, tb);
        for (i = 0; i < 1024; i = i + 1) begin
            {op, a, b} = i[9:0]; #2;
            case (op)
                2'd0: want = a + b;
                2'd1: want = a - b;
                2'd2: want = a & b;
                default: want = a ^ b;
            endcase
            if (result !== want || zero !== (want == 4'd0)) begin
                errors = errors + 1;
                if (errors < 6)
                    $display("FAIL: op=%0d a=%h b=%h -> result=%h zero=%b",
                             op, a, b, result, zero);
            end
        end
        if (errors == 0) $display("TB PASS");
        else $display("TB FAIL (%0d errors)", errors);
        $finish;
    end
endmodule