Verilog HDL设计练习进阶(六)--掌握函数在模块设计中的使用
 
- UID
- 1023229
- 来自
- 中国
|

Verilog HDL设计练习进阶(六)--掌握函数在模块设计中的使用
练习六. 在Verilog HDL中使用函数目的:掌握函数在模块设计中的使用。
与一般的程序设计语言一样,Veirlog HDL也可使用函数以适应对不同变量采取同一运算的操作。Veirlog HDL函数在综合时被理解成具有独立运算功能的电路,每调用一次函数相当于改变这部分电路的输入以得到相应的计算结果。
下例是函数调用的一个简单示范,采用同步时钟触发运算的执行,每个clk时钟周期都会执行一次运算。并且在测试模块中,通过调用系统任务$display在时钟的下降沿显示每次计算的结果。
模块源代码:
module tryfunct(clk,n,result,reset);
output[31:0] result;
input[3:0] n;
input reset,clk;
reg[31:0] result;
always @(posedge clk) //clk的上沿触发同步运算。
begin
if(!reset) //reset为低时复位。
result<=0;
else
begin
result <= n * factorial(n)/((n*2)+1);
end
end
function [31:0] factorial; //函数定义。
input [3: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
测试模块源代码:
`include "./step6.v"
`timescale 1ns/100ps
`define clk_cycle 50
module tryfuctTop;
reg[3:0] n,i;
reg reset,clk;
wire[31:0] result;
initial
begin
n=0;
reset=1;
clk=0;
#100 reset=0;
#100 reset=1;
for(i=0;i<=15;i=i+1)
begin
#200 n=i;
end
#100 $stop;
end
always #`clk_cycle clk=~clk;
tryfunct tryfunct(.clk(clk),.n(n),.result(result),.reset(reset));
endmodule
上例中函数factorial(n)实际上就是阶乘运算。必须提醒大家注意的是,在实际的设计中,我们不希望设计中的运算过于复杂,以免在综合后带来不可预测的后果。经常的情况是,我们把复杂的运算分成几个步骤,分别在不同的时钟周期完成。
仿真波形(部分):
[[wysiwyg_imageupload:249:]] 练习:设计一个带控制端的逻辑运算电路,分别完成正整数的平方、立方和阶乘的运算。编写测试模块,并给出仿真波形。 |
|
|
|
|
|