Pages: [1]   Go Down
Author Topic: question about random function  (Read 321 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Newbie
*
Karma: 0
Posts: 28
architecture | media | computing
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

 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?
Logged

Forum Administrator
Cambridge, MA
Offline Offline
Faraday Member
*****
Karma: 9
Posts: 3538
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

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
Logged

0
Offline Offline
Newbie
*
Karma: 0
Posts: 28
architecture | media | computing
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
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);
}
« Last Edit: September 14, 2007, 01:09:38 pm by daidalos » Logged

Pages: [1]   Go Up
Jump to: