Skip to content

Instantly share code, notes, and snippets.

@nebs
Last active November 3, 2022 16:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nebs/4d219cdf97ccd7afcbbd to your computer and use it in GitHub Desktop.
Save nebs/4d219cdf97ccd7afcbbd to your computer and use it in GitHub Desktop.
Arduino random seed with EEPROM
/*
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