My exercise was to design and test a 4-bit adder/subtractor in strcutural form, the adder/subtractor will operate either adder or subtractor depending on the control signal. I have the sample answer now but don't understand the working of it. Please help explain to me the below code, how does the code make a 4-bit adder/subtractor in structural form? And how does the testbench work to test it? If possible please explain line by line, I will rate 5 stars I promise, tq.
My exercise was to design and test a 4-bit adder/subtractor in strcutural form, the adder/subtractor will operate either adder or subtractor depending on the control signal. I have the sample answer now but don't understand the working of it. Please help explain to me the below code, how does the code make a 4-bit adder/subtractor in structural form? And how does the testbench work to test it? If possible please explain line by line, I will rate 5 stars I promise, tq.
Structural 4-bit Adder/Subtractor |
Structural 4-bit Adder/Subtractor testbench |
module adder_subtractor(A, B, Cin, k, Sum, Cout); input [3:0] A,B; input Cin; input k; output [3:0] Sum; output Cout;
wire C0, C1, C2; wire S0, S1, S2, S3;
xor x1 (S0, k, B[0]); xor x2 (S1, k, B[1]); xor x3 (S2, k, B[2]); xor x4 (S3, k, B[3]);
fulladder M1(A[0], S0, Cin, Sum[0], C0); fulladder M2(A[1], S1, C0, Sum[1], C1); fulladder M3(A[2], S2, C1, Sum[2], C2); fulladder M4(A[3], S3, C2, Sum[3], Cout);
endmodule
module fulladder(A, B, Cin, Sum, Cout); input A, B, Cin; output Sum, Cout;
wire n1, n2, x1; xor u1 (x1, A, B); xor u2 (Sum, x1, Cin); and u3 (n1, Cin, x1); and u4 (n2, A, B); or u5 (Cout, n1, n2);
endmodule |
`timescale 1us / 100ns //total duration 10.24ms
module adder_subtractor_tb();
reg [3:0] A, B; reg Cin, k; wire [3:0] Sum; wire Cout;
adder_subtractor u1 (A, B, Cin, k, Sum, Cout); integer i;
initial begin
k=0; for (i=0; i<512; i=i+1) begin {Cin,B,A}=i; #10; end
k=1; for (i=0; i<512; i=i+1) begin {Cin,B,A}=i; #10; end
end endmodule |
Step by step
Solved in 2 steps
Can you please explain the testbench part of the question as well? the code on the right side, thanks in advance
For reference:
Structural 4-bit Adder/Subtractor testbench |
`timescale 1us / 100ns //total duration 10.24ms
module adder_subtractor_tb();
reg [3:0] A, B; reg Cin, k; wire [3:0] Sum; wire Cout;
adder_subtractor u1 (A, B, Cin, k, Sum, Cout); integer i;
initial begin
k=0; for (i=0; i<512; i=i+1) begin {Cin,B,A}=i; #10; end
k=1; for (i=0; i<512; i=i+1) begin {Cin,B,A}=i; #10; end
end endmodule |