 # Random Numbers Selecting 1 of 2 possible leds to light - problem with coding

I have a problem with a piece of code that I wanted to write. This piece of code would, by generating a random number (1 or 2) select a path through an if statement. This if statement would light up an LED on either pin 13 or 12. It would keep it on for a short while and then fetch a new random number and begin the process again - here is the code:

``````int led = 13;
int led2 = 12;

void setup() {
// put your setup code here, to run once:
pinMode(led, OUTPUT);

}

void loop() {
// this part of the code picks a random number 0 or 1. This is then used to pick which side of an if statement to use in order to
// flash either 'led' or 'led2'
int RandNum = random(1,3)
if(RandNum = 1)
{
digitalWrite(led, HIGH);
delay(250);
digitalWrite(led, LOW);
delay(100);
}
else
{
digitalWrite(led2, HIGH);
delay(250);
digitalWrite(led2, LOW);
delay(100);
}
}
``````

The problem is that all I am getting is the LED on pin 13 flashing over and over again. It is the same on every reset - it isn't latching onto a single random number then I would imagine.

Any help would be greatly appreciated

Thanks

``````if(RandNum = 1)
``````

That assigns 1 to RandNum, and also uses the result as the value for the if.

I think you meant:

``````if(RandNum == 1)
``````

= assigns, == compares.

Sorry - used to BASIC that does not seem to work either - I can definitely see the random now (it is flashing at irregular intervals), but it is not swapping between which LED is lit

Thanks

``````void setup() {
// put your setup code here, to run once:
pinMode(led, OUTPUT);

}
``````

What's missing from that function?

Um? Um?... I'm sorry - I think your going to have to tell me!

I hope it isn't too obvious

What's missing from that function?

At least two things - randomSeed() and pinMode() for hints.

You're setting the led pin to be an output - but what about the led2 pin...?

Oh yeah - that's not good - I can't believe I missed that

Thanks for this embarrassing lesson in something so important

... much better!

Thank you to everybody who helped

And you should really seed the random number generator, otherwise the randomness won't be so random - it'll be the same sequence every time you turn on.

``````randomSeed(analogRead(0));
``````

is the generally accepted way of doing a very crude seeding of the PRNG (there are much much better ways).

Ah - thankyou - that info will be useful