Random number

Hello,
I've read in different tutorials that a simple way to get a real random number in Arduino is using "randomSeed" function with analogRead(0) from an unused analog pin.

Something like this:

randomSeed (analogRead (0));
randNumber = random (300);

If I haven't any analog pin available can I use "millis()" function?

randomSeed(millis());

Thank you very much for you help.

Elia

If I haven't any analog pin available can I use "millis()" function?

You can, but if you use it in setup() you are likely to seed it with the same number each time, thus effectively nullifying the effect of randomSeed(). One technique would be to prompt the user to press a button to start the program and use the millis() or micros() value afterwards.

Perfect. A push button seems to be a right solution in my case!

Thank you.

If the value on the analog pin is unpredictable, you can still use it for seeding.

If you have some eeprom space available, the following is a far better option in any case: The reliable but not very sexy way to seed random. Reply #52 contains the latest version, reply #6 shows a way to make it dependent on the code that you loaded.

Here's another option:

Here is how you can get true random numbers with an Arduino DUE, see reply #11 of this thread :

https://forum.arduino.cc/index.php?topic=472905.0