Project 5.01 Cycling Colors with a Button
The goal of this project is to change the color of the Neopixels every time SW1 is pressed. The colors will cycle between red, green and blue.
Project Code:
/////////////////////////////////////////////////
// 5.01 Cycling Colors With a Button
#include <Adafruit_NeoPixel.h>
byte dataPin = 10;
byte numberOfPixels = 2;
byte brightness = 10;
byte LEDSetting = 0;
byte SW1 = 1;
byte buttonState = 0;
bool pressed = 0;
Adafruit_NeoPixel pixels(numberOfPixels, dataPin, NEO_GRB + NEO_KHZ800);
void setup() {
pinMode(SW1, INPUT);
pixels.begin();
pixels.setBrightness(brightness);
pixels.show();
}
void loop() {
buttonState = digitalRead(SW1);
if (buttonState == pressed) {
LEDSetting++;
if (LEDSetting > 2) {
LEDSetting = 0;
}
if (LEDSetting == 0) {
pixels.setPixelColor(0, pixels.Color(255, 0, 0));
pixels.setPixelColor(1, pixels.Color(255, 0, 0));
}
else if (LEDSetting == 1) {
pixels.setPixelColor(0, pixels.Color(0, 255, 0));
pixels.setPixelColor(1, pixels.Color(0, 255, 0));
}
else {
pixels.setPixelColor(0, pixels.Color(0, 0, 255));
pixels.setPixelColor(1, pixels.Color(0, 0, 255));
}
pixels.show();
delay(250);
}
}
///////////////////////////////////////////////////
*If you’re copying and pasting the code, or typing from scratch, delete everything out of a new Arduino sketch and paste / type in the above text.
In the loop() function, the first thing we do is check to see if a SW1 is being pressed.
buttonState = digitalRead(SW1);
if (buttonState == pressed) {
In this example a variable called LEDSetting is used to keep track of which color should be displayed. Every time the button is pressed, this variable is incremented by 1.
LEDSetting++;
After incrementing that variable, it needs to be checked to see if it is out of the settings range (0 - 2). If it is, it is reset to 0.
if (LEDSetting > 2) {
LEDSetting = 0;
}
Next, the appropriate colors are loaded into the Neopixels based on the LEDSetting variable according to the table below:
| LEDSetting Value | Neopixel Color |
|---|---|
| 0 | Red |
| 1 | Green |
| 2 | Blue |
if (LEDSetting == 0) {
pixels.setPixelColor(0, pixels.Color(255, 0, 0));
pixels.setPixelColor(1, pixels.Color(255, 0, 0));
}
else if (LEDSetting == 1) {
pixels.setPixelColor(0, pixels.Color(0, 255, 0));
pixels.setPixelColor(1, pixels.Color(0, 255, 0));
}
else {
pixels.setPixelColor(0, pixels.Color(0, 0, 255));
pixels.setPixelColor(1, pixels.Color(0, 0, 255));
}
To display the new color we have to update the Neopixels using the show() function.
pixels.show();
Lastly, a crude debounce is used to prevent more than one press being read at a time.
delay(250);
}
}
///////////////////////////////////////////////////

