21.条件编译举例
module compile(
input a,
input b,
output out
);
`ifdef add //宏名为add
out <= a + b;
`else
out <= a - b;
`endif
endmodule
`ifdef 为条件编译语句,只有当程序中宏定义过`ifdef后的宏名,才进行下一步的动作。在上个程序中,即为若程序中定义过add,则进行相加处理。
22.加法计数器中的进程
module count(
input clk,
input reset,
input load,
input [3:0] data,
output cout,
output reg [3:0] qout
);
always@(posedge clk) begin
if(reset) //同步清零
qout <= 4'b0;
else if (load) //同步置位
qout <= data;
else
qout <= qout + 4'b1;
end
assign cout = (qout == 4'hf)?1:0;//第二进程输出进位
endmodule
23.任务举例
module alutask(
input [1:0] code,
input [3:0] a,
input [3:0] b,
output reg [4:0] c,
);
task my_and;//任务定义,无输出输出端口列表
input [3:0] a,b;
output [4:0] out;
integer i;
begin
for(i = 3;i >= 0; i = i - 1)
out[i] = a[i] & b[i];
end
endtask
// ===================================
// 调用task,需注意端口的列表需要与定义的端口顺序相同
// ===================================
always@(code or a or b)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; //加
default :c = 5'b0;
endcase
end
endmodule
24.函数举例
function [7:0] get0;
input [7:0] x;
reg [7:0] count;
integer i;
begin
count = 0;
for(i = 0;i <= 7;i = i + 1 )
if(x[i] = 1'b0)
count = count + 1;
else
count = count;
get0 = count;
end
endfunction
25.阶乘运算函数
module funct(
input clk,
input [3:0] n,
input reset,
output[31:0] result
);
always@(posedge clk)begin
if(result)
result <= 32'b0;
else
result <= 2 * factorial(n);
end
function [31:0]factorial;
input [3:0] opa;
reg [3:0] i;
begin
factorial = opa ? 1 : 0;
for(i = 2; i <= opa; i = i + 1)
factorial = i * factorial;
end
endfunction
ebdmodule