#include <U8g2lib.h>

#define LDRPIN  32
#define GAMMA   0.7
#define RL10    50

U8X8_SSD1306_128X64_NONAME_HW_I2C display(U8X8_PIN_NONE);

uint32_t StartTime;
uint32_t DataCaptureDelay;

uint32_t getStartTime() {
  return millis() + DataCaptureDelay;
}

void drawBaseOLED() {
  display.clearDisplay();
  display.drawString(2, 1, "I LOVE IOT");
}

void drawUpdateOLED(float lux) {
  display.clearLine(4);
  display.drawString(1, 4, "LUX: ");
  display.setCursor(7, 4);
  display.print(lux);
}

void setup() {
  Serial.begin(115200);
  
  pinMode(LDRPIN, INPUT);

  display.begin();
  display.setPowerSave(0);
  display.setFont(u8x8_font_pxplusibmcgathin_f);
  drawBaseOLED();

  DataCaptureDelay = 100;
  StartTime = getStartTime();
}

void loop() {
  if (millis() > StartTime) {
    int analogValue = analogRead(LDRPIN);
    float voltage = analogValue / 4096. * 5;
    float resistance = 2000 * voltage / (1 - voltage / 5);
    float lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA));

    drawUpdateOLED(lux);

    StartTime = getStartTime();
  }
}