module addernew(
input clk ,
input rst_n ,
input [2:0] in_a ,
input [2:0] in_b ,
input sel ,// 选择器
output reg [4:0] sum ,
output reg [4:0] carry
);
always@(posedge clk or negedge rst_n )
begin
if(rst_n ==0)
begin
carry <=0;
sum <=0;
end
else
begin
if( sel ==0)
begin
{carry,sum }<= in_a + in_b ;
end
else
begin
{carry,sum }<= in_a * in_b ;
end
end
end
endmodule
adder_tb.sv
class input_0;staticint count =0;int id;
logic [2:0] ina;// 与 in_a 和 in_b 一致的类型int arr[5]= '{1,2,3,4,5};// constructor
function new();
this.id = count++;
endfunction
// task to show values
task showk();foreach(arr[i]) begin
automatic int k = arr[i];
$write("%d\n", k);
end
endtask
// function to run with input
function voidrun(int a);
ina = a;// 直接赋值
$display("ina number is %3d", ina);
endfunction
endclass
module test();
input_0 inst_a, inst_b;
logic clk;
logic rst_n;
logic sel;
logic [2:0] in_a, in_b;// 使用 logic 代替 wire
logic [4:0] sum, carry;// Generate clock
initial begin
clk =0;
forever #5 clk =~clk;
end
// Adder module instantiation
addernew uadder(.clk(clk),.rst_n(rst_n),.in_a(in_a),// 从 in_a 获取值.in_b(in_b),// 从 in_b 获取值.sel(sel),.sum(sum),.carry(carry));
initial begin
rst_n =0;// 初始化复位信号
inst_a =new();
inst_b =new();
$display("inst_a id = %d", inst_a.id);
$display("inst_b id = %d", inst_b.id);
inst_a.showk();
inst_b.showk();
#10 rst_n =1;// 释放复位信号
sel =1;// 选择信号
inst_a.run(3);// 运行 inst_a
inst_b.run(2);// 运行 inst_b// 赋值 in_a 和 in_b
in_a = inst_a.ina;
in_b = inst_b.ina;
#105;// 等待一段时间// 打印结果
$display("ina = %3d, inb = %3d, sel = %d, sum = %5d, carry = %5d",
in_a, in_b, sel, sum, carry);
$display("time = %t",$time);
end
endmodule