Using a 'random' function in sketch gives same pattern of numbers every-time. But, I need to generate different numbers such that any number to repeat itself should have a very less probability.
-
If you just want random data (but not true random data, only random pseudo-random data) follow Edgar Bonet solution. Read this article and, of course, the wikipedia page to better understand this. However, unless your application is very particular, you won't need true randomness, because pseudo-random numbers are fine for almost every application– frarugi87Mar 29, 2016 at 8:55
-
Related: arduino.stackexchange.com/questions/50671/…– RexcirusFeb 20 at 10:16
2 Answers
The standard (but not very good) solution is to seed the random number generator from an analogRead()
on an unconnected pin. For better options, see this answer to a related question.
-
1This, however, is not a "true random numbers generator", it's a randomly seeded pseudo-random generator. This, however, is what I think the OP was requestiong, so +1 Mar 29, 2016 at 8:50
Allocate 4 bytes in EEPROM to save a seed value.
Use the EEPROM library (#include ). Use EEPROM.put() and EEPROM.get() functions to write and read the seed value to EEPROM.
In setup(): Read the seed_value from EEPROM, increment it and write it back to EEPROM. Then call randomSeed(seed_value).
Now, after every run of setup(), random() will create a whole new random sequence. If you need a new sequence within your sketch, you can repeat the process, and don't forget to write the new seed to EEPROM for next time.
Note that I didn't bother with initialising the EEPROM value the first time we run. It'll probably be zero when you start a new Arduino board, but the only thing that matters is that you increment it each run. Incrementing by 1 will do the trick, but any increment value will probably do.
-
I notice that the title said "true random", but the question asked for something different. My suggestion solves the request, but it's not a "true random" generator, of course. Jun 13, 2016 at 7:15
-
-
Oh? I thought I remembered finding zeros up there, but it doesn't matter in this case. Thanks. Jun 14, 2016 at 7:45