After having published my previous article, I received some comments asking what was the purpose of a random number generator, like the one included in the esp32 chip.

Random numbers are widely used in **cryptography **and a good random number generator is very important to assure an high level of security, as well-explained in Cloudflare’s blog post. This is the reason why Expressif decided to include a RNG as an **hardware peripheral** within the esp32 chip.

Today I’m going to show you a more *frivolous *use of random numbers: I’ll use them to turn a led on/off, simulating a flame burning with random movement.

I’ve already explained in a different article the functions the *framework* includes to perform basic I/O, so the source of this example (as usual available on Github) should be easily understandable.

The led can be connected to any I/O pin: via **menuconfig** you can specify the pin you chose. To limit the current, I connected a **100ohm** resistor in series with the led:

The random numbers the chip generates go from 0 to 4294967296 (the register is indeed **32bit **wide). I therefore needed to *scale* the numbers to obtain an on/off interval between 50 and 500ms (4294967296 / 9544371 is about **450**):

uint32_t getRandomDelay() { uint32_t random = esp_random(); return 50 + random / 9544371; } |

**uniform distribution**, this means that each number in the interval 0 – 2^32 has the same probability to be generated. The function above is not the best mathematical way to

*scale*an uniform distribution, but for my purpose – light a led – I think it’s ok ;)

Here’s the final effect:

Eduard27/07/2017 at 16:41 -Hi Luca! First of all thank you for the great tutorials!

I just built and flashed the example and work as expected. It’s just that I don’t quite understand the esp_random() function. Could you please explain it in more detail?

Thanks again!

luca28/07/2017 at 12:51 -hi, that is a built-in (in the ESP-IDF framework) function to use the hardware number generator and obtain a random value.

Marius15/11/2017 at 22:20 -Hi Luca, how do you figure out the stack size?

I changed the function to:

uint32_t getRandomDelay() {

uint32_t random = esp_random();

uint32_t result2 = 50 + random / 9544371;

printf(“esp_random: %d\r\n”,result2);

return result2;

}

Why do I need to change stack_size to 2048?

xTaskCreate(&blink_task, “blink_task”, 2048, NULL, 5, NULL);