Using Random Numbers with Arduino [SOLVED]

Are you trying to use random numbers with Arduino?

This article 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.

Pseudo random numbers 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.

randomSeed(), our solution to the random problem

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!

This doesn’t seem quite the random numbers with Arduino we were trying to achieve.

So, what to do?  

Programming Electronics Academy members, use the coding challenges in the Bread and Butter: I/O section of the Arduino Course for Absolute Beginners to drive home these basic coding skills.

Not a member yet?  Sign up here.

analogRead() to the random rescue!

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.

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

//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 message to the serial monitor when a new sequence of random numbers starts
  Serial.println("Starting new Random Number Sequence");

  //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);
}

If you compare the output when using the randomSeed from one run of the sketch to another, you’ll see it varies in the sequence.

Random numbers with Arduino is not as hard as you might have thought. Of course, this is still an approximation of randomness, but hey, to get this close to random in a couple lines of code is pretty impressive!

installing Arduino libraries

Installing Arduino Libraries | Beginners Guide

IoT sewage project

Pumping poo! An IoT sewage project

ESP32 webOTA updates

How to update ESP32 firmware using web OTA [Guide + Code]

error message Brackets Thumbnail V1

expected declaration before ‘}’ token [SOLVED]

Compilation SOLVED | 1

Compilation error: expected ‘;’ before [SOLVED]

Learn how to structure your code

23 Comments

  1. 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!

    • MICHAEL JAMES on August 18, 2014 at 8:27 am

      Awesome tip! Thanks for Andy.

    • Wil Hunter on February 13, 2021 at 10:18 am

      Hi Michael
      Is there a code available for an arduino single digit 7 segment display number generator. That can be operated push button.

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

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

  3. 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:)

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

      Thanks for adding this Franta – great points!

  4. 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.

    • Heikki Hietala on December 23, 2020 at 4:15 pm

      Suppose you read A1 too and multiply A0 by it for seeding. That should be a large enough pool.

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

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

  6. 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. 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. Bob on April 25, 2019 at 8:26 pm

    Really useful

  9. 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?

    • 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.

      • Autelio on August 13, 2019 at 5:57 pm

        Great stuff! Im actually here because of the same question Glen brought up. And your suggestion Micheal is something I will try. I tried using arrays and index calling but cant fund what I need. I wull try this if statement approach and share results.
        Aj

        • Michael James on August 13, 2019 at 8:51 pm

          I’ll have to spin up a video lesson about that use case Autelio!

  10. m r on August 26, 2019 at 1:10 am

    HOW TO SEND THE RANDOM NUMBER DISPLAY ON THE SERIAL MONITOR TO THE MOBILE APP THROUGH BLUETOOTH HM10
    .
    if (BTSerial.available()) // read from Hm-10 and send to Arduino Serial Monitor
    Serial.write(BTSerial.read());

    if (Serial.available()) // Keep reading from Arduino Serial Monitor and send to HC-05
    BTSerial.write(Serial.read());
    THIS CODE WILL HELPS TO SEND DATA TYPED ON THE SERIAL MONITOR TO APP AND RECIVE THE DATA FROM THE APP

    BUT I WANT TO SEND THE DATA (RANDOM NUMBER) DISPLAYING ON THE SERIAL MONITOR TO THE APP

  11. Bob King on May 15, 2021 at 3:55 pm

    Hi Michael
    The random lighting of the three LED’s was just what I was looking for but now, for (the new game I am trying) I want to create a random time of between 2 or 10 seconds delay between the outputs of any of the three LED’s is this possible?

    • Michael James on May 15, 2021 at 10:22 pm

      Hi Bob, yes, totally possible. For example, you could create another random variable between 2000 and 10000, and pass that to the delay function (assuming you are using delay for this program).

  12. Anchu on November 25, 2023 at 8:35 am

    Could you show it with an example

Leave a Comment