Skip to content

Commit 1e3717b

Browse files
authored
Adds pseudo random numbers generation (#7848)
1 parent 8873adb commit 1e3717b

File tree

2 files changed

+26
-4
lines changed

2 files changed

+26
-4
lines changed

Diff for: cores/esp32/Arduino.h

+11-3
Original file line numberDiff line numberDiff line change
@@ -137,9 +137,19 @@ typedef unsigned int word;
137137
void setup(void);
138138
void loop(void);
139139

140+
// The default is using Real Hardware random number generator
141+
// But when randomSeed() is called, it turns to Psedo random
142+
// generator, exactly as done in Arduino mainstream
143+
long random(long);
140144
long random(long, long);
141-
#endif
145+
// Calling randomSeed() will make random()
146+
// using pseudo random like in Arduino
142147
void randomSeed(unsigned long);
148+
// Allow the Application to decide if the random generator
149+
// will use Real Hardware random generation (true - default)
150+
// or Pseudo random generation (false) as in Arduino MainStream
151+
void useRealRandomGenerator(bool useRandomHW);
152+
#endif
143153
long map(long, long, long, long, long);
144154

145155
#ifdef __cplusplus
@@ -207,8 +217,6 @@ void setToneChannel(uint8_t channel = 0);
207217
void tone(uint8_t _pin, unsigned int frequency, unsigned long duration = 0);
208218
void noTone(uint8_t _pin);
209219

210-
// WMath prototypes
211-
long random(long);
212220
#endif /* __cplusplus */
213221

214222
#include "pins_arduino.h"

Diff for: cores/esp32/WMath.cpp

+15-1
Original file line numberDiff line numberDiff line change
@@ -29,10 +29,22 @@ extern "C" {
2929
}
3030
#include "esp32-hal-log.h"
3131

32+
// Allows the user to choose between Real Hardware
33+
// or Software Pseudo random generators for the
34+
// Arduino random() functions
35+
static bool s_useRandomHW = true;
36+
void useRealRandomGenerator(bool useRandomHW) {
37+
s_useRandomHW = useRandomHW;
38+
}
39+
40+
// Calling randomSeed() will force the
41+
// Pseudo Random generator like in
42+
// Arduino mainstream API
3243
void randomSeed(unsigned long seed)
3344
{
3445
if(seed != 0) {
3546
srand(seed);
47+
s_useRandomHW = false;
3648
}
3749
}
3850

@@ -46,7 +58,9 @@ long random( long howbig )
4658
if (howbig < 0) {
4759
return (random(0, -howbig));
4860
}
49-
return esp_random() % howbig;
61+
// if randomSeed was called, fall back to software PRNG
62+
uint32_t val = (s_useRandomHW) ? esp_random() : rand();
63+
return val % howbig;
5064
}
5165

5266
long random(long howsmall, long howbig)

0 commit comments

Comments
 (0)