SALES INQUIRIES: 1 (888) 767-9864

Using Random Numbers with Arduino

This video tutorial talks about using the random() and randomSeed() functions with Arduino.  It is pretty straight forward, but there are some intricacies worth noting.

Creating truly random numbers in Arduino is harder than you might think.  The closest we can get in Arduino, and just about anywhere else, is using pseudo random numbers.  That is, numbers that mimic randomness, but in fact do have a pattern if analyzed for a long enough period.

 

Why are Random Numbers with Arduino All the Same?

The most important thing to understand when using the random() function with Arduino is that it will generate the exact same list of pseudo random numbers every time.

So if you build a slot machine, and the first crank of the handle is a winner, then you can be sure that if you reset the Arduino board and pull the handle again – it will still be a winner the first time.

Using random numbers with Arduino breadboard image

The easy way to overcome this is using the randomSeed() function.

This function takes a value (an integer for example), and uses the number to alter the random list generated by the random() function.  The number you pass to the randomSeed() function is called a ‘seed’.

You might put randomSeed() in the setup, and then use the random() function in the loop.  Something like this:

//this variable will hold a random number generated by the random() function
long randomNumber;

//Set up - this is where you get things "set-up". It will only run once
void setup() {
  
  //setup serial communications through the USB
  Serial.begin(9600);

  //Let's make it more random
  randomSeed(42);   
      
}//close setup

void loop() {
  
  //generate a random number
  randomNumber = random(2,5);
  
  //display the random number on the serial monitor
  Serial.print("The Random Number is = ");
  Serial.println(randomNumber);
  
}

But there is still an issue – even though the sequence of random numbers is different when using the randomSeed() function – it will still be the same every time the sketch is run.  It is just a different list of pseudo random numbers!

 

One Solution to the Random Problem

So, what to do?  Lucky for us the Arduino reference has a great solution.  Use the analogRead() function to read a value from an unused analog pin.  Since an unused pin that has no reference voltage attached to it is basically ‘floating’, it will return a “noise” value. This noise value can seed the randomSeed() function to produce differing  sequences of random numbers every time the sketch is run.

Random numbers with Arduino supplies list

 

Below is the sketch from the video using analogRead() and randomSeed() in unison:

/*How to use the random() and randomSeed() function

YOU WILL NEED:
 (3) LEDs
 (3) 220OHM resistors
 (1) Jumper Wire
 (4) Hot cakes
 
CIRCUIT:

Connect a resitor to pin 2 and then to a breadboard.  
Connect the long leg of an LED to the resitor and the short leg to one of the ground rails on the breadboard
Repeat this for the other components at pin 3 and 4
Coonect the ground on the breadboard to one of the Arduino GND pins.

Created JUL 2014
by Michael James
The Arduino Course
*/ //Declare and initialize LED pin variables int LED_1 = 2; int LED_2 = 3; int LED_3 = 4; //this variable will hold a random number generated by the random() function long randomNumber; //Set up - this is where you get things "set-up". It will only run once void setup() { //setup serial communications through the USB Serial.begin(9600); //Let's print a start messgae to the serial monitor when a new sequence of random numbers starts Serial.println("Starting new Random Number Sequence"); //set the LED pins as outputs pinMode(LED_1, OUTPUT); pinMode(LED_2, OUTPUT); pinMode(LED_3, OUTPUT); //Let's make it more random randomSeed(analogRead(A0)); }//close setup //The loop() runs over and over again void loop() { //generate a random number randomNumber = random(2,5); //display the random number on the serial monitor Serial.print("The Random Number is = "); Serial.println(randomNumber);

Well, hopefully that was random enough for you! If you enjoy this tutorial, I highly recommend checking out our free Arduino Crash Course (You can sign up below).

15 Comments

  1. Avatar Andy Crofts on August 16, 2014 at 3:04 am

    Of course, you could always use the method “ERNIE” uses…and has done (or did) for over 50 years…
    Wire up a zener to the analog pin without a capacitor-just resistor. 3.3V zeners are hellishly noisy!

  2. Avatar Chrips on March 25, 2015 at 1:23 pm

    Thanks, it really helped with the random numbers. Exactly what i needed.

  3. Avatar Franta Křivochcálek on September 26, 2015 at 7:50 pm

    Hi guys,
    one nice thing, when you need partial randomness and you are having all analog pins used, is… to use first human-interfaced action as seed. For example, you can use millis() of first keypress, micros() of it, duration of button pressing… In some systems, where you have no free analogs, this is good solution. Or when analogs have bigger sink current and they reads full-zeros or full-ones for almost whole time. The less noise, the more reproducible randoms:)

    • Avatar MICHAEL JAMES on October 1, 2015 at 9:28 am

      Thanks for adding this Franta – great points!

  4. Avatar Andrey Sartorius on August 29, 2017 at 12:24 am

    Very bad solution. analogRead returns integer nubmer between 0 and 1023, so, you will have only 1024 lists of sequences which is extremly low.

  5. Avatar Daniel on November 1, 2017 at 7:39 am

    I created an electronic dice. This tutorial helped a lot. Thank you!

  6. Avatar Anton Bielousov on December 19, 2017 at 1:44 pm

    Haha, I thought I was paranoid noticing that my robot’s eyes always start “randomly” moving in the same pattern 😀

    Thank you.

  7. Avatar Albert Argilaga Claramunt on January 26, 2018 at 9:05 am

    If you want TRULLY random numbers with Arduino you can use the clock drift between the two clocks of an Arduino, I explain it in the video: https://www.youtube.com/watch?v=oXMzqBsz6Dw there are also links to the original code by endolith.

  8. Avatar Bob on April 25, 2019 at 8:26 pm

    Really useful

  9. Avatar Glen on July 10, 2019 at 1:16 pm

    Is there a way to use this method to have an ON/ON toggle switch actuate a random LED as defined during the setup? And have that be a different random LED after reset?

    • Avatar Michael James on July 10, 2019 at 1:29 pm

      Great question Glen,

      So you’re saying could you have a button and when someone presses the button, it turns on a random LED? Yes this would be possible.

      You could try using digitalRead() to detect the button press, and then an “if statement” to turn off the LED that is currently on, and then randomly select another one and turn it on using the method above, or one of the methods shared in the comments.

Leave a Comment