#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <Servo.h>
#include "aio.h"

#define ENCODER_CLK 2
#define ENCODER_DT  3

#define SERVO_PIN 9

oled displays;
Servo s;

const int cw = SSD1306_WHITE;
int lastClk = HIGH;
int rotation;

void setup() {
  Serial.begin(115200);

  pinMode(ENCODER_CLK, INPUT);
  pinMode(ENCODER_DT, INPUT);

  s.attach(SERVO_PIN);
  s.write(0);

  display.clearDisplay();
  display.setCursor(0,0);
  display.setTextSize(_textSize);
  display.setTextColor(_textColor);
  display.println(_text);
  display.display();
}

void loop() {
  int newClk = digitalRead(ENCODER_CLK);

  if (newClk != lastClk) {
    // There was a change on the CLK pin
    lastClk = newClk;
    int dtValue = digitalRead(ENCODER_DT);
    
    if (newClk == LOW && dtValue == HIGH) {
      rotation += 5;
    }
    else if (newClk == LOW && dtValue == LOW) {
      rotation -= 5;
    }

    if (rotation > 180)
    {
      rotation = 0;
    }
    else if (rotation < 0)
    {
      rotation = 180;
    }

    s.write(rotation);

    display.clearDisplay();
    display.setCursor(0,0);
    display.setTextSize(_textSize);
    display.setTextColor(_textColor);
    display.println(_text);
    display.display();
  }
}