Skip to content

Commit

Permalink
Adds pseudo random numbers generation (#7848)
Browse files Browse the repository at this point in the history
  • Loading branch information
SuGlider authored Feb 15, 2023
1 parent 8873adb commit 1e3717b
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 4 deletions.
14 changes: 11 additions & 3 deletions cores/esp32/Arduino.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"
Expand Down
16 changes: 15 additions & 1 deletion cores/esp32/WMath.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}

Expand All @@ -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)
Expand Down

0 comments on commit 1e3717b

Please sign in to comment.