Monday, August 12, 2013

Functions in VHDL

FUNCTIONS IN VHDL :-

SYNTAX :
function <function-name>( Argument list ) return <return-type> is
-- variable or constant declaration (no signals are allowed here) --
begin
-- function body (sequential statements)--
end <function-name>;

Examples of function :

(Example 1) LRSHIFT() -> logical right shift function.
 function LRSHIFT( val ,shifts: integer ) return integer is  
 variable vect : std_logic_vector(31 downto 0);  
 variable p : integer;  
 begin  
 vect := CONV_STD_LOGIC_VECTOR(val,32);  
 for i in 0 to shifts loop  
 vect := '0'&vect(31 downto 1);  
 end loop;  
 p := CONV_INTEGER(vect);  
 return p;  
 end LRSHIFT;  

(Example 2) TO_STD_LOGIC() -> convert character to std_logic.
 function TO_STD_LOGIC(c: character) return std_logic is  
 variable sl: std_logic;  
 begin  
 case c is  
 when 'U' =>  
          sl := 'U';  
 when 'X' =>  
          sl := 'X';  
 when '0' =>  
         sl := '0';  
 when '1' =>  
         sl := '1';  
 when 'Z' =>  
         sl := 'Z';  
 when 'W' =>  
         sl := 'W';  
 when 'L' =>  
         sl := 'L';  
 when 'H' =>  
         sl := 'H';  
 when '-' =>  
        sl := '-';  
 when others =>  
        sl := 'X';  
 end case;  
 return sl;  
 end TO_STD_LOGIC;  

(Example 3) analogToDigital() -> analog to digital converter for ADC (step size 1).

 function analogToDigital(analogin: integer) return std_logic_vector is  
 variable anIp: integer;  
 variable vect: std_logic_vector(WIDTH-1 downto 0); --WIDTGH:=8  
 begin  
 if (SIGN = 1) then -- binary signed rep --  
 anIp := analogin + 2**(WIDTH-1);  
 else  
 anIp := analogin;  
 end if;  
 vect := CONV_STD_LOGIC_VECTOR(anIp,WIDTH);  
 return vect;  
 end analogToDigital;  

(Example 4) PRINT_ERR_MSG -> function without arguments
 function PRINT_ERR_MSG return boolean is  
 begin  
  report "ERROR !! simluation stopped"; --prints to stdout--  
  return true;  
 end PRINT_ERR_MSG;  

No comments:

Post a Comment