March 6, 2011

Random Arduino Bits 'n Bytes (part 1)

Let's take a look at the random number generation on arduino, and on bit-level manipulation. This lesson will be helpful for a project I'm preparing.

So arduino has the random() function that when called returns a long (that means a long integer) number. This function can be used in two ways. The first is calling it with the max range of probable number that you want the function to produce.
For example if you want the  function to return a single digit integer you will call it this way:

random(10);


Notice that just like in C-language code the number start from 0, so 0-9 are 10 numbers.
The second call is by providing a range in which you want the number to be in.

random(0,10);

This will still return a number between 0 and 9.



How this function work? It's not actually random generation it's pseudorandom. That means that there is a very big list of random numbers that the program uses. The problem is the even though the list has random numbers, it will use the same numbers every time time the program is reset. 

This is where the randomseed(seed) function comes in. This function takes a seed (a number) that says the random() function where in the big list it should start. So all you need to do is give the randomseed() function it's seed, and the random() function will give different random numbers every time the program is reset. 

And what could be a better random number that the electrical noise? So we take a read from one of the analog inputs of the board and use that "noise" as the seed.

randomseed(analogread(0));

That is the command that makes this happen. So here are 2 videos that demonstrate the use of the random function:

(This is random number generation with no seed)


(And this is random generation with random initial seed)


Here code for the randoms_no_seed program and for the randoms_seed program.

Read on part 2!

If you have any question leave a comment below!

And if you like my posts then subscribe via rss, or via e-mail to stay updated.

Happy Tinkering!

If you liked this article then take a second to bookmark it with...


No comments:

Post a Comment