from machine import ADC, Pin, I2C
from utime import sleep
import ssd1306
from math import pow

# Constants for the photoresistor's attributes
GAMMA = 0.7
RL10 = 50

def calculate_lux(analogValue):
    # ESP32 ADC is 12-bit, so max value is 4095 and voltage range is 5V
    voltage = analogValue / 4095 * 5 
    resistance = 2000.0 * voltage / (1 - voltage / 5)
    lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA))
    return int(lux)

# ADC setup
adc = ADC(Pin(34))
adc.atten(ADC.ATTN_11DB)
# ESP32 Pin assignment 
i2c = I2C(0, scl=Pin(22), sda=Pin(21))

oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)

while True:
    reading = adc.read()
    lux = calculate_lux(reading)
    # Clear display
    oled.fill(0)
    adc_str = f'Pot Value: {lux:5}'
    oled.text(adc_str, 0, 0)
    oled.show()
    sleep(0.1)