Sunday, March 17, 2013

Missing Arduino Analog Inputs, and the Random Function

The Atmel 328P chip used on many of the Arduino boards actually has 8 Analog Inputs, but specifically with the DIP version instead of the SMT, there weren't enough pins on the DIP carrier to bring those ports out for use. On some of the SMT versions, like the Pro Mini, Ports A6 & A7 are available as analog inputs, but not multi purpose (Digital I/O) like A0-A5.

Even on the UNO, which doesn't bring A6 & A7 out to a pin, we can still make use of these ports. The Random function is a common function for many applications, as it seems to provide a random number generator that can be used for dice games, and other applications. However, unless seeded by a varying start number, it actually is quite predictable.

One neat feature of an analog input is referred to as a floating input. This is a input that is not connected to anything. If you try to read it, the values will be all over the place, based on changing electrical fields nearby. We can use either of these two phantom analog inputs as seeds for the random function, ensuring a truly random output.


long randNumber;

void setup(){
  Serial.begin(9600);
  randomSeed(analogRead(A7));
}

void loop(){
  randNumber = random(300);
  Serial.println(randNumber);

  delay(50);
}


More Info:


http://arduino.cc/en/Reference/RandomSeed

http://arduino.cc/en/Reference/Random

http://arduino.cc/en/Reference/AnalogRead