diff --git a/src/Arduboy2.cpp b/src/Arduboy2.cpp index 2672fcb..fc38443 100644 --- a/src/Arduboy2.cpp +++ b/src/Arduboy2.cpp @@ -275,7 +275,7 @@ int Arduboy2Base::cpuLoad() return lastFrameDurationMs*100 / eachFrameMillis; } -void Arduboy2Base::initRandomSeed() +unsigned long Arduboy2Base::generateRandomSeed() { power_adc_enable(); // ADC on @@ -283,9 +283,16 @@ void Arduboy2Base::initRandomSeed() ADCSRA |= _BV(ADSC); // start conversion (ADMUX has been pre-set in boot()) while (bit_is_set(ADCSRA, ADSC)) { } // wait for conversion complete - randomSeed(((unsigned long)ADC << 16) + micros()); + unsigned long seed = (static_cast(ADC) << 16) + micros(); power_adc_disable(); // ADC off + + return seed; +} + +void Arduboy2Base::initRandomSeed() +{ + randomSeed(generateRandomSeed); } /* Graphics */ diff --git a/src/Arduboy2.h b/src/Arduboy2.h index 9b86f4a..10e20c1 100644 --- a/src/Arduboy2.h +++ b/src/Arduboy2.h @@ -692,6 +692,19 @@ class Arduboy2Base : public Arduboy2Core */ uint8_t* getBuffer(); + /** \brief + * Create a seed suitable for use with a random number generator. + * + * \details + * The seed is generated with a random value derived from entropy from an + * ADC reading of a floating pin combined with the microseconds since boot. + * + * This method is still most effective when called after a semi-random time, + * such as after a user hits a button to start a game or other semi-random + * event. + */ + unsigned long generateRandomSeed(); + /** \brief * Seed the random number generator with a random value. *