why don't random() and randomSeed() conform to Arduino specifications? #7399
-
According to the Arduino API reference https://www.arduino.cc/reference/en/language/functions/random-numbers/randomseed/ it should be possible to create a repeatable sequence of pseudo-random numbers based on the same seed being used. This does not seem to work on ESP32. Poking around, it looks like it is implemented here It looks like it is based on esp_random() which uses noise to more "truly" randomize numbers. This might seem like a good idea, but it actually breaks documented behavior. The spec even suggests: "it can occasionally be useful to use pseudo-random sequences that repeat exactly." I think it would be better to keep the defined Arduino behavior and give the user a way to opt for the ESP32 style randomization if desired, or perhaps documenting a technique to do so, such as setting a seed based on esp_random(). |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Well spotted @rsiemens77! This issue also used to exist in the ESP8266 Arduino core. On one hand, some libraries in the Arduino ecosystem used the The solution which was implemented in the ESP8266 Arduino core was to use the HW RNG unless Relevant links:
I think the same approach could be applied in the arduino-esp32 project. |
Beta Was this translation helpful? Give feedback.
-
in general, always the highest possible Arduino-code-compatibilty is needed, in any respect. |
Beta Was this translation helpful? Give feedback.
Well spotted @rsiemens77!
This issue also used to exist in the ESP8266 Arduino core. On one hand, some libraries in the Arduino ecosystem used the
random
function inappropriately to generate some secrets or keys, hence it was desirable to make the source of these numbers truly random. On the other hand, there was the concern you have mentioned — sometimes it's desirable to have a repeatable pseudorandom sequence, for example in games.The solution which was implemented in the ESP8266 Arduino core was to use the HW RNG unless
randomSeed
function was called. This was based on the observation that libraries didn't usually callrandomSeed
, and only calledrandom
. So callingrandomSeed
was an …