#include <Adafruit_NeoPixel.h>
#define PIX_PIN 5
#define NUM_PIX 8
Adafruit_NeoPixel pixel(NUM_PIX, PIX_PIN, NEO_GRB + NEO_KHZ800);
#define ENCODER_SW 4
#define ENCODER_DT 3
#define ENCODER_CK 2
int pix, pixold; // pixel to be lit
bool colorChange = 0;
void setup() {
pixel.begin(); // start NeoPixel
pinMode(LED_BUILTIN, OUTPUT); // show use of switch
pinMode(ENCODER_SW, INPUT_PULLUP); // pushbutton pin with pullup resistor
pinMode(ENCODER_CK, INPUT); // pin with interrupt
pinMode(ENCODER_DT, INPUT); // pin with interrupt
attachInterrupt(digitalPinToInterrupt(ENCODER_CK), readEncoder, FALLING);
pixel.setPixelColor(0, pixel.Color(0, 255, 0)); // color zeroth pixel green
pixel.show(); // display buffer
}
void loop() {
if (pix != pixold) { // if encoder changed...
pixel.clear(); // clear ws2812
pixel.setPixelColor(pix, pixel.Color(0, 255 * (colorChange == 0), 255 * (colorChange == 1)));
pixel.show(); // send buffer to LEDs
pixold = pix; // store old value
}
if (digitalRead(ENCODER_SW) == LOW) { // read switch
colorChange = !colorChange;
pixel.setPixelColor(pix, pixel.Color(0, 255 * (colorChange == 0), 255 * (colorChange == 1)));
pixel.show(); // send buffer to LEDs
delay(100); // debounce
}
}
void readEncoder() {
int dtValue = digitalRead(ENCODER_DT); // read DATA pin
if (dtValue == HIGH) { // if HIGH
pix++; // add to pixel position
if (pix > 7) pix = 7; // constrain to seven
}
if (dtValue == LOW) {
pix--; // subtract from pixel position
if (pix < 0) pix = 0; // constrain to zero
}
}