#include <CheapStepper.h>
#include <Adafruit_NeoPixel.h>

#define LED_PIN_OUT 6
#define LED_NUM 5
#define TWO_ROTATIONS 8192

Adafruit_NeoPixel strip = Adafruit_NeoPixel(LED_NUM + 1, LED_PIN_OUT, NEO_GRB + NEO_KHZ800);

CheapStepper stepper;
// here we declare our stepper using default pins:
// arduino pin <--> pins on ULN2003 board:
// 8 <--> IN1
// 9 <--> IN2
// 10 <--> IN3
// 11 <--> IN4

int g_value = 0;
int ring_count = 0;
boolean toggle_open = false;
boolean toggle_close = false;

boolean dread_array[4] = {false, false, false, false};
int degree = 0;

void setup() {
  pinMode (LED_PIN_OUT, OUTPUT);
  pinMode (2, INPUT_PULLUP);
  pinMode (3, INPUT_PULLUP);
  pinMode (4, INPUT_PULLUP);
  pinMode (5, INPUT_PULLUP);
  strip.begin();
  strip.show();
  Serial.begin(9600);
}


/*
 * this function takes in the parameter for the digital pin to read, and then assigns the value to the dread_array location (-2)
 * since we're using pins 2,3,4,5, and want them to be in the array at locations 0,1,2,3
 * 
 */
boolean dread (int d) {
  if (digitalRead(d) == HIGH) {
    if (dread_array[d - 2] == true){
      dread_array[d - 2] = 0;
    }
  } else if (digitalRead(d) == LOW) {
    dread_array[d - 2] = true;
  }
}




void loop() {
  
  int n = stepper.getStep ();
  if (n % 128 == 0) {
    Serial.print (n);
    Serial.print (":");
    Serial.println (degree);
  }
  // read in the digital pin values
  for (int i = 2; i < 6; i++) {
    dread(i);
  }

  // open the eye
  if (dread_array[0]) {
    toggle_open = true;
    toggle_close = false;
  }

  // close the eye
  if (dread_array[3]) {
    toggle_close = true;
    toggle_open = false;
    
  }

  // step the eye one degree at a time
  if (dread_array[1] || dread_array[2]) {
    toggle_close = false;
    toggle_open = false;
  }
  if (dread_array[1]) {
    stepper.stepCCW();
  } else if (dread_array[2]) {
    stepper.stepCW();
  }


  // toggled the animation and turning on the LED
  if (toggle_open && degree < TWO_ROTATIONS) {
    degree++;
    stepper.stepCCW();
    if (degree % 30 == 0) g_value ++;
    if (g_value > 255) g_value = 255;
  } else if (toggle_close && degree > 0) {
    degree--;
    stepper.stepCW();
    if (degree % 30 == 0) g_value --;
    if (g_value < 0) g_value = 0;
  }

  if (degree > TWO_ROTATIONS) degree = TWO_ROTATIONS;
  if (degree < 0) degree = 0;

  if (degree % 30 == 0) {
    int g = g_value - 50;
    if (g < 0) g = 0;
    for (int i = 0; i < LED_NUM; i++) strip.setPixelColor (i, 0, g,0);
    strip.setPixelColor (ring_count++ % LED_NUM, 0, g_value, 0);
    strip.show();
  }

  if (degree >= TWO_ROTATIONS) {
    for (int i = 0; i < LED_NUM; i++) strip.setPixelColor (i, 0, (245 + ring_count++) % 255, 0);
    strip.show();
    delay(20);

  }
}
