#include <Adafruit_NeoPixel.h> // Add the NeoPixel library

#ifdef __AVR__
  #include <avr/power.h>
#endif

// Defining variables for NeoPixel

#define PIN        6
#define NUMPIXELS 16

// Adafruit NeoPixel Sh*t

Adafruit_NeoPixel pixels(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);
#define DELAYVAL 10

// Defining variables for rotary encoder

#define ENCODER_CLK 2
#define ENCODER_DT  3

void setup() {

  // Setup pins

  pinMode(5, OUTPUT);
  pinMode(4, INPUT_PULLUP);
  digitalWrite(4, HIGH);
  pinMode(3, INPUT_PULLUP);
  pinMode(13, OUTPUT);
  digitalWrite(13, HIGH);
  pinMode(12, INPUT_PULLUP);
  pinMode(ENCODER_CLK, INPUT);
  pinMode(ENCODER_DT, INPUT);

  // Attaching an interupt to call the function "readEncoder"

attachInterrupt(digitalPinToInterrupt(ENCODER_CLK), readEncoder, FALLING);

  // Serial Baud Rate

  Serial.begin(115200);

  // Adafruit_NeoPixel Sh*t

#if defined(__AVR_ATtiny85__) && (F_CPU == 16000000)
  clock_prescale_set(clock_div_1);
#endif

  // Starts NeoPixel output

  pixels.begin();           // INITIALIZE NeoPixel pixel object (REQUIRED)
  pixels.show();            // Turn OFF all pixels ASAP
}

// Defining variables

int i = 0;
int x = 0;
int R = 0;
int G = 0;
int B = 0;
int encoder_count = 0;
int brightness = 1;

void readEncoder() {
  int valueDT = digitalRead(ENCODER_DT);
  i = 0;
  if (valueDT == HIGH) {
    encoder_count++;
    Serial.println(encoder_count);
    brightness = 20;
    if (x==0) {
      while(i<NUMPIXELS) {
        pixels.setPixelColor(i, pixels.Color(0, 0, B+brightness));
        pixels.show();
        delay(DELAYVAL);
        i++;
      }
    }
    if (x==1) {
      while(i<NUMPIXELS) {
        pixels.setPixelColor(i, pixels.Color(R+brightness, G+brightness, B+brightness));
        pixels.show();
        delay(DELAYVAL);
        i++;
      }
    }
  }
  if (valueDT == LOW) {
    encoder_count--;
    Serial.println(encoder_count);
    brightness = -20;
    if (x==0) {
      while(i<NUMPIXELS) {
       pixels.setPixelColor(i, pixels.Color(0, 0, B+brightness));
        pixels.show();
        delay(DELAYVAL);
        i++;
      }
    }
    if (x==1) {
      while(i<NUMPIXELS) {
        pixels.setPixelColor(i, pixels.Color(R+brightness, G+brightness, B+brightness));
        pixels.show();
        delay(DELAYVAL);
        i++;
      }
    }
  }
}

void loop() {
  if (x==0 && digitalRead(4) == LOW) {
    B = 150;
    R = 0;
    G = 0;
    i = 0;
    while(i<NUMPIXELS) {
      pixels.setPixelColor(i, pixels.Color(R, G, B+brightness));
      pixels.show();
      delay(DELAYVAL);
      i++;
    }
  x = 1;
  }
  if (x==1 && digitalRead(4) == LOW) {
    R = 150;
    G = 150;
    i = 0;
    while(i<NUMPIXELS) {
      pixels.setPixelColor(i, pixels.Color(R+brightness, G+brightness, B+brightness));
      pixels.show();
      delay(DELAYVAL);
      i++;
    }
    x = 0;
  }
}