How do I generate random numbers in a microcontroller efficiently?

Donotalo picture Donotalo · Oct 13, 2009 · Viewed 22k times · Source

How do I generate random numbers in a microcontroller efficiently? Are there any general guidelines or a particular fast method?

Answer

DigitalRoss picture DigitalRoss · Oct 13, 2009

One normally generates pseudo-random numbers and not actual random numbers, although both are possible at varying rates.

There are two general categories, depending on whether the sequence will be used for cryptographic purposes. The primary distinction is whether knowledge of one number in the sequence allows prediction of the next. General purpose RNG's don't worry about whether knowledge of the algorithm would allow an observer to duplicate the sequence, and they run quite a bit faster.

A typical general purpose RNG algorithm is the Mersenne Twister. There are many public implementations of various algorithms. See here for one.

If the MT requires too much memory, a half-way-decent fallback is the linear congruential generator. (The MT wasn't invented until 1997.) This generator has certain issues but it requires almost no memory, almost no code, and is extremely fast. Implementations are everywhere, and it was covered in detail in Knuth's Seminumerical Algorithms.

To seed any RNG, you will need a source of entropy, see http://en.wikipedia.org/wiki/Entropy_(computing) (Note: SO gets confused about the ()'s in that link.) This is typically derived by timing events that the CPU can observe, such as keystrokes, (I guess that won't work for you) interrupts, and packet arrivals. A real time clock is often an acceptable source if it maintains its own state, as reboots are rarely timed in any sort of sequence.