How do I generate random numbers in a microcontroller efficiently? Are there any general guidelines or a particular fast method?
If you can leave a pin floating, it could help to generate random numbers with linear feedback shift register. I'm not sure this is the way to go, but please have a look at my code:
// This code was written for 8051 (AT89S52)
unsigned char lfsr = 231; //8 bit shift register, with the seed of 231 or '11100111b'
unsigned char input_bit, i;
void main (void)
{
//Setup
P0_0 = 0; // Leave Pin 0 Port 0 floating
uart_init(); //Initializing uart/serial communication with pc
while (1)
{
for (i = 0; i < 255; i++)
{
if (P0_0 == 1) // If Pin 0.0 is HIGH
{
input_bit = ((lfsr >> 0) ^ (lfsr >> 2) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1;
lfsr = (lfsr >> 1) | (input_bit << 7);
}
}
printf_tiny("%u\n", lfsr); //Send the random number to PC
soft_delay(65535); //Simple delay function
} //end while (1) loop
}
EDIT: I found out my answer may be a bad one. More details on why should not use a floating digital pin: https://electronics.stackexchange.com/questions/50476/random-number-generators-using-a-gpio-pin