Using the Real Random object in the obex created by Chip Gracey
This object generates real random numbers by stimulating and tracking CTR PLL jitter. It requires one cog and at least 20MHz.
http://obex.parallax.com/objects/62/
Code:
Background and Detail: │
│ │
│ A real random number is impossible to generate within a closed digital system. This is because there are no │
│ reliably-random states within such a system at power-up, and after power-up, it behaves deterministically. │
│ Random values can only be 'earned' by measuring something outside of the digital system. │
│ │
│ In your programming, you might have used 'var?' to generate a pseudo-random sequence, but found the same │
│ pattern playing every time you ran your program. You might have then used 'cnt' to 'randomly' seed the 'var'. │
│ As long as you kept downloading to RAM, you saw consistently 'random' results. At some point, you probably │
│ downloaded to EEPROM to set your project free. But what happened nearly every time you powered it up? You were │
│ probably dismayed to discover the same sequence playing each time! The problem was that 'cnt' was always │
│ powering-up with the same initial value and you were then sampling it at a constant offset. This can make you │
│ wonder, "Where's the end to this madness? And will I ever find true randomness?". │
│ │
│ In order to have real random numbers, either some external random signal must be input, or some analog system │
│ must be used to generate random noise which can be measured. We're in luck here, because it turns out that the │
│ Propeller does have sufficiently-analog subsystems which can be exploited for this purpose -- each cog's CTR │
│ PLLs. These can be exercised internally to good effect, without any I/O activity. │
│ │
│ This object sets up a cog's CTRA PLL to run at the main clock's frequency. It then uses a pseudo-random │
│ sequencer to modulate the PLL's target phase. The PLL responds by speeding up and slowing down in a an endless │
│ effort to lock. This results in very unpredictable frequency jitter which is fed back into the sequencer to │
│ keep the bit salad tossing. The final output is a truly-random 32-bit unbiased value that is fully updated │
│ every ~100us, with new bits rotated in every ~3us. This value can be sampled by your application whenever a │
│ random number is needed.
Bookmarks