Nios® V/II Embedded Design Suite (EDS)
Support for Embedded Development Tools, Processors (SoCs and Nios® V/II processor), Embedded Development Suites (EDSs), Boot and Configuration, Operating Systems, C and C++
12603 Discussions

Generate a random number with C

Altera_Forum
Honored Contributor II
1,479 Views

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 !
0 Kudos
3 Replies
Altera_Forum
Honored Contributor II
694 Views

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.

0 Kudos
Altera_Forum
Honored Contributor II
694 Views

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.

0 Kudos
Altera_Forum
Honored Contributor II
694 Views

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 !
0 Kudos
Reply