Verilog中函数function写法使用方法

function写法

function的标准写法如下:

 

 函数的语法为:

.定义函数时至少要有一个输入参量;可以按照ANSI和module形式直接定义输入端口。

例如:function[63:0] alu (input[63:0] a, b, input [7:0] opcode);

.在函数的定义中必须有一条赋值语句给函数名具备相同名字的变量赋值;

.在函数的定义中不能有任何的时间控制语句,即任何用#,@或wait来标识的语句。

.函数不能启动任务。

.如果描述语句是可综合的,则必须所有分支均赋值,不予存在不赋值的情况,只能按照组合逻辑方式描述。

function与触发器电路结合
function本身表述的是组合电路,但可以赋值给某个触发器;

module func_test(
input rst_n,
input clk,
input [6:0] func_i,
output reg [4:0] func_o
);

//***************************************************************************
// Tasks and Functions
//***************************************************************************

// This function takes the lower 7 bits of a character and converts them
// to a hex digit. It returns 5 bits - the upper bit is set if the character
// is not a valid hex digit (i.e. is not 0-9,a-f, A-F), and the remaining
// 4 bits are the digit
function [4:0] to_val;
input [6:0] char;
begin
if ((char >= 7'h30) && (char <= 7'h39)) // 0-9
begin
to_val[4] = 1'b0;
to_val[3:0] = char[3:0];
end else if (((char >= 7'h41) && (char <= 7'h46)) || // A-F
((char >= 7'h61) && (char <= 7'h66)) ) // a-f
begin
to_val[4] = 1'b0;
to_val[3:0] = char[3:0] + 4'h9; // gives 10 - 15
end else begin
to_val = 5'b1_0000;
end
end
endfunction


wire [4:0] func_wire;

assign func_wire = to_val(func_i);

always @ (posedge clk or negedge rst_n ) begin
if ( !rst_n ) begin
func_o <= 5'b0;
end else begin
func_o <= func_wire;
end
end

endmodule

电路中,function对应的功能为判断输入字符是否为数字;而always描述数据的存储过程。

于是电路被清晰地划分为两部分:

计算函数部分,此部分为纯组合电路实现;
D触发存储部分。
如果只是简单的上述组合逻辑,工作频率不高,是完全可以使用该语法的。

但考虑到函数的复杂程度,比如许多超越函数,就需要进行分解;

posted @ 2022-08-25 09:08  电型金刚  阅读(904)  评论(0编辑  收藏  举报