0

I am trying to generate random output for the leds from the given values in the array I created but it does not work, I found this online and they said do it like below but it doesn't do anything. The programme should get a random value from the array.

int randomArray[4] = { 0,85,170,255 };




void setup() {

    Serial.begin(9600);
    pinMode(red, OUTPUT);
    pinMode(green, OUTPUT);
    pinMode(blue, OUTPUT);
    pinMode(RLed, OUTPUT);
    pinMode(YLed, OUTPUT);
    pinMode(GLed, OUTPUT);
    randomSeed(millis());

}

void loop() {

    redvalue = randomArray[random(0,3)];
    bluevalue = randomArray[random(0, 3)];
    greenvalue = randomArray[random(0, 3)];
    Serial.println(redvalue);
    Serial.println(bluevalue);
    Serial.println(greenvalue);
    analogWrite(red, redvalue);
    analogWrite(blue, bluevalue);
    analogWrite(green , greenvalue);
    analogWrite(RLed, redvalue);
    analogWrite(YLed, bluevalue);
    analogWrite(GLed, greenvalue);
    delay(1000);
}
6
  • 1
    what do you mean with "generate random output for the leds from the given values in the array"? do you want to use those array values as seeds? or do you want to pick a random element of that array of fixed values? where do you declare redvalue and your other variables? Commented Jun 10, 2020 at 9:03
  • @Piglet. Yes, I want the output values to be random but only using the 4 values that I specified in the random array Commented Jun 10, 2020 at 9:06
  • So the output should either be 0, 85,170 or 255 Commented Jun 10, 2020 at 9:06
  • @Piglet I have tried your answer but it doesn't work. It just generates a random number between 0 and 4 and not the values from the array Commented Jun 10, 2020 at 14:48
  • then you did it wrong. update your code Commented Jun 10, 2020 at 15:53

1 Answer 1

2

If you want a random element of your array you have to use a random index.

I you have 4 values in your array the index must be in the interval [0-3].

From the Arduino Reference:

random(max)

random(min, max)

Parameters min: lower bound of the random value, inclusive (optional). max: upper bound of the random value, exclusive.

Returns A random number between min and max-1. Data type: long.

int randomArray[4] = {0, 85, 170, 255};
int randIndex = (int)random(0, 4);
int randElem = randomArray[randIndex];

should do the trick, but my C++ is a bit rusty. you can probably omit the int cast.

Sign up to request clarification or add additional context in comments.

1 Comment

I guess you can just write long randIndex = random(0, 4);.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.