Verilog中task,fun与module的调用
程序员文章站
2022-07-14 22:57:19
...
本文旨在当大家写module或者task以及fun时有个模板进行借鉴,以及了解如何调用fun与task,然后就是如何写testbench文件。
一、module的调用:
//这是一个简单的3-8译码器模块
//.v文件
module digitalEncode(impo,expo);
input[2:0]impo;
output[7:0]expo;
reg[7:0]expo;
aaa@qq.com(*)begin
expo = 8'b0111_1111;
case(impo)
3'b000:expo = 8'b0111_1111;
3'b001:expo = 8'b1011_1111;
3'b010:expo = 8'b1101_1111;
3'b011:expo = 8'b1110_1111;
3'b100:expo = 8'b1111_0111;
3'b101:expo = 8'b1111_1011;
3'b110:expo = 8'b1111_1101;
3'b111:expo = 8'b1111_1110;
default:expo = 8'b1111_1111;
endcase
end
endmodule
//testbench文件
`timescale 10ns/1ps
module digitalEncode_tb;
reg[2:0]impo;
parameter Delay = 100;
wire[7:0] expo;
digitalEncode z(impo,expo);
initial begin
#Delay impo = 3'b000;
#Delay impo = 3'b001;
#Delay impo = 3'b010;
#Delay impo = 3'b011;
#Delay impo = 3'b100;
#Delay impo = 3'b101;
#Delay impo = 3'b110;
#Delay impo = 3'b111;
#Delay impo = 3'b111;
end
endmodule
看下仿真:
二、task的调用:
//调用了按位与的一个task
module alutask(code,a,b,c);
input [1:0] code;
input [3:0] a,b;
output [4:0] c;
reg[4:0] c;
task my_and;//任务定义,注意无端口列表
input [3:0] a,b;//名称的作用域范围为task任务内部
output [4:0] out;
integer i;
begin
for(i = 3;i >= 0;i = i - 1)
out[i] = a[i] & b[i];//按位与
end
endtask
aaa@qq.com(*)
begin
case(code)
2'b00:my_and(a,b,c);
2'b01:c = a|b;
2'b10:c = a+b;
2'b11:c = a-b;
endcase
end
endmodule
//testbench
`timescale 10ns/1ps
module alu_tb;
reg [3:0] a,b;
reg [1:0] code;
wire [4:0] c;
parameter Delay = 100;
alutask ADD(code,a,b,c);//调用被测模块
initial begin
code = 4'd0;a = 4'b0000;b = 4'b1111;
#Delay code = 4'd0; a = 4'b0111;b = 4'b1101;
#Delay code = 4'd1; a = 4'b0001;b = 4'b0011;
#Delay code = 4'd2; a = 4'b1001;b = 4'b0011;
#Delay code = 4'd3; a = 4'b0011;b = 4'b0011;
#Delay code = 4'd4; a = 4'b0111;b = 4'b1001;
#Delay $stop;
end
initial $monitor($time,,,"code = %b a = %b b = %b c = %b",code,a,b,c);
endmodule
仿真结果:
三、function的调用
//module中调用fun
//fun的作用是计输入二进制数据0的个数
module count_0(a,b);
input [7:0] a;
output[2:0] b;
//wire [2:0] b;
function [2:0]Count0Fun;
input[7:0] a;
integer i;
begin
Count0Fun = 0;
for(i = 0;i < 8;i = i+1)begin
if(a[i] == 0)
Count0Fun = Count0Fun + 1'b1;
end
end
endfunction
assign b = Count0Fun(a);
endmodule
`timescale 10ns/1ps
module count0_tb;
reg [7:0] a;
wire [2:0] b;
parameter Delay = 10;
count_0 coun(.a(a),.b(b));
initial begin
#Delay a = 8'b00000000;
#Delay a = 8'b00000001;
#Delay a = 8'b00000011;
#Delay a = 8'b00000111;
#Delay a = 8'b00001111;
#Delay a = 8'b00011111;
#Delay a = 8'b00111111;
#Delay a = 8'b01111111;
#Delay a = 8'b11111111;
end
endmodule