Go Down

Topic: question about random function (Read 423 times) previous topic - next topic

daidalos

Just a quick question about the random number function in Arduino - I've noticed that every time the program is reset and starts up again, it will pick the same "random" numbers in the exact order as it did before.....


Is there an explaination for this?

mellis

Yes.  Like the random functions in most programming languages, it's not actually generating real random numbers.  Instead, it does various operations on each number to get the next one, and these operations are complicated enough that the results appear random.  Because each number is only based on the one before it, you'll always get the same sequence by default.  To "seed" the sequence, you can call the randomSeed() function in your setup().  You can try passing it the value of an unconnected analog input (e.g. randomSeed(analogRead(0))), which gives a sort of random value.  Or you can try to generate random data some other way - e.g. if you've got some pushbuttons connected to your Arduino, you could call randomSeed(millis()) when one of the buttons gets pressed.  Or you could send a random byte from the computer over the serial connection.  

The Make blog actually had a nice link to a proper random number generator recently: http://www.makezine.com/blog/archive/2007/09/orb_open_random_bit_gener.html

daidalos

#2
Sep 14, 2007, 08:03 pm Last Edit: Sep 14, 2007, 08:09 pm by daidalos Reason: 1
ah I see ... thanks for the quick reply!

I'll check out the link.


Also - the analogRead(0) seed in the setup() achieved what I was looking for - it seems to be generating a new list of random numbers every time I reset the program.

cheers mellis!

Code: [Select]
long randNumber;
long time;


void setup(){
 Serial.begin(9600);
 randomSeed(analogRead(0));
}

void loop(){
 Serial.print("Time: ");
 time = millis();
 Serial.println(time);
 delay(2000);
 
 randNumber = random(50,300);
 
 Serial.println(randNumber);
}

Go Up