how to create and use functions in VHDL

This is a continuation of the tutorial- how to create and use functions in VHDL. In this tutorial we show how a function can be declared inside an entity section. In the last two tutorials we showed how a function can be declared in a package and how a function can be declared inside the architecture.

The code below is the function we created that accepts two inputs of the type std_logic_vector and outputs one parameter also of the type std_logic_vector.

FUNCTION myAdder(signal f1,f2: STD_LOGIC_vector(3 downto 0)) return std_logic_vector IS
    variable sum_int : integer := 0;
    variable sum : std_logic_vector(3 downto 0) := "0000";
BEGIN
 
    sum_int := to_integer(unsigned(f1)) + to_integer(unsigned(f2));
 
    sum := std_logic_vector(to_unsigned(sum_int,4));
 
    return sum;
 
END FUNCTION myAdder;

As you might already guessed from the two earlier tutorials, once you have create the function VHDL code, the placement of the function is just matter of copying and pasting the code inside a package or architecture declarative part. The placement of function code in entity is similar of that of architecture method. The function code is just placed after the port declaration and the function is called in the architecture after the begin keyword.

 The following shows where to place the function code in the function declaration in entity method:

 library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity function_test is
    port(
    a : in std_logic_vector(3 downto 0);
    b : in std_logic_vector(3 downto 0);
    y : out std_logic_vector(3 downto 0)
    );
 
FUNCTION myAdder(signal f1,f2: STD_LOGIC_vector(3 downto 0)) return std_logic_vector IS
    variable sum_int : integer := 0;
    variable sum : std_logic_vector(3 downto 0) := "0000";
BEGIN
 
    sum_int := to_integer(unsigned(f1)) + to_integer(unsigned(f2));
 
    sum := std_logic_vector(to_unsigned(sum_int,4));
 
    return sum;
 
END FUNCTION myAdder;

end function_test;

architecture model of function_test is

begin
 
    y <= myAdder(a, b);

end model;

 There is difference in the package method though. In the package method, we declared the function header inside the package header and the whole function(header and body) inside the package body.

In case of entity and architecture method, the whole function code(header and body) is declared inside the entity or architecture whichever method is used. 

Related Posts by Categories

0 comments:

Post a Comment

Powered by Blogger.