Last active
November 3, 2022 16:59
-
-
Save nebs/4d219cdf97ccd7afcbbd to your computer and use it in GitHub Desktop.
Arduino random seed with EEPROM
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Arduino's random() function repeats when the program resets. | |
The typical solution is to seed it with a floating analog pin reading. | |
The problem with that is that the analog pin is not really random either | |
so you still end up with sequences that repeat fairly frequently. It also | |
requires you to give up an analog pin. | |
This gist attempts to solve these problems by storing the previous seed | |
in EEPROM and incrementing it each time the program resets. | |
It stores a 16-bit word so the seed will repeat every 65,536 resets. | |
Keep in mind that the EEPROM writes are limited to ~100,000. | |
*/ | |
#include <avr/eeprom.h> | |
void setup() { | |
uint16_t seed = eeprom_read_word(0); | |
randomSeed(seed++); | |
eeprom_write_word(0, seed); | |
} | |
void loop() { | |
random(0, 100); // use random() as you normally would | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment