#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <RotaryEncoder.h>

#define OLED_RESET 4

#define PIN_IN1 2
#define PIN_IN2 3

float freq = 101.5;
int vol = 10;
int rssi = 54;
char buffer[6];
char buffer2[6];
char buffer3[6];
char buffer4[6];
String rsd = "Radio cidade";
char clk[6] = "19:47";
uint16_t textWidth, textHeight;
int16_t x, y;

Adafruit_SSD1306 oled(128, 64);
RotaryEncoder encoder(PIN_IN1, PIN_IN2, RotaryEncoder::LatchMode::TWO03);

void setup()
{
  oled.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  delay(200);
  oled.clearDisplay();
  updateLCD();
}

void loop()
{
  readEncoder();
}

void updateLCD()
{
  oled.setTextColor(SSD1306_WHITE, SSD1306_BLACK);

  if (freq > 100.0) {
    oled.setCursor(0, 32);
    oled.clearDisplay();
  }
  else {
    oled.setCursor(18, 32);
    oled.clearDisplay();
  }

  dtostrf(freq, 2, 1, buffer);
  oled.setTextSize(3);
  oled.print(buffer);



  oled.setCursor(97, 32);
  oled.setTextSize(2);
  oled.print("FM");

  oled.setCursor(92, 47);
  oled.setTextSize(1);
  oled.print("STEREO");

  oled.setCursor(1, 10);
  oled.print("----------------------");

  sprintf(buffer2, "Level:%2d", rssi);
  oled.setCursor(74, 20);
  oled.print(buffer2);
  oled.write(37);

  sprintf(buffer3, "Volum:%2d", vol);
  oled.setCursor(0, 20);
  oled.print(buffer3);
  oled.write(37);

  sprintf(buffer4, "<<<    PM %2s   >>>", clk);
  oled.setCursor(0, 0);
  oled.print(buffer4);

  oled.getTextBounds(rsd, 0, 0, &x, &y, &textWidth, &textHeight);
  oled.setCursor(oled.width() / 2 - textWidth / 2, 56);
  oled.print(rsd);
  oled.fillRect(0, 55, 127, 12, SSD1306_INVERSE);

  oled.display();
}

void readEncoder() {

  static int pos = 0;
  encoder.tick();

  int newPos = encoder.getPosition();
  if (pos != newPos) {

    if (newPos > pos)
      freq = freq - 0.1;
    if (newPos < pos)
      freq = freq + 0.1;

    pos = newPos;

    if (freq > 108.0)freq = 108.0;
    if (freq < 87.0)freq = 87.0;

    updateLCD();
  }
}