random()
Description
The random function generates pseudo-random numbers.
Syntax
random(max)
random(min, max)
Parameters
: lower bound of the random value, inclusive (optional)min
: upper bound of the random value, exclusivemax
Returns
A random number between min and max-1. Data type:
long
.Example Code
The code generates random numbers and displays them.
1long randNumber;2
3 void setup() {4 Serial.begin(9600);5
6 // if analog input pin 0 is unconnected, random analog7 // noise will cause the call to randomSeed() to generate8 // different seed numbers each time the sketch runs.9 // randomSeed() will then shuffle the random function.10 randomSeed(analogRead(0));11 }12
13 void loop() {14 // print a random number from 0 to 29915 randNumber = random(300);16 Serial.println(randNumber);17
18 // print a random number from 10 to 1919 randNumber = random(10, 20);20 Serial.println(randNumber);21
22 delay(50);23 }
Notes and Warnings
If it is important for a sequence of values generated by
random()
to differ, on subsequent executions of a sketch, use randomSeed()
to initialize the random number generator with a fairly random input, such as analogRead()
on an unconnected pin.Conversely, it can occasionally be useful to use pseudo-random sequences that repeat exactly. This can be accomplished by calling
randomSeed()
with a fixed number, before starting the random sequence.The
max
parameter should be chosen according to the data type of the variable in which the value is stored. In any case, the absolute maximum is bound to the long
nature of the value generated (32 bit - 2,147,483,647). Setting max
to a higher value won’t generate an error during compilation, but during sketch execution the numbers generated will not be as expected.See also
Suggest changes
The content on docs.arduino.cc is facilitated through a public GitHub repository. If you see anything wrong, you can edit this page here.
License
The Arduino documentation is licensed under the Creative Commons Attribution-Share Alike 4.0 license.