How to generate random number in your Arduino Program?
In this course we will see how to generate a random number in your Arduino Program by using the random function:
random(min,max)
The random function has two parameter : a minimum and maximum number. The function will generate a number between this range.
Here is an example:
voidsetup(){Serial.begin(9600);//We initalize the serial monitor On initalise le moniteur série
int random_number=random(1,100);//We generate a random number between 1 and 100 Serial.println(random_number);// We display the random number}voidloop(){}
In our example, the number chosen can’t be equal to the maximum number you gave, in our case 100. The maximum random number chosen can be max-1 which mean 99 in our case.
As you may know, it is not as easy to have a real random number in programming language. That’s why in Arduino there a function called randomSeed which permits to change the way that’s a random number is generate.
randomSeed()
The Randomseed function is used to create a new group of random numbers from a stable number. This number can be from an Analog input of the arduino card or a number that you choose by yourself. We will see now an example of it:
voidsetup(){Serial.begin(9600);//We initialize the serial monitor randomSeed(1);//We initialize the new group with the number 1
int random_number =random(0,50);//We generate our random numberSerial.println(raldom_number);// We display the number }voidloop(){}
By changing the number in random Seed, we have a new group of number and we have new random number.