File size: 2,306 Bytes
035592e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
`timescale 1ns / 1ps

module testbench;

  reg [3:0] A;    // First BCD input (4 bits)
  reg [3:0] B;    // Second BCD input (4 bits)
  reg Cin;        // Carry-in input (1 bit)
  wire [3:0] Sum; // BCD sum output (4 bits)
  wire Cout;      // Carry-out output (1 bit)

  integer i;      
  integer error = 0; 
  reg [4:0] expected_sum; 
  integer hA, hB, hC;      // additional check: exhaustive loop indices


  adder_bcd uut (
    .A(A),
    .B(B),
    .Cin(Cin),
    .Sum(Sum),
    .Cout(Cout)
  );

  initial begin
    for (i = 0; i < 100; i = i + 1) begin
        A = $random % 10; 
        B = $random % 10;
        Cin = $random % 2;
        if (A > 9) A = A % 10;
        if (B > 9) B = B % 10;
        // Wait for the operation to complete
        #10;

        expected_sum = A + B + Cin;

        // Adjust for BCD overflow (sum greater than 9)
        if (expected_sum > 9) begin
            expected_sum = expected_sum + 6;  // Correct the sum for BCD
        end

        // Check the result of the BCD adder
        if ({Cout, Sum} !== expected_sum) begin
            error = error + 1;
            $display("Test failed: A = %d, B = %d, Cin = %d | Expected = %d, Got = %d, Cout = %d", 
                     A, B, Cin, expected_sum, Sum, Cout);
        end
    end


    // Additional checks: the spec defines A and B as decimal digits 0..9 and Cin as 1 bit; the random loop
    // above never drives sums 1, 17 or 19 (e.g. 9+9+1). Check every valid input combination (200 cases).
    for (hA = 0; hA < 10; hA = hA + 1)
      for (hB = 0; hB < 10; hB = hB + 1)
        for (hC = 0; hC < 2; hC = hC + 1) begin
          A = hA; B = hB; Cin = hC;
          #10;
          expected_sum = A + B + Cin;
          if (expected_sum > 9) expected_sum = expected_sum + 6;
          if ({Cout, Sum} !== expected_sum) begin
            error = error + 1;
            $display("HCHK exhaustive: A = %0d, B = %0d, Cin = %0d | Expected {Cout,Sum} = %b, Got Cout = %b Sum = %b",
                     A, B, Cin, expected_sum, Cout, Sum);
          end
        end
    
    if (error == 0) begin
      $display("=========== Your Design Passed ===========");
    end
    else begin
      $display("=========== Test completed with %d /100 failures ===========", error);
    end

    $finish;
  end

endmodule