from machine import Pin,ADC 
import time, os
import network, gc, urequests

def df():
    s = os.statvfs('//')
    return ('{0} MB'.format((s[0]*s[3])/1048576))


def free(full=False, collect=False):
    if collect:
        gc.collect()
    F = gc.mem_free()
    A = gc.mem_alloc()
    T = F+A
    P = '{0:.2f}%'.format(F/T*100)
    if not full:
        return P
    else:
        return ('Total:{0} Free:{1} ({2})'.format(T, F, P))

# # while True:
#     print(free(True, False))
#     time.sleep(1)

gc.enable()
led = Pin(15,Pin.OUT) 
light_adc = ADC(32)

print('Connecting to\n  WiFi...')
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect('Wokwi-GUEST', '')
while not wifi.isconnected():
    pass
print('Connecting\n  success...')

while 1 :
    light = light_adc.read_u16()
    GAMMA = 0.7
    RL10 = 50
    analogValue = light;
    voltage = analogValue / 65535 * 5;
    resistance = 2000 * voltage / (1 - voltage / 5);
    lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA));
    print(free(True, False))

    # # try:
    # response = urequests.get('https://api.thingspeak.com/update?api_key=3Y5KGPNSI0GDFSCG&field2={}'.format(lux))
    # print(response)
    # # except:
    # #     print('Error:  failed')
    time.sleep(5)