Subscribe to Arduino Academy and start learning today for FREE!

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.

Become the Maker you were born to be. Try Arduino Academy for FREE!

 

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

Subscribe
Notify of
guest
2 Comments
Inline Feedbacks
View all comments
Wrinkles
10 years ago

A question… If the voltage is read from the floating analog pin then assigned an integer value of 1 to 1024, would hat not limit you to 1024 discrete seeds and cause the output to be one of just 1024 values? If the random seed is limited to 300, then would you get one of just 300 values? Granted you wouldn't know which of those 300.

Is the voltage seen on the floating pin random or if I took 10,000 readings, would values tend to cluster?

If the values do tend to cluster, that might alter the odds on the

Steve Spence
10 years ago

It means there would be 1024 possible sequences of random numbers. Each sequence would be random numbers between whatever your start and end numbers are. The sequences could cluster, but not predictably.

Archives

2
0
Would love your thoughts, please comment.x
()
x