Working on an SMD board that has a 32U4 chip. I'm running low on pins and want to use the A5 pin as a button input - however, A5 is also used to generate a random value for random seed.
Does anyone know if putting a button on A5 will affect scripts that use a random seed function? If so, what is the result?
If you are not using an external pullup or pulldown resistor for the button on A5 then as long as you do the randomSeed() before setting the pinMode() for A5 then you will probably be OK as it will be floating at an unknown voltage
Not recommended because the random number generation requires the Input pin to be "floating": non-deterministic between 0 - 1023. Having electronic components such as a button creates additional capacitance (and inductance) and could create a signal during reboot which would make the random numbed algorithm fail.
So, my take on this is everything will work at power-up, but a forced reset may be problematic... or not.
Ray
long randNumber;
void setup() {
Serial.begin(9600);
// if analog input pin 0 is unconnected, random analog
// noise will cause the call to randomSeed() to generate
// different seed numbers each time the sketch runs.
// randomSeed() will then shuffle the random function.
randomSeed(analogRead(0));
}
void loop() {
// print a random number from 0 to 299
randNumber = random(300);
Serial.println(randNumber);
//
// print a random number from 10 to 19
randNumber = random(10, 20);
Serial.println(randNumber);
//
delay(50);
}
There are ways to use a button to help with or without the seed by taking advantage of unpredictable and imprecise human timing.. And depending what you're doing with the hardware & software you may be able to make a dual-use button
For example you can run a random number generator in a loop (before seeding) and when the button is pushed (at a random/unknown time) you grab the random number and use that for your seed.
Or, you can keep that random number generator running full-time in the "background" and just grab a random number every time the button is pushed. In that case you don't need a seed.