Categories
Uncategorized

Arduino – Random Colors

Colors

One of my PCOMP students wants to randomly select a set of RGB values from a predetermined list. It’s the sort of things where I know the concept is easy but the execution is a bit more difficult only because I’ve done it in other languages/environments, but not in an Arduino sketch.

The nice thing about programming is that once you know how to do something using one language, the concepts transfer over to other languages, and it becomes mostly a matter of figuring out the syntax and method to make it all work.

Here’s an example sketch that allows you to have a list (array) of RGB values and then randomly select one and return it, split the r, g, b into their own integer variables, and then print them to the serial monitor. (The final version will use analogWrite to control RGB LEDs.)

// RandomColor.ino

void setup() {
  Serial.begin(9600);
  randomSeed(analogRead(A0));
}

void loop() {
  char* rgb = returnColors();
  int r, g, b;
  if (sscanf(rgb, "%d,%d,%d", &r, &g, &b) == 3) {
    Serial.print(r);
    Serial.print(", ");
    Serial.print(g);
    Serial.print(", ");
    Serial.println(b);
  }
  delay(500);
}

char* returnColors() {
  char* myColors[6];
  myColors[0] = "128,0,0";
  myColors[1] = "0,128,0";
  myColors[2] = "0,0,128";
  myColors[3] = "255,0,0";
  myColors[4] = "0,255,0";
  myColors[5] = "0,0,255";
  int colorIndex = random(0,6);
  char* result = myColors[colorIndex];
  return (result);
}

Obviously the list can be much larger than just six elements, but this is example code to be expanded upon.

You can also grab this code from github.

Update: Royce has his own version you can check out. He suggests it should be more efficient because the textual RGB values are converted to binary at compile time rather than runtime.