diff --git a/cores/esp32/Arduino.h b/cores/esp32/Arduino.h index 8b0aa220d98ab4d0b68d65751500d285e3ec9ed4..2dc0d543489f5121a5c95817a21f8ba9a077fe7d 100644 --- a/cores/esp32/Arduino.h +++ b/cores/esp32/Arduino.h @@ -137,9 +137,19 @@ typedef unsigned int word; void setup(void); void loop(void); +// The default is using Real Hardware random number generator +// But when randomSeed() is called, it turns to Psedo random +// generator, exactly as done in Arduino mainstream +long random(long); long random(long, long); -#endif +// Calling randomSeed() will make random() +// using pseudo random like in Arduino void randomSeed(unsigned long); +// Allow the Application to decide if the random generator +// will use Real Hardware random generation (true - default) +// or Pseudo random generation (false) as in Arduino MainStream +void useRealRandomGenerator(bool useRandomHW); +#endif long map(long, long, long, long, long); #ifdef __cplusplus @@ -207,8 +217,6 @@ void setToneChannel(uint8_t channel = 0); void tone(uint8_t _pin, unsigned int frequency, unsigned long duration = 0); void noTone(uint8_t _pin); -// WMath prototypes -long random(long); #endif /* __cplusplus */ #include "pins_arduino.h" diff --git a/cores/esp32/WMath.cpp b/cores/esp32/WMath.cpp index 078e18a876795634e138f1f4b7dc7e8ce391effa..68cbb0c5dbb6c7979ecaad825de7008039dfd5ef 100644 --- a/cores/esp32/WMath.cpp +++ b/cores/esp32/WMath.cpp @@ -29,10 +29,22 @@ extern "C" { } #include "esp32-hal-log.h" +// Allows the user to choose between Real Hardware +// or Software Pseudo random generators for the +// Arduino random() functions +static bool s_useRandomHW = true; +void useRealRandomGenerator(bool useRandomHW) { + s_useRandomHW = useRandomHW; +} + +// Calling randomSeed() will force the +// Pseudo Random generator like in +// Arduino mainstream API void randomSeed(unsigned long seed) { if(seed != 0) { srand(seed); + s_useRandomHW = false; } } @@ -46,7 +58,9 @@ long random( long howbig ) if (howbig < 0) { return (random(0, -howbig)); } - return esp_random() % howbig; + // if randomSeed was called, fall back to software PRNG + uint32_t val = (s_useRandomHW) ? esp_random() : rand(); + return val % howbig; } long random(long howsmall, long howbig)