The ESP32 features a hardware Random Number Generator (RNG) module that allows generating 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 WiFi and Bluetooth RF subsystems 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 security-dependent functions.
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 the adaptation of the ESP32 to the Arduino environment, they were smart enough to modify Arduino’s Random() function so that internally it 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 still be taking advantage of the ESP32’s random core.

