Using random variables - masonandrewmann/MEAP GitHub Wiki
The ESP32 has both a pseudorandom number generator and a random seed generator, giving us true random number generation! Behind the scenes the ESP32 uses its wifi sensor to sense a random signal strength and uses that as a seed to its pseudorandom number generator.
The default ESP32 random number generator function is very slow and may disrupt the audio rate, so the Mozzi library provides us with another random number generator that executes faster.
The process for setting this up is as follows:
- include the mozzi random module
- generate a random seed using ESP32 randomSeed() function.
- generate a random number using ESP32 random() function
- use this random number to seed the Mozzi random function: xorshiftSeed()
- generate your random numbers using Mozzi's random number generator xorshift96()
#include <MozziGuts.h>
#include <mozzi_rand.h>
void setup() {
randomSeed(10); // this line will generate a random seed for the ESP32 random function
xorshiftSeed((long)random(1000)); // this line generates a random number using ESP32's random function and uses it as a seed for Mozzi's random algorithm
Serial.println(xorshift96()); // this will generate one true random number and print it to the serial monitor
}
The random number generated above will be a random 32-bit integer, a very large number that will be difficult to deal with. The first step towards wrangling this number is to convert it into a more reasonable data-type, like 16 bits. By storing it in a variable with the datatype uint16_t the program will truncate the extra bits and we will have a random number in the range 0 to 65,535. We can then map this number into any range we want by using the map() function whose usage is described in the potentiometer tutorial. For example, maybe we want to generate a note with a random pitch. We might set the lowest frequency we want to be 200Hz and the highest to be 2000Hz. The following lines of code will generate a random frequency within that range and use it to set the frequency of an oscillator.
uint16_t myRandom = xorshift96(); // generates a random number and converts it to a 16 bit unsigned int
myRandom = map(myRandom, 0, 65535, 200, 2000); // maps random number to range 200 -> 2000
mySine.setFreq(myRandom); // sets frequency of oscillator using mapped random number