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 » Generating random numbers in C.

August 04, 2010
by TexanBackpacker
TexanBackpacker's Avatar

So I do know how to program in Java, but this is one thing I can't figure out about C. What I am trying to do is Generate a random number between 0 to 3, and a certain LED will light up depending on the number. How can you accomplish this? I am trying to learn how to do this cause in the near future I am going to use this information so I can make a whack-a-mole game. (Saw it in Make Magazine)

Thanks!

August 05, 2010
by bretm
bretm's Avatar

There are many approaches. You can see some of them if you search RNG, PRNG, or Random Numbers in the search box here, or another good resource is avrfreaks.net.

The tricky part is getting a good seed value so that you don't generate the same sequence each time. A common way of doing that is sampling the ADC a number of times with no input, and grab the least-significant bits that come out, which are pretty noisy/random.

You could also use the ADC technique to generate the random numbers themselves, instead of just a seed for a pseudo-random generator. Especially in your case since you only need one random number for each "whack", which is on the timescale of human reactions. If you needed something fast I would have suggested seeding a 16- or 32-bit linear feedback shift register (LFSR) which you can search for more info on. There's a lot of it out there.

But the ADC noise samples should work fine. Grab two bits, shift one left and OR with the first one to make a 2-bit value (0 to 3).

Post a Reply

Please log in to post a reply.

Did you know that SPDT stands for "Single Pole, Double Throw"? Learn more...