Go Down

Topic: Random (Read 789 times) previous topic - next topic

jmnijsse

Hi,

I try to turn on max 5 leds by pressing 2 buttons.
For this I used this script below.
But, after reset, the most time the same led is beaming.

Is there any improvement on it?

Gr.
Johan

Code: [Select]

int led[] = {3,4,5,6,7,8};
int numberLeds = 6;
int button1 = 9;
int button2 = 10;

void setup() {               
  for (i=0;i<5;i++){
    pinMode(led[i],OUTPUT);
    digitalWrite(led[i],LOW);
  }
  pinMode(button1,INPUT);
  pinMode(button2,INPUT);
}

void loop() {
  randomSeed(analogRead(0));
  if (digitalRead(button1)&&digitalRead(button2)){
    if(random(100)>50){
      digitalWrite(led[random(numberLeds)],HIGH);
    }
    if(random(100)>50){
      digitalWrite(led[random(numberLeds)],HIGH);
    }
    if(random(100)>50){
      digitalWrite(led[random(numberLeds)],HIGH);
    }
    if(random(100)>50){
      digitalWrite(led[random(numberLeds)],HIGH);
    }
    if(random(100)>50){
      digitalWrite(led[random(numberLeds)],HIGH);
    }
    while(true){
      delay(1000);
    }
  }
}

AWOL

You random seed should be in "setup"
"Pete, it's a fool looks for logic in the chambers of the human heart." Ulysses Everett McGill.
Do not send technical questions via personal messaging - they will be ignored.

Coding Badly


Why analogRead is a bad choice...
http://arduino.cc/forum/index.php/topic,66206.msg630884.html#msg630884

The reliable but not very sexy way to seed random...
http://arduino.cc/forum/index.php/topic,66206.msg537783.html#msg537783

And, of course, heed AWOL's advice.

michael_x

#3
Jun 13, 2012, 10:23 am Last Edit: Jun 13, 2012, 11:54 am by michael_x Reason: 1
As there's manual input ( button push ), you could use millis() of the first button press as a random seed, too.
Or simply call random(); in the beginning of loop() where now is your randomSeed(), this will be repeated an undefinite number of times, until both buttons are pressed.

BTW: Your code does not generate a sequence at all, as it never ends the loop().
Strange design... you need to press 3 buttons: Reset, then the 2 others together.

Edit: sent too early

jmnijsse

Thanks all.
It's working for the purpose we want.
And yes, it's a strange design, but we have no time to make it better.
(pupils always start to late with their projects...)

Gr.
Johan

Go Up