Search code examples
randomnumbersvhdl

How can I get random numbers between -1024 and 1024 in vhdl


I am really beginner in VHDL and I am trying to make a hot-n-cold game. My first goal is generating numbers between -1024 and 1024 so that I can use 10 switches to guess. However, there are a lot of sources about positive integers but I could not find any for negative ones. Here is a sample code of mine. Also, someone says LFSR does this job but I am new and I could not understand the behavior of LFSR.

library ieee;
use ieee.math_real.all;

entity rand_gen is
end rand_gen;

architecture behavior of rand_gen is 

signal rand_num : integer := 0;

begin

process
    variable seed1, seed2: positive;              
    variable rand: real;   
    variable range_of_rand : real := 1024.0;   
begin
    uniform(seed1, seed2, rand);   
    rand_num <= integer(rand*range_of_rand);  
    wait for 10 ns;
end process;

end behavior;

Solution

  • Please have a look at Open Source VHDL Verification Methodology. This framework offers many packages to ease writing of testbenches. For instance there is a RandomPkg VHDL package, that offers lots of randomization procedures, functions and a protected type for constrained random: RandInt(min, max).

    process
      variable RV : RandomPType;
    begin
      RV.Init("dkudbcsdkbcfsdbcfdsyc");   -- create a seed value
    
      for in i 0 to 15 loop
        rand_num <= RV.RandInt(-1024, 1024);
        wait until rising_edge(Clock);
      end loop;
    end process;
    

    The protected type will take care of handling the two seed integers, that you would need to handle manually if you use ieee.math_real.uniform(...)