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


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 - than you can be sure that if you reset the Arduino board and pull the handle again - it will be a winner the first time.

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

This function takes a value of data type long or an integer, 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:

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.  That is it is just a different list of pseudo random numbers!

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 it is basically 'floating' and 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:

Learning about Arduino?
Join the thousands to signup for our Free 12-part Arduino Video Course
We hate spam just as much as you