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.
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.
- 45,094
- 4
- 42
- 81
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