randomSeed function doesn't work

For the discussion of Arduino related topics.

Moderator: phalanx

Post Reply
JonBDavidson
Posts: 10
Joined: Thu May 10, 2018 2:39 pm

randomSeed function doesn't work

Post by JonBDavidson » Mon Jun 04, 2018 10:31 pm

HI,

I'm trying to use the randomSeed(analogRead(0)); function to randomly generate numbers between 1 and 3. However, despite following the Arduino example using the randNumber variable, I get the same exact numbers almost every single time. Here is an example of what I get on the serial monitor:

1
2
1
1
2
2
3
3
3
3
3
3
2
1
1
etc.

It doesn't matter if I put delays in the code between readings or if I lengthen or shorten the delays, there is nothing connected to the analog A0 pin, and to make matters more mysterious, if i use while loops to keep the function from progressing until it generates a new number, it keeps generating the same numbers anyway. If I use If conditions to make sure the new number generated doesn't match the previous number generated, it ignores the If statements too, and continues to print the same numbers. Is randomSeed a viable random number generator function, or should I drop it for another one? Thanks for any input on this.

jremington
Support Volunteer
Posts: 2173
Joined: Fri Jun 15, 2007 9:41 pm
Location: Eugene, Or

Re: randomSeed function doesn't work

Post by jremington » Tue Jun 05, 2018 8:48 am

You have to use a different value for the randomSeed argument every time, to get a different sequence.

It is not guaranteed that an unconnected or "floating" analog input will provide suitable numbers. Is A0 actually unconnected, in your case? Try printing out the value returned by analogRead(A0) to see if it ever changes.

Another approach is to start a loop counting when the program begins, stop it when someone presses a button and use the count for the seed.

Valen
Support Volunteer
Posts: 1698
Joined: Wed Dec 22, 2010 2:05 am

Re: randomSeed function doesn't work

Post by Valen » Wed Jun 06, 2018 5:48 am

Is a internal pull-up resistor enabled in the code?

Post Reply