random()

Description

The random function generates pseudo-random numbers.

Syntax

random(max)

random(min, max)

Parameter Values

  • min: lower bound of the random value, inclusive (optional).
  • max: upper bound of the random value, exclusive.

Return Values

  • A random number between min and max-1. Data type: long.

Example Code

The code generates random numbers and displays them on Serial Monitor.

long randNumber; void setup() { Serial.begin(9600); // if analog input pin 0 is unconnected, random analog // noise will cause the call to randomSeed() to generate // different seed numbers each time the sketch runs. // randomSeed() will then shuffle the random function. randomSeed(analogRead(0)); } void loop() { // print a random number from 0 to 299 randNumber = random(300); Serial.print("A random number from 0 to 299: "); Serial.println(randNumber); // print a random number from 10 to 19 randNumber = random(10, 20); Serial.print("A random number from 10 to 19: "); Serial.println(randNumber); delay(1000); }
  • The result on Serial Monitor:
COM6
Send
A random number from 0 to 299: 52 A random number from 10 to 19: 15 A random number from 0 to 299: 165 A random number from 10 to 19: 15 A random number from 0 to 299: 276 A random number from 10 to 19: 17 A random number from 0 to 299: 244 A random number from 10 to 19: 13 A random number from 0 to 299: 216 A random number from 10 to 19: 15 A random number from 0 to 299: 91
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  

※ 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

ARDUINO BUY RECOMMENDATION

Arduino UNO R3
Arduino Starter Kit
Please note: These are Amazon affiliate links. If you buy the components through these links, We will get a commission at no extra cost to you. We appreciate it.

※ OUR MESSAGES