Arduino: Random Numbers & Delay – RandomSeed

A randomSeed(analogRead(0)) in Arduino initializes the pseudo-random number generator that reads the random analog noise from an unconnected analog pin 0 and floats to relatively random values between 0 and 1023.

This shuffles the random() number generator each time you start the Arduino sketch.

In this note i will show the examples of how to generate random numbers and create random delays in Arduino using the randomSeed() and random() functions.

Cool Tip: Simulate keystrokes using the Arduino boards! Read more →

Random Numbers & Delay in Arduino

A simple example of how to generate random numbers in Arduino and print them to the serial console:

void setup() {
  Serial.begin(9600);
  randomSeed(analogRead(0));
}

void loop() {
  // print a random number from 0 to 99
  Serial.println(random(100));

  // print a random number from 100 to 199
  Serial.println(random(100, 200));

  delay(1000);
}

Use the following code snippet in Arduino to print messages to the serial console with random delays:

void setup() {
  Serial.begin(9600);
  randomSeed(analogRead(0));
}

void loop() {
  // print a message with a random delay from 0 to 1000 milliseconds
  Serial.println("Ping!");
  delay(random(1000));

  // print a message with a random delay from 1000 to 60000 milliseconds
  Serial.println("Pong!");
  delay(random(1000; 60000));
}