You are on page 1of 9

Function and Task Examples

module andfunc(in1,in2);
input [3:0] in1,in2;
reg [3:0] regx;
always @(in1 or in2)
begin
regx=myandfunc(in1,in2);
end
function [3:0] myandfunc;
input [3:0] in1,in2;
begin
myandfunc=(in1 & in2);
end
endfunction
endmodule

module parity;
reg [31:0] addr;
reg parity;
initial addr=10101010101010101010101010101010;
always @(addr)
begin
parity=calc_parity(addr);
$display("Parity calculated =%b",calc_parity(addr));
end

function calc_parity;
input [31:0] address;
begin
calc_parity=^address;
end
endfunction
endmodule

module task_bitwise_operations;
reg a,b,c,d,e;
initial begin
a=1;
b=0;
c=1;
my_task;
end

task my_task;
begin
#20 d = a & b;
#20 e = a|c;
end
endtask
endmodule


module sequence;
reg clock;
initial
init_seq;
always
begin
asymmetric_seq;
end

task init_seq;
begin
clock=1'b0;end
endtask
task asymmetric_seq;
begin
#12 clock = 1'b0;
#5 clock = 1'b1;
#3 clock = 1'b0;
#10 clock = 1'b1;
end
endtask
endmodule
module div_func;
reg[7:0]a,b,q,r;
initial
begin
a=5;b=3;
do_it;
a=187;b=3;
do_it;
a=255;b=18;
do_it;
end
task do_it;
begin
{q,r}=div(a,b);
$display("%d goes in to %d ,%d times with a remainder of %d",a,b,q,r);
$display("%d /%d = %d",a,b,q);
$display("%d mod %d = %d",a,b,r);
end
endtask
function [15:0]div;
input [7:0]dividend,divisor;
reg [7:0] quotient,reminder;

begin
quotient = dividend/divisor;
reminder = dividend%divisor;

div = {quotient,reminder};

end
endfunction
endmodule






module adder_8bit (input [7:0]a ,b,
output reg [7:0]sum,
output reg carry);


always @(*)
begin
task_adder (a,b,sum, carry);
end

task task_adder;
input [7:0]a,b;
output reg [7:0]sum;
output reg carry;
{carry,sum} = a+b ;
endtask

endmodule


// Factorial using function

module fact_fun (input [2:0]a,
output [13:0]Z);


assign Z = fact(a);

function automatic integer fact;
input [2:0]a;
begin
if (a == 0)
fact = 1;
else
fact = fact(a-1)*a;
end
endfunction

endmodule


// Count no. of 1's in given no.

module binary_task (input [4:0]a,
output reg [2:0]y);
always @(*)
begin
task_binary(a,y);
end

task task_binary;
input [4:0]a;
output [2:0]y;
begin
y = a[4] + a[3] + a[2] + a[1] + a[0];
end
endtask

endmodule


Counter Examples


module john_cnt (clk, reset, q);
parameter n = 4; // n = 4
input clk, reset;
output reg [n-1:0]q;

always @ (posedge clk)
begin
if (reset)
q = 4'b0000;
else
q <= { q[n-2:0], (~q[n-1])};
end

endmodule



module gray_cnt (clk, reset, g);
parameter n = 4; // n= 4
input clk, reset;
output reg [n-1:0]g;

reg [n-1:0]a;
wire [3:0]b;

assign b = {g[n-1], b[n-1:1]^g[n-2:0]};

always @ (posedge clk)
begin
a = b + 4'b0001;
if (reset)
g = 4'b0000;
else
g = {a[n-1], a[n-1:1]^a[n-2:0]};
end

endmodule

// Serial-In Parallel Out register

module si_po (input a,
input clk,
output reg [3:0]y);

initial y = 4'b0000;

always @ (posedge clk)
begin
y[3] <= y[2];
y[2] <= y[1];
y[1] <= y[0];
y[0] <= a;
end

endmodule

You might also like