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

#define ENCODER_CLK 2
#define ENCODER_DT  3

#define SERVO_PIN 9

oled displays;
Servo s;

int lastClk = HIGH;
int rotation;
int inc = 5;

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

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

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

  displays.run();
  displays.setCursor(0, 0);
  displays.setText(2, SSD1306_WHITE);
  displays.printText(String("Uhel: ") + rotation);
}

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 += inc;
    }
    else if (newClk == LOW && dtValue == LOW)
    {
      rotation -= inc;
    }

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

    s.write(rotation);
    
    displays.printText(String("Uhel: ") + rotation);
  }
}