Random Numbers
Syntax#
-
random(max) //Returns a (long) pseudo-random number between 0 (inclusive) and max (exclusive)
-
random(min, max) //Returns a (long) pseudo-random number between min (inclusive) and max (exclusive)
-
randomSeed(seed) //Initializes de pseudo-random number generator, causing it to start at a specified point in its sequence.
Parameters#
Parameter | Details |
---|---|
min | The minimum possible value (inclusive) to be generated by the random() function. |
max | The maximum possible value (exclusive) to be generated by the random() function. |
seed | The seed that will be used to shuffle the random() function. |
## Remarks# | |
If randomSeed() is called with a fixed value (eg. randomSeed(5) ), the sequence of random numbers generated by the sketch will repeat each time it is run. In most cases, a random seed is preferred, which can be obtained by reading an unconnected analog pin. |
|
## Generate a random number | |
The random() function can be used to generate pseudo-random numbers: |
void setup() {
Serial.begin(9600);
}
void loop() {
long randomNumber = random(500); // Generate a random number between 0 and 499
Serial.println(randomNumber);
randomNumber = random(100, 1000); // Generate a random number between 100 and 999
Serial.println(randomNumber);
delay(100);
}
Setting a seed
If it is important for a sequence of numbers generated by random()
to differ, it is a good idea to specify a seed with randomSeed()
:
void setup() {
Serial.begin(9600);
// If analog pin 0 is left unconnected, analogRead(0) will produce a
// different random number each time the sketch is run.
randomSeed(analogRead(0));
}
void loop() {
long randomNumber = random(500); // Generate a random number between 0 and 499
Serial.println(randomNumber);
delay(100);
}