// https://starthardware.org/arduino-und-encoder-schaltplan-erklaerung-code/

#include <Adafruit_NeoPixel.h>

#define NUMPIXELS 12
#define LEDPIN 2

Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, LEDPIN, NEO_GRB + NEO_KHZ800);

int encoderPinA = 4;
int encoderPinB = 5;
int encoderPos = 0;
int encoderPinALast = LOW;
int encoderPinANow = LOW;

long colorNew = 65535;
long color = 65535;


void setup() {
  pinMode (encoderPinA, INPUT_PULLUP);
  pinMode (encoderPinB, INPUT_PULLUP);
  Serial.begin (115200);

  delay(150);
  Serial.println("PIXELS");
  
  pixels.begin(); // initialize NeoPixel library.

  //pixels.setBrightness(40);
  //pixels.fill(pixels.Color(217, 101, 0), 0, NUMPIXELS);
  
  pixels.fill(pixels.gamma32(pixels.ColorHSV(65535, 255, 190)), 0, NUMPIXELS);
  pixels.show();
  
  /*
  for(long firstPixelHue = 0; firstPixelHue < 5*65536; firstPixelHue += 256) {
    pixels.rainbow(firstPixelHue);
    pixels.show();
    delay(10);
  }
  */
}

void loop() {
  encoderPinANow = digitalRead(encoderPinA);
  if ((encoderPinALast == HIGH) && (encoderPinANow == LOW)) {
    if (digitalRead(encoderPinB) == HIGH) {
      encoderPos++;
      colorNew += 4096;
    } else {
      encoderPos--;
      colorNew -= 4096;
    }
    
    if (colorNew > 65535) {
      colorNew = 0;
    }
    else if (colorNew < 0) {
        colorNew = 65535;
    }
  }
  encoderPinALast = encoderPinANow;

  if (colorNew != color) {
    color = colorNew;
    pixels.fill(pixels.gamma32(pixels.ColorHSV(color, 255, 100)), 0, NUMPIXELS);
    pixels.show();
    Serial.println(color);
  }
}
