#include <U8g2lib.h>

#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64

// BATTERY LEVEL
#define BAT_X_POS  90
#define BAT_Y_POS   2
#define BAT_HEIGHT  6
#define BAT_LENGTH  8
#define BAT_LOW     3000
#define BAT_FULL    3400
#define LOW_BAT     "LOW BAT"

// RADIO LEVEL
#define RADIO_LEVEL_X_POS 110
#define RADIO_LEVEL_Y_POS 8

int f_new = 1013;
boolean lowVolts = false;
long volts;
char tmp[12];

U8G2_SSD1306_128X64_NONAME_1_HW_I2C oled(U8G2_R0);

void setup() {
  oled.begin();
  delay(1000);
  showFrequency();
}

void loop() {
  showFrequency();

}

void showFrequency() {

  oled.firstPage();
  

  do {
    oled.setFont(u8g2_font_fub14_tf);
    // FREQUENCIA
    dtostrf(f_new * 0.1, 3, 1, tmp);
    //tmp = (char)f_new;
    if (f_new > 999)
      oled.drawStr(9,32, tmp);
    else
      oled.drawStr(20, 32, tmp);

    oled.setFont(u8g2_font_fub11_tf);
    oled.drawStr(64, 32, "MHz");

    // BATERIA
    oled.drawBox(BAT_X_POS + BAT_LENGTH, BAT_Y_POS + 2, 2, 2);
    oled.drawFrame(BAT_X_POS, BAT_Y_POS, BAT_LENGTH, BAT_HEIGHT);

    if (volts > BAT_LOW) {
      oled.drawBox(BAT_X_POS, BAT_Y_POS, ((BAT_LENGTH - 2) * (volts - BAT_LOW)) / (BAT_FULL - BAT_LOW), BAT_HEIGHT);
    }

    // DIAL
    for (unsigned char i = 0; i < 8; i++) {
      oled.drawVLine(RADIO_LEVEL_X_POS + (2 * i), RADIO_LEVEL_Y_POS - i, i);
    }

     oled.setFont(u8g2_font_fub14_tf);
      if (lowVolts) {
        //oled.drawStr((SCREEN_WIDTH-u8g2.getStrWidth(LOW_BAT))/2,36, LOW_BAT);
      } else {
        //oled.drawStr((SCREEN_WIDTH-u8g2.getStrWidth(RDSName))/2,36, RDSName);
      }

    oled.setFont(u8g2_font_u8glib_4_tf);
    oled.drawLine(0, SCREEN_HEIGHT - 1, SCREEN_WIDTH - 1, SCREEN_HEIGHT - 1);

    for (int f = 860; f <= 1080; f += 10) {

      unsigned int x = ((f - 860) * 12) / ((1080 - 860) / 10);

      if (f % 50 == 0) {
        oled.drawVLine(x + 4, SCREEN_HEIGHT - 8, 8);
        sprintf(tmp, "%d", (unsigned int)f / 10);
        oled.drawStr(x, SCREEN_HEIGHT - 12, tmp);
      } else {
        oled.drawVLine(x + 4, SCREEN_HEIGHT - 4, 4);
      }
    }

    unsigned int x = 4 + (((f_new) - 860) * 12) / ((1080 - 860) / 10);

    oled.drawTriangle(x - 3, 54, x, 60, x + 3, 54);

  } while (oled.nextPage());

}