Hello!
I'm an Arduino beginner. In one of my projects, I have got 3 LEDs. I want to turn on just one of them chosen by the random() function. The next time that random() makes his choice, I want to exclude the previous number extracted. How can I do it?
Thanks in Advance.
or number = (number + random(1, nr_entries)) % nr_entries;That way the old number is automatically excluded. nr_entries = 3 (as in your case) random returns a 1 or a 2, the modulo of the addition will return a new value.
A simple while loop - check if the value returned is the same as the last.
If it is, pick a new one
const uint8_t nr_pins = 3;
const int ledpin[] = {5, 6, 7}; // you have to store the pin nrs in an array
void setup() {
for (uint8_t i = 0; i < nr_pins; i++) { // set them all to ouput
pinMode(ledpin[i], OUTPUT);
}
}
void loop() {
static uint8_t pin = random(nr_pins); // initial can be anything, as example say it '1'
for (uint8_t i = 0; i < nr_pins; i++) {
if (i == pin) digitalWrite(ledpin[i], HIGH); // set one of the pins HIGH
else digitalWrite(ledpin[i], LOW); // and the others LOW
}
delay(1000);
pin = (pin + random(1, nr_pins)) % nr_pins; // if pin is '1' say the random = '2' together = '3'
// and 3 % 3 = 0
}
Something like this. please remember to post code within </> code-tags