- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
Hi,
i would like to know how to generate a random number by using C. I wrote the following code :
srand(time(NULL));
int x = rand()%(4-1)+1;
printf("%d", x);
However, the generated numbers are always the same. It must be because of the seed which is given by the time. Because there is no memory of the time on the FPGA, the seed is always the same. Would you have a simple solution for me or could you help me to bypass my problem ? Thanks !
Link Copied
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
To try and randomize the seed a bit more you would need to have your software do something that can take a variable amount of time or give different results each time it is called, such as waiting for a network packet or user input from the terminal. Only then use the value of a counter to initialize the random seed. The time function will also probably only work if you have a system timer in your system. If you need more randomness, you could also put a fast timer (that doesn't generate interrupts) and use the value of that fast timer as seed. But you still need to depend on an external event that can take a variable amount of time.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
If you don't need a very good random number (and rand() doesn't give you one of those - especially seeded from time()), and you code isn't running a really well determined time after fpga reset, you might get a good enough number by having counted the clocks since reset and using that instead.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
Thank you for your answers, they really helped me :)
What i did is that is ask the user to press a button to start using the program. Until the user presses the button, a variable increments itself. I show you my code :
do
{
if(*switches==0)
{
LCD_Test("Switch up SW0", "To continue");
while(*switches==0)
{
if(highPrecisionTimer>100000000)
highPrecisionTimer=0;
highPrecisionTimer++;
}
keepGoing = 1;
}
else if(*switches==1)
{
LCD_Test("Switch down SW0", "To continue");
while(*switches==1)
{
if(highPrecisionTimer>100000000)
highPrecisionTimer=0;
highPrecisionTimer++;
}
keepGoing = 1;
}
}while(keepGoing != 1);
srand(highPrecisionTimer);
So now my rand() function works. Thank you !

- Subscribe to RSS Feed
- Mark Topic as New
- Mark Topic as Read
- Float this Topic for Current User
- Bookmark
- Subscribe
- Printer Friendly Page