Search code examples
vhdl

Assigning a signal to variable and a variable to a signal


I am new to VHDL and after I read through a lot of tutorials, I am now getting my feet wet. Here is a code example which troubles me. The trade_cell entity gets in a signed signal n which is assigned to a variable abs_n after getting the absolute. The result then is assigned to the signal amount for output.

Everytime I simulate this, amount is set to X. What am I missing here?

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;

entity trade_cell is
    Port (
        n: IN signed(31 downto 0); 
        amount: OUT signed(31 downto 0);
    );
end trade_cell;

architecture Behavioral of trade_cell is
begin

    trader: process(start, value, n, P, dP, delta, ddelta)
    variable abs_n : signed(31 downto 0) := abs(n);
begin
    amount <= abs_n; 
    end process;
end Behavioral;

With friendly regards, RincewindWizzard


Solution

  • Your problem is that this line:

        variable abs_n : signed(31 downto 0) := abs(n);
    

    is initialising the variable abs_n once at the beginning of the simulation (technically during elaboration). At this time, the signal n will have the value 'U' and abs('U') will be 'X', so the variable abs_n is initialised with the value 'X' and never assigned any value after that.

    So, instead of:

        trader: process(start, value, n, P, dP, delta, ddelta)
        variable abs_n : signed(31 downto 0) := abs(n);
    begin
        amount <= abs_n; 
        end process;
    

    you need:

        trader: process(start, value, n, P, dP, delta, ddelta)
        variable abs_n : signed(31 downto 0);
    begin
        abs_n := abs(n);  -- assign abs_n here...
        amount <= abs_n;      -- ...and use its value here
        end process;
    

    I assume you have pared down the code to make an MCVE, which is why there are many other signals in the sensitivity list of the process trader. If not, you only need the inputs to that process in the sensitivity list (in this case just n).