How do I generate random numbers in a microcontroller efficiently?

前端 未结 8 2082
梦毁少年i
梦毁少年i 2021-02-15 18:14

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

相关标签:
8条回答
  • 2021-02-15 19:07

    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.

    0 讨论(0)
  • 2021-02-15 19:18

    If the hardware has a button for the user, a simple trick is to count how long the button is pressed. With a fast enough short counter you get a "random" number.

    0 讨论(0)
提交回复
热议问题