I am trying to make a particular pixel in a neopixel strip, turn green, red or blue depending which button has been pressed and to stay on until pressed off again (like a toggle), but currently when I press one of the buttons it flashes the correct colour when button is pressed down but isn't acting as a toggle switch and then goes to a white light.
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
#include <avr/power.h> // Required for 16 MHz Adafruit Trinke
#endif
#define BUTTON_PIN1 2
#define BUTTON_PIN2 10
#define BUTTON_PIN3 11
#define PIXEL_PIN 6 // Digital pin 6 connected to the NeoPixels.
#define PIXEL_COUNT 13 // Number of NeoPixels
// Declare our NeoPixel strip object:
Adafruit_NeoPixel strip(PIXEL_COUNT, PIXEL_PIN, NEO_GRB + NEO_KHZ800);
boolean oldState1 = HIGH;
boolean newState1 = HIGH;
boolean toggle1 = LOW;
boolean oldState2 = HIGH;
boolean newState2 = HIGH;
boolean toggle2 = LOW;
boolean oldState3 = HIGH;
boolean newState3 = HIGH;
boolean toggle3 = LOW;
void setup() {
Serial.begin(9600);
pinMode(BUTTON_PIN1, INPUT_PULLUP);
pinMode(BUTTON_PIN2, INPUT_PULLUP);
pinMode(BUTTON_PIN3, INPUT_PULLUP);
strip.begin(); // Initialize NeoPixel strip object (REQUIRED)
strip.show(); // Initialize all pixels to 'off'
}
void loop() {
updateButtonState1();
updateButtonState2();
updateButtonState3();
}
void updateButtonState1() {
// Get current button state.
newState1 = digitalRead(BUTTON_PIN1);
if ((newState1 == LOW) && (oldState1 == HIGH)) {
delay(50);
newState1 = digitalRead(BUTTON_PIN1);
if (newState1 == LOW) {
toggle1 = !toggle1;
}
}
oldState1 = newState1;
if (toggle1 == HIGH) {
strip.setPixelColor(2, 245, 15, 15); //electrical/fire hazard (red)
} else {
strip.setPixelColor(2, 0, 0, 0);
}
strip.show(); // Update strip with new contents
}
void updateButtonState2() {
// Get current button state.
newState2 = digitalRead(BUTTON_PIN2);
if ((newState2 == LOW) && (oldState2 == HIGH)) {
delay(50);
newState2 = digitalRead(BUTTON_PIN2);
if (newState2 == LOW) {
toggle2 = !toggle2;
}
}
oldState2 = newState2;
if (toggle2 == HIGH) {
strip.setPixelColor(2, 13, 50, 190); //Leak (blue)
} else {
strip.setPixelColor(2, 0, 0, 0);
}
strip.show(); // Update strip with new contents
}
void updateButtonState3() {
// Get current button state.
newState3 = digitalRead(BUTTON_PIN3);
if ((newState3 == LOW) && (oldState3 == HIGH)) {
delay(50);
newState3 = digitalRead(BUTTON_PIN3);
if (newState3 == LOW) {
toggle3 = !toggle3;
}
}
oldState3 = newState3;
if (toggle3 == HIGH) {
strip.setPixelColor(2, 58, 233, 65); //bins/recylcing (green)
} else {
strip.setPixelColor(2, 0, 0, 0);
}
strip.show(); // Update strip with new contents
}