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.
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!
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!
Awesome tip! Thanks for Andy.
Hi Michael
Is there a code available for an arduino single digit 7 segment display number generator. That can be operated push button.
Thanks, it really helped with the random numbers. Exactly what i needed.
Great – glad it could help!
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:)
Thanks for adding this Franta – great points!
Very bad solution. analogRead returns integer nubmer between 0 and 1023, so, you will have only 1024 lists of sequences which is extremly low.
Suppose you read A1 too and multiply A0 by it for seeding. That should be a large enough pool.
I created an electronic dice. This tutorial helped a lot. Thank you!
Great! Glad it could help.
Haha, I thought I was paranoid noticing that my robot’s eyes always start “randomly” moving in the same pattern 😀
Thank you.
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.
Thanks for sharing!
Really useful
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?
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.
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
I’ll have to spin up a video lesson about that use case Autelio!
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
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?
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).
Could you show it with an example