#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
#include <avr/power.h>
#endif
//
#define outA 5
#define outB 6
#define sw 4
#define PIN 8
//
int previousA = 1;
int previousB = 1;
int previousPush = 1;
int cwCount = 0;
int ccwCount = 0;
int whiteBrightness = 125;
bool whiteOn = false;
unsigned long debounce = 0;
//
Adafruit_NeoPixel ledBar = Adafruit_NeoPixel(16, PIN, NEO_GRBW + NEO_KHZ800);
//
void setup() {
#if defined (__AVR_ATtiny85__)
if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
#endif
Serial.begin(115200);
//
pinMode(outA, INPUT_PULLUP);
pinMode(outB, INPUT_PULLUP);
pinMode(sw, INPUT_PULLUP);
//
ledBar.begin();
ledBar.show();
for ( int i = 0; i < 16; i++ ) {
ledBar.setPixelColor(i, 0, 0, 0 );
}
ledBar.show();
}
//
void loop() {
int currentA = digitalRead(outA);
int currentB = digitalRead(outB);
//
if ( ( millis() - debounce ) > 1 ) {
if ( ( currentA != previousA ) || ( currentB != previousB ) ) {
if ( currentA == 0 ) { // A 입력이 "0"일때
if ( currentB == 0 ) { // B 입력이 "0"일때
// 입력이 0,0 일때의 처리
if ( ( cwCount == 1 ) ) {
cwCount = 2;
} else if ( ( ccwCount == 1 ) ) {
ccwCount = 2;
}
} else { // B 입력이 "1"일때
// 입력이 0,1 일때의 처리
if ( ( cwCount == 0 ) && ( ccwCount == 0 ) ) {
cwCount = 1;
} else if ( ( ccwCount == 2 ) ) {
ccwCount = 3;
}
}
} else { // A 입력이 "1"일때
if ( currentB == 0 ) { // B 입력이 "0"일때
// 입력이 1,0 일때의 처리
if ( ( cwCount == 2 ) ) {
cwCount = 3;
} else if ( ( cwCount == 0 ) && ( ccwCount == 0 ) ) {
ccwCount = 1;
}
} else { // B 입력이 "1"일때
// 입력이 1,1 일때의 처리
if ( ( cwCount == 3 ) ) {
whiteBrightness += 5;
if ( whiteBrightness > 255 ) whiteBrightness = 255;
if ( whiteOn ) {
for ( int i = 0; i < 16; i++ ) {
ledBar.setPixelColor(i, 0, 0, 0, whiteBrightness);
}
ledBar.show();
}
cwCount = 0;
} else if ( ( ccwCount == 3 ) ) {
whiteBrightness -= 5;
if ( whiteBrightness < 1 ) whiteBrightness = 1;
if ( whiteOn ) {
for ( int i = 0; i < 16; i++ ) {
ledBar.setPixelColor(i, 0, 0, 0, whiteBrightness);
}
ledBar.show();
}
ccwCount = 0;
}
}
}
previousA = currentA;
previousB = currentB;
}
// 엔코더의 push 스위치 처리
int currentPush = digitalRead(sw);
//
if ( currentPush != previousPush ) {
if ( currentPush == 0 ) {
if ( whiteOn ) {
whiteOn = false;
for ( int i = 0; i < 16; i++ ) {
ledBar.setPixelColor(i, 0, 0, 0, whiteBrightness );
}
ledBar.show();
} else {
whiteOn = true;
for ( int i = 0; i < 16; i++ ) {
ledBar.setPixelColor(i, 0, 0, 0, whiteBrightness);
}
ledBar.show();
}
}
previousPush = currentPush;
}
debounce = millis();
}
}