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; } |
Here’s the final effect:
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!
hi, that is a built-in (in the ESP-IDF framework) function to use the hardware number generator and obtain a random value.
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);