VHDL coding tips and tricks: Variables and Shared Variables
Contact me for VHDL or Verilog projects and assignments

Tuesday, March 9, 2010

Variables and Shared Variables

Variables :
Variables declared in a function are initialized every time a call is made to the function, but it is initialized only once when used inside a process. Values of variables do not persist between function calls.Functions use variables only to store intermediate values.A signal's value is updated only after a small time interval,but in case of variables the data is updated instantly.
These things should be kept in memory when you are opting between signals and variables.The design may not work as you have expected,if you write your code without keeping these things in mind.
Variables are assigned and changed using the ":=" operator.

--for example:
variable var_name : integer :=0;
Variables are synthesizable.

Shared Variables :
      Shared variables are specific type of variables which can be used in two processes at the same time.But they are not synthesizable.Using shared variables is risky sometimes.You should take care that when one process is using the shared variable the other process should not use it.Otherwise simulation will terminate.

3 comments:

  1. "Variables are reset each time the function or process is called."

    No they aren't!

    ReplyDelete
  2. For a process - the variable can be used within that process only.And you have to initialize that variable during declaration.So whenever the process in evoked the variable get initialized to its old value.
    process(clk)
    begin
    variable example : integer :=0;
    --other statements;
    end process;
    Now each time clk changes your variable value get initialized to zero.Am I wrong here?

    Now for the function,the same rule goes.Function is a combinatorial block.Variable is declared inside this block.So whenever a function is executed the variable gets initialized back to its old value.For example:
    function add (a : std_logic_vector(2 downto 0); b: std_logic_vector(2 downto 0)) return std_logic_vector is
    variable sum : std_logic_vector(2 downto 0):="000";
    variable i : integer:=0;
    begin
    if(i < 3) then
    sum(i):=a(i) or b(i);
    i := i+1;
    end if;

    Here I am expecting the result "sum <= a or b" but I will get only "sum(0) <=a(0) or b(0)".Because the value of variable 'i' never goes beyond 1.

    ReplyDelete
  3. But I can agree that,I cant use the term "function is called" here.Because unlike C or any other programming language VHDL is not sequential.Its concurrent,hardware description language.Just like in a digital circuit you cant call a block to get executed,its not possible to do it in VHDL.If you don't want some statements ,to not get executed then you have to give conditions using 'if statement' etc...

    ReplyDelete