body, html {font-family: 'Open Sans', sans-serif;} #nav a, #nav span.in{font-family: 'Open Sans', sans-serif;} #title #tagline {font-family: 'Open Sans', sans-serif;} #main .gridItem h3 {font-family: 'Open Sans', sans-serif;}

About Random Numbers


Drymat


When designing the sketch for Crazy Potis, I wanted to have new target values for all four potis every time the sketch ist starting. I stepped into the topic with random numbers and learned a lot, I like to share with you. To make it easier to understand, I’m using only 1 digit numbers for this explanation...


random(min,max)

This is a function giving back a random value between min and max-1. (Yes, another example for that crazy language: min is included, but max is excluded. So if you want to receive a random number between 1 and 9 the term is random(1,10).

But the Arduino doesn’t create a real random number. Internaly it has a long row of random numbers, and everytime random() is called, it’s taking the next one in it’s row. 

The problem (especially in our case) is, that with every start of the Arduino, the random figures would be the same. Have a look to the first sketch

R S 01


and the result (The Arduino has been started 3 times):

R O 01


As you can see, all the time the random numbers are equal


randomSeed(seed)

The function randomSeed is forcing the Arduino not to start from its first random number but from somewhere else.

R S 02


The random figures now are different, but still everytime the same after each reboot:


R O 02

So also this won’t help us.


Using an analog pin

Many sketches are based on the clever idea, to read the value from an unused analog pin and using this value as the seed value for randomSeed. It’s working, but not as fine as I wanted. I discovered that the value of an unused analogue pin isn’t providing real random figures. Instead of receiving values between 0 and 1023 I received values between 290 and 330 and sometimes 4 times in a row exactly the same one.


Using a counter

This idea came up, when lying in the sun and inside the sauna when we stood near Stuttgart last week. The main idea is to use a counter, which is increasing everytime the sketch is starting. This counter will be stored inside EEPROM as I did it with the vistitor counter, Tim didn’t liked…

R S 03


At the beginning the counter is read from the EEPROM. I’m adding 9 to it (to spread the seed a little bit) and If the new value for counter is exceeding a limit (here 150), I’m setting counter to a random figure between 0 and 9. After that the counter will be written back to EEPROM.

Below you’ll see the result of four times restarting the Arduino. You can see the value of the counter and the 3 random figures, which are pretty different after each restart.


R O 03


Based on that I wrote a very short „Z_Better_Seed“ routine and integrated that to the main sketch of Crazy_Potis.



©  Olaf Goette 2008 - 2018