The ESP32 features a hardware random number generation module (RNG Random Number Generator) that allows for the generation of high-quality random numbers.
Generating random numbers is a common task in programming, but it is especially important in applications related to security and cryptography.
The ESP32’s RNG module uses noise from the RF subsystem of WiFi and Bluetooth to generate true random numbers, which are suitable for use in cryptographic applications.
If both subsystems are disabled, the ESP32’s RNG module simply generates pseudo-random numbers. These should not be used for functions that rely on security.
How to generate random numbers on ESP32
To use the ESP32’s RNG module in our code, we can generate a random number using the esp_random()
function, which returns a 32-bit integer (between 0 and 4294967295).
void setup()
{
Serial.begin(115200);
}
void loop()
{
auto randomNumber = esp_random();
Serial.println(randomNumber);
delay(2000);
}
However, in adapting the ESP32 to the Arduino environment, they have been smart enough to modify the Random()
function of Arduino, so that it internally uses esp_random()
Therefore, for practical purposes, we can generate random numbers in the same way we would on a “conventional” Arduino. For example like this.
void setup()
{
Serial.begin(115200);
}
void loop()
{
auto randomNumber0_10 = random(10); // random number between 0-10
auto randomNumber10_20 = random(10, 20); // random number between 10-20
Serial.println(randomNumber0_10);
Serial.println(randomNumber10_20);
delay(1000);
}
Internally we will be using esp_random()
, so we will also be taking advantage of the random core of the ESP32.