skip navigational linksPJRC
Shopping Cart Checkout Shipping Cost Download Website
Home MP3 Player 8051 Tools All Projects PJRC Store Site Map
You are here: 8051 Tools Code Library Random Numbers

PJRC Store
8051 Board, $79
LCD 128x64 Pixel, $29
LCD 16x2 Char, $14
Serial Cable, $5
9 Volt Power, $6
More Components...
8051 Tools
Main Page
Software
PAULMON Monitor
Development Board
Code Library
89C2051 Programmer
Other Resources

Pseudo Random Number Generator

These routines generate a sequence of pseudo-random numbers using the ordinary linear feedback shift register technique. Both routines require memory to hold the last number generated. They produce a predictable but randomly distributed sequence of numbers, similar to the rand() function in most C libraries.

No routine analogous to srand() is provided, but it is easily implemented by writing the seed value into the memory which holds the previously generated number. These routines check for zero (the illegal value), so it is not necessary to initialize the memory with a seed value unless a predictable starting seed is required or a truely random number is available.

RAND8
Generate an 8 bit pseudo random number, from 1 to 255. The number is returned in Acc.
RAND16
Generate a 16 bit pseudo random number, from 1 to 65535. The number is returned in Acc (lsb) and B (msb).
This code is available as plain text or in a zip file.

 

Some people have asked about the mysterious "p" variable. This line

        mov     c, p

utilizes a special feature of the 8051 processor. The "p" bit is one of the bits in the PSW (program status word) special functon register. This bit is the parity of the byte currently stored in the accumulator. This is equivilant to the exclusive OR of all 8 bits of the accumulator. The code uses this feature to quickly compute the exclusive OR of 4 bits by using a logical AND to mask off the other 4 bits, then simply read the parity bit to get the exclusive OR of the 4 remaining bits.


Paul's 8051 Code Library, Paul Stoffregen
http://www.pjrc.com/tech/8051/rand.html
Last updated: February 24, 2005
Status: complete
Suggestions, comments, criticisms: <paul@pjrc.com>