Hey everyone,
I don't need true randomness, but I was hoping to inject a little more entropy by multiplying a few consecutive readings.
Is my syntax wrong, or is it that I have placed this above the void setup(); section?
int rndSeed = (analogRead(A0) * analogRead(A0) * analogRead(A0) * analogRead(A0) * analogRead(A0)); //Unconnected analog pin used to collect noise
randomSeed(rndSeed);
Ahh hang on, but I guess it doesn't matter if it's global or not, because the randonSeed has already been set, and I suppose this has to be global by design, right?
A small correction...
Warning: know that analogRead() can be a terrible source of entropy and successive analog readings of a floating pin tend to drift the value towards zero generally making that useless.
Hey everyone,
Thanks for your replies. I really appreciate you sharing your knowledge and experience.
I won't be using this random number for anything critical like cryptography, etc, it's just to select 1 of 5 outputs 'randomly'.
(Further coding fun is that not all 5 output will be used at all times, so might be 1-2-5, 2-3-4-5, etc. But I'm really enjoying the puzzle of working this stuff out. Arduinos are awesome. )
(I figure I'll check if the random number is one of the active channels and if not, generate a new random number.)
To be pedantic: use the elapsed time since bootup, rather than the elapsed time of the button press action.
// Button Entropy Injection for random() and randomSeed()
//https://wokwi.com/projects/421713344617482241
// for https://forum.arduino.cc/t/int-rndseed-analogread-a0-analogread-a0/1349109
const int ButtonPin = 2;
void pauseForButtonEntropy(const int ButtonPin) {
Serial.println("Press button to start");
while (digitalRead(ButtonPin) == HIGH) { // wait for button press
; //do nothing
}
while (digitalRead(ButtonPin) == LOW) { // protect against button initially being pressed
; //do nothing
}
randomSeed(micros() + random()); // inject entropy, rather than overwrite entropy -- good for repeated use
}
void setup() {
Serial.begin(115200);
pinMode(ButtonPin, INPUT_PULLUP);
}
void loop() {
pauseForButtonEntropy(ButtonPin);
Serial.println(random());
//delay(500); // simple rate-limiting -- need some sort of debouncing for noisy buttons
}
Bear in mind values outside of the 1 - 0x7FFFFFF range are degenerate. Applying a mask before calling randomSeed eliminates the trouble. Zero is best handled by retrying.