NerdKits - electronics education for a digital generation

You are not logged in. [log in]

NEW: Learning electronics? Ask your questions on the new Electronics Questions & Answers site hosted by CircuitLab.

Microcontroller Programming » Easy Random Numbers

February 28, 2010
by disneyd7
disneyd7's Avatar

What is the best way to generate random numbers using the MCU from the usb nerdkit?

What I need to do, each iteration, is generate two different random numbers between 1 and 8. Will the rand function in C work?

February 28, 2010
by pbfy0
pbfy0's Avatar

look at this thread

March 01, 2010
by hevans
(NerdKits Staff)

hevans's Avatar

Hi disneyd7,

I think you are looking for something like the rand() function, make sure you include stdlib.h before trying to use it. It will return a random number between 0 and RAND_MAX, where RAND_MAX is the biggest integer the MCU can represent.

random() is not actually choosing a random number every time you call it. What it actually does is return the next number in a series of pseudo-random numbers. You need to seed this list of pseudo-random numbers by calling srandom(). Seeding the sequence with the same number will result in the same sequence being returned every time. Note that this still results in a seemingly random sequence, you just get the same seemingly random sequence every time you run your program. If you are ok with that, then you don't need to worry about seeding your values with an actual entropy source (source of randomness). If you are looking for truly random results you need to do something fancy to seed the random number generator. For that, check out the thread pbfy0 pointed you too above.

Let us know if any of this doesn't make sense. It is actually a fairly deep (but awesome) topic.

Humberto

Post a Reply

Please log in to post a reply.

Did you know that two resistors can be used to make a voltage divider? Learn more...