Language: EN

esp32-random-numbers

Generate True Random Numbers on ESP32

The ESP32 has a hardware random number generation (RNG Random Number Generator) module 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 security and cryptography-related applications.

The ESP32’s RNG module uses the noise from the WiFi and Bluetooth RF subsystem 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 depend 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 Arduino Random() function to internally use esp_random()

So, for practical purposes, we can generate random numbers in the same way as 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 random core of the ESP32.