I have some code:
char *fruits[]={"Lettuce", "Tomato", "Pineapple", "Apple"}; //This is the array
long fruit1;
void setup(){
Serial.begin(9600);
randomSeed(500);
fruit1 = random(sizeof(fruits)/sizeof(char*));
Serial.println(fruits[fruit1]);//Prints random in serial
}
This code picks a random fruit the first time an arduino sketch is ran, but every other time I run it, it uses the same random fruit it picked the first time the sketch is ran. I want it to pick a random fruit from the array every time the sketch is ran, meaning everytime I turn it on and off I want to see a different and random fruit from the last. Sorry if I'm doing something wrong.
Code source: https://forum.arduino.cc/index.php?topic=45653.0
For a given seed value you will always get the same sequence of random numbers. You need a different seed every time setup is called:
randomSeed()
initializes the pseudo-random number generator, causing it to start at an arbitrary point in its random sequence. This sequence, while very long, and random, is always the same.If it is important for a sequence of values generated by random() to differ, on subsequent executions of a sketch, use
randomSeed()
to initialize the random number generator with a fairly random input, such asanalogRead()
on an unconnected pin.Conversely, it can occasionally be useful to use pseudo-random sequences that repeat exactly. This can be accomplished by calling randomSeed() with a fixed number, before starting the random sequence.