Skip to content

Adds pseudo random numbers generation #7848

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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