Adafruit Circuit Playground Random Colors Tutorial

By Nath Tumlin. Feel free to send comments, questions, concerns, corrections, or cash to ngtumlin@crimson.ua.edu

Video demo

In this tutorial we learn how to make a program for the Adafruit Circuit Playground that makes the 10 NeoPixels on the Circuit Playground flash random colors, or maintain their current color depending on the position of the toggle switch.

Initialization

We'll start by including Adafruit's CircuitPlayground library.

#include "Adafruit_CircuitPlayground.h"

Then we need to define the setup() function, which runs one time when we turn on the board.

void setup() {
  randomSeed(analogRead(0));
  CircuitPlayground.begin();
}

First, setup() sets up our random number generator so that each time we turn on the board we get a new sequence of lights. After that it sets up the CircuitPlayground library.

Changing the lights

The rest of the code lives in the loop() function, which runs over and over after setup() finishes. Below is the loop() function this program uses.

void loop() {
  if (CircuitPlayground.slideSwitch()) {
    //Loop through all pixels and set them to a random color
    for (int i=0; i<10; i++) {
      CircuitPlayground.setPixelColor(i, CircuitPlayground.colorWheel(random(256)));
    }
    delay(500);
  }
}

First we check if the slide switch is to the left. If it isn't we do nothing. The Circuit Playground has 10 NeoPixels, numbered 0 through 9. We loop from 0 to 9 and use CircuitPlayground.setPixelColor(i, CircuitPlayground.colorWheel(random(256))) to set the ith NeoPixel to a random color. random(256) returns a random number between 0 and 255, and the CircuitPlayground.colorWheel() function takes a number between 0 and 255 and turns it into a color. Finally, delay(500) makes the Circuit Playground wait for half of a second before changing the lights again so that we can actually see the new colors.

The complete code

#include "Adafruit_CircuitPlayground.h"

void setup() {
  randomSeed(analogRead(0));
  CircuitPlayground.begin();
}

void loop() {
  if (CircuitPlayground.slideSwitch()) {
    //Loop through all pixels and set them to a random color
    for (int i=0; i<10; i++) {
      CircuitPlayground.setPixelColor(i, CircuitPlayground.colorWheel(random(256)));
    }
    delay(500);
  }
}