Languages

Random random seed

The random() function of the AVR is pretty useful, however, since it is based on a seed, it will always deliver the same random numbers if the seed is the same. On a computer, one generally overcomes this problem by setting the seed using a pseudo-random process such as the computer clock.

Since there is no internal clock on an AVR, a good solution is to use an open analog pin. The following code does exactly this, but instead of just calling

randomSeed( analogRead(pin) );

it calls analogRead() four times to fill up all of the 32 bits of the seed. Here it is:

  /// Initializes the random number generator 
  /// by using analogRead on an open pin.
  void seed(byte pin) {
    unsigned long seed = 0;
    for (int s=0; s<32; s+=10) {
      unsigned long val = 0;
      do {
        val = analogRead(pin);
      } while (val == 0); // discard zeros
      seed |= (val << s);
    }
    randomSeed( seed );
  }