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](https://boallen.com/random-numbers.html) and, of course, [the wikipedia page](https://en.wikipedia.org/wiki/Pseudorandomness) 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 – frarugi87 Mar 29 '16 at 08:55
-
Related: https://arduino.stackexchange.com/questions/50671/getting-a-truly-random-number-in-arduino – Rexcirus Feb 20 '23 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.
- 39,449
- 4
- 36
- 72
-
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 – frarugi87 Mar 29 '16 at 08: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.
- 11
- 1
-
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. – Joe Weisman Jun 13 '16 at 07:15
-
-
Oh? I thought I remembered finding zeros up there, but it doesn't matter in this case. Thanks. – Joe Weisman Jun 14 '16 at 07:45