Reputation: 1
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);
}
Upvotes: 0
Views: 1895
Reputation: 28984
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.
Upvotes: 2