di2704.txt ;************************************************************************************************ ; LISTING 1 - SOURCE CODE FOR A VIRTUAL-EEPROM BASED RANDOM-NUMBER GENERATOR ; ; "Rolling-code generator uses flash microprocessor," EDN, May 3, 2001, pg 94 ; ; http://www.ednmag.com/ednmag/reg/2001/050301/designideas.htm#09di5 ;************************************************************************************************ #include <8cbr.h> #include //*************************************************************** // // Description: The following is a random number generator, // its implementation is the use of a 16 bit // LFSR, by XORing the correct bits we arrive // at a pseudo random number // // Implementation: The pseudo number is created by using the // feedback equation (for a 16 bit word) // bit16=bit5 XOR bit4 XOR bit3 XOR bit0 // //*************************************************************** void random(){ unsigned int seed_upper; // The seed variables unsigned int seed_lower; // Seed the random number generator // Choose any random numbers for the MSB and // LSB of the initial random numbers readbf(0x1FFF); // Do a read at the high location seed_upper=ISPRD; readbf(0x2000); // Do a read at the low location seed_lower=ISPRD; if (!seed_upper && !seed_lower){ // If it is zero then continue } else { seed_upper=10; // Otherwise give it a seed seed_lower=20; } bits temp1; // Some Xoring Bits bits temp2; char flag; bits carry; temp1=(bits)seed_upper; // Assign the upper & lower temp2=(bits)seed_lower; carry.0=temp2.5^temp2.4; // Now do the Xoring carry.0=carry.0^temp2.3; carry.0=carry.0^temp2.0; if (temp2.0) flag=1; else flag=0; temp1=temp1>>1; // Bit shift left temp2=temp2>>1; if (flag) temp2.7=1; temp1.7=carry.0; // Use the Carry Bit seed_upper=temp1; seed_lower=temp2; page_erase(0x1FFF); // Erase the location cwritebf(0x1FFF,seed_upper); // Save the upper byte cwritebf(0x2000,seed_lower); // Save the lower byte } // end of the random routine void main(){ unsigned int i; // A counter variable unsigned int random_arr[2]; // A random number array // Set the clock timer PGMTIM=0x7B; // copy it back to the random numbers readbf(0x1FFF); // Read the result random_arr[0]=ISPRD; // From the ISPRD register readbf(0x2000); random_arr[1]=ISPRD; // Both the Upper and Lower // Seed while (1){ page_erase(0x1FFF); // Page Erase cwritebf(0x1FFF,random_arr[0]); // Write the byte back cwritebf(0x2000,random_arr[1]); // Write the byte back // Get a number ramdomly generated through 100 iterations for (i=0;i<100;i++) // Call the random number { // generator a hundred times random(); } // Application code goes over here } } // end of main