Monday, December 26, 2011

Creating random numbers on a µC [code snippet]

This is a small C function, to feed srand() with a random seed. I wrote it some weeks ago just to test if it would be possible to get random seeds with an 8051 microcontroller without additional hardware. And yes, it is possible. I was using an AT89C51ED, but the code should work with every 8051 compatible microcontroller.
How does it work and why? I took a closer look in the data sheet of the µC and i saw that some bits and bytes in the special function registers (SFRs) are not initialized with "1" or "0". Some bits were marked with "x" and those are the interesting ones. The value of those bits can be "0" or "1" after power up - their initial value is random. All i had to do was to iterate over all those SFR-bytes and XOR them. I am sure generations of 8051 coders have had the same idea, but i did not study all available information regarding 8051 and random numbers.
Just call the function like that "srand(getRandom());", and you will have a new random seed, after each power up of the microcontroller. (A normal µC reset will not give you a new random seed!)

unsigned char getRandom( void )
     unsigned char *random;
     unsigned char k;
     unsigned char value;
    random = 0x80; //Starting address of the SFRs
    for (k=0; k <= 127; k++) //iterate over the 128 bytes of the SFRs:
        value ^= random[k]; //XOR the values
    return value; //return the random seed

No comments:

Post a Comment