提示:文章完成后,目录可以自动生成,如何生成可以参考右边的帮助文档
前言
一、函数调用简单示范
1.1 程序语句:
1.2 testbench语句:
1.3 仿真波形:
二、带控制端的逻辑运算电路
2.1 程序语句:
2.2 testbench语句:
2.3 仿真波形:
总结
前言
函数调用的简单示范。执行同布时钟触发操作,每个clk计算将在测试模块中执行时钟周期,并通过调用系统任务$display每次计算的结果都显示在时钟的下降边。
一、函数调用简单示范
1.1 程序语句:
module tryfunction(clk, n, reset, result); input [3:0]n; input clk, reset; output [31:0]result; reg [31:0]result; always @(posedge clk) begin if(!reset) result <= 0; else begin result <= n * factorial(n)/((n * 2) 1); end end function [31:0]factorial; input [3:0]operand; reg [31:0]index; begin factorial = operand ? 1 : 0; for(index = 2; index <= operand; index = index 1) factorial = index * factorial; end endfunction endmodule
1.2 testbench语句:
`timescale 1 ns/ 100 ps `define clk_cycle 50 module tryfunction_vlg_tst(); reg clk; reg [3:0] n,i; reg reset; wire [31:0] result; tryfunction i1 ( .clk(clk), .n(n), .reset(reset), .result(result) ); initial begin clk = 0; n = 0; reset = 1; #100 reset = 0; #100 reset = 1; for(i=0;i<=15;i=i 1) begin #200 n=i; end end initial begin #100000 $stop; end always #`clk_cycle clk = ~clk; endmodule
二、带控制端的逻辑运算电路
2.1 程序语句:
module square_cube_factorial(clk, sel, n, reset, result); output [6:0]result; input clk, reset; input [2:0]n; input [1:0]sel; reg [6:0]result; always @(posedge clk) begin if(!reset) result <= 0; else begin case(sel) 2'b01: result <= square(n); 2'b10: result <= cube(n); 2'b11: result <= factorial(n); default: result <= 7'bx; endcase end end function [6:0]square; input [2:0]operand; begin square = operand * operand; end endfunction function [6:0]cube; input [2:0]operand; begin cube = operand * operand * operand; end endfunction function [6:0]factorial; input [2:0]operand; reg [3:0]index; begin factorial = operand ?1:0; for(index = 2; index <= operand; index = index 1) factorial = index * factorial; end endfunction endmodule
2.2 testbench语句:
`timescale 1 ns/ 100 ps `define clk_cycle 50 module square_cube_factorial_vlg_tst(); reg clk; reg [2:0] n; reg reset; reg [1:0] sel; wire [6:0] result; square_cube_factorial i1 ( .clk(clk), .n(n), .reset(reset), .result(result), .sel(sel) ); initial begin n = 0; sel = 0; clk = 0; reset = 1; #100 reset = 0; #100 reset = 1; forever begin #100 sel = {$random}%3; n = {$random}%6; en
end
initial
begin
#10000 $stop;
end
always #`clk_cycle clk = ~clk;
endmodule
2.3 仿真波形:
总结
factorial模块中,operand和index的代码长度需不同,否则仿真报错(原因暂时我也不知道。