Random LED sequence

Hello. I need to turn on two LEDs, red and green, in a random sequence. I am currently using the randomSeed(analogRead(0)) and randNumber = random(2) commands and it works pretty well. Now, I want to define the percentage of cases in which each LED will be on. That is, for example, 30% for the red LED and 70% for the green LED. What is the simplest way to do that?

Post you code for random and your best try for % code.

Without attempting to write the code...

Create a random number between 0 and 9.
Follow it by an if-statement.
There is a 30% chance it's less than 3.

1 Like

random(2) creates 50% (1/2) so what would create 70% or 30%?

What is the task of the sketch in real life?

Yes, I know that. I probably need to create an array of 0's and 1's and somehow determine the percentage of 0 and 1. The 30 and 70% are not fixed values; there must be a possibility to change the percentage.

Some behavioral experiment in which the subject will do some task on a green light and wait on a red light.

use a switch-case with 0 - 9 and 3 of the cases will result "red" and the rest will result "green"

Okay.

At any time, change the rate of randomness. random(2) has a 50:50 rate/ratio of creating a 0 or a 1. Similar with 1/7 ot 1/3. Creating arrays or storing values stops any change. Or do you know that, too?

That!

Make it a variable!

Here's the sketch that creates a sequence of 10 numbers with 30% of 0's and 70% or 1's

int randNumberLED;  //either 0 (red LED) or 1 (green LED)
int output;
int i = 1;
int j = 0;

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

void loop() {
  while (i <= 10) {
    randNumberLED = random(3);
    if(randNumberLED == 0) {
      j++;
      if ((j/10) <= 0.3) {
        output=0;
      }
    }
    else {
      output=1;
    }
  Serial.print(output);
  Serial.print(" , ");
  i++;
  }
}

That's true. But I feel it needs improving. The 10 numbers don't have an equal probability of being 1.

EDIT: no, all 10 could be zero.

int thirtyseventy;

void setup() 
{
  Serial.begin(9600);
}

void loop() 
{
  thirtyseventy = random(0, 9);
  Serial.println(thirtyseventy);
  if (thirtyseventy > 6)
  {
    Serial.println("green");
  }
  else
  {
    Serial.println("red");
  }
  
  delay(3000);
}

why not a simple random(101) and switch on the red if it is <= 30?

Isn't that what I just did in the previous post?