I think the example for Retro uses the ADC to do it.
If you do not seed the random number generator somewhat randomly you will get the same list of “random numbers” every time you run your program from what I understand.
It is important to seed the random number generator with a “random” number. Normally I used time() but in a desktop application or system with an OS which has a rather random program start time.
The Retro code uses the Adc input (probably from an open pin? as I have not checked).
Time is probably a bad idea for our application because the ARM chip boots up in a fixed amount of time every time (relatively the same amount of time … ms level not ns).
Maybe you should try seeding it with time when the user presses a key or if you don’t have that with a button press or something… That way you start with something random.
I found this tidbit on what might be inside the rand() function on the mbed platform:
Also you can add more randomness by swapping around the order you call the random function in with a random switch statement
Using an ADC input is a good plan for getting a random number but realistically only the least significant few bits are going to be random.
This is the code I used on my mbuino dice program:
// create a 32 bit number out of 32 LSBs from the ADC
uint32_t seedValue = 0;
uint16_t value;
uint8_t counter;
for (counter = 0; counter < 32; counter++) {
seedValue = seedValue<<1;
value = RandomIn.read_u16(); // reads a 10 bit ADC normalised to 16 bits.
if (value & 0x0040) // LSB of ADC output is a 1
seedValue++;
}
srand(seedValue); // seed the random generator with the background noise of an analog input
Once running I also had a truly random input, a person, so rather than using every random number generated I calculated a number based on the time in microseconds between two user inputs and threw that many results away each time I needed a number.
Not the most cpu efficient method but it does avoid any potential patterns in the numbers generated.