#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <Servo.h>

#define COUNT_BUTTON 2
#define START_BUTTON 3
#define INTERVAL_POT A6
#define MOTOR 4
#define SENSOR1 5

int interval, freq, state = 0;
int count[3] = {1, 5, 10};

Adafruit_SSD1306 display = Adafruit_SSD1306(128, 64, &Wire);
Servo shutter;

void setup() 
{
    display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
    shutter.attach(MOTOR);

    pinMode(COUNT_BUTTON, INPUT_PULLUP);
    pinMode(START_BUTTON, INPUT_PULLUP);
    pinMode(INTERVAL_POT, INPUT);
    pinMode(MOTOR, OUTPUT);

    display.clearDisplay();
    display.setTextColor(WHITE);
    display.setTextSize(1);
}

void loop() {

    interval = analogRead(INTERVAL_POT);
    freq = map(interval, 0, 1023, 1, 10);

    if (digitalRead(COUNT_BUTTON) == LOW) {
        state++;
        if (state>2) state=0;
        while(digitalRead(COUNT_BUTTON) == LOW){}
    }

    display.setTextSize(1);
    startScreen(count[state], freq);

    delay(20);

    if (digitalRead(START_BUTTON) == LOW) {
        for(int k=0;k<count[state];k++) {
            display.clearDisplay();
            display.setCursor(0,0);
            if (k<10) display.print("00");
            else if (k<100) display.print("0");
            display.print(k);
            display.display();
            shutter.write(90);
            InputWait(SENSOR1);
            shutter.write(0);
            delay(freq * 1000);   
        }
        finishScreen();
        delay(4000);
    }
}

void startScreen(int c, int f) {
    display.clearDisplay();
    display.setCursor(0, 0);
    display.print("Wiederholungen: ");
    display.println(c);
    display.print("Intervall: ");
    display.print(f);
    display.println(" sec");
    display.display();  
}

void finishScreen() {
    display.clearDisplay();
    display.setCursor(0, 0); 
    display.setTextSize(2);
    display.print("ENDE");
    display.display();    
}

void InputWait(int digitalPin){
  int inputState = 0;
  while(1){
    inputState = digitalRead(digitalPin);
    if (inputState == LOW) {
      return;
    }
  }
}