# from machine import Pin, ADC
# from time import sleep
# ldr = ADC(27)
# while True:
# voltage = ldr.read_u16() / (65535 * 3.3)
# resistance = 2000 * voltage / (1 - voltage / 5);
# lux = pow(50 * 1e3 * pow(10, 0.7) / resistance, (1 / 0.7));
# print(lux)
# sleep(2)
# #(250 / ldr.read_u16())-50
# from machine import ADC, Pin
# import time
# class LDR:
# """This class read a value from a light dependent resistor (LDR)"""
# def __init__(self, pin, min_value=0, max_value=100):
# """
# Initializes a new instance.
# :parameter pin A pin that's connected to an LDR.
# :parameter min_value A min value that can be returned by value() method.
# :parameter max_value A max value that can be returned by value() method.
# """
# if min_value >= max_value:
# raise Exception('Min value is greater or equal to max value')
# # initialize ADC (analog to digital conversion)
# self.adc = ADC(Pin(pin))
# # set 11dB input attenuation (voltage range roughly 0.0v - 3.6v)
# self.adc.atten(ADC.ATTN_11DB)
# self.min_value = min_value
# self.max_value = max_value
# def read(self):
# """
# Read a raw value from the LDR.
# :return A value from 0 to 4095.
# """
# return self.adc.read()
# def value(self):
# """
# Read a value from the LDR in the specified range.
# :return A value from the specified [min, max] range.
# """
# return (self.max_value - self.min_value) * self.read() / 4095
# # initialize an LDR
# ldr = LDR(27, 0, 65537)
# while True:
# # read a value from the LDR
# value = ldr.value()
# print('value = {}'.format(value))
# # a little delay
# time.sleep(3)
from machine import Pin, ADC
from time import sleep
ldr = ADC(27)
MAX_ADC_READING = 65535;
ADC_REF_VOLTAGE = 3.3;
REF_RESISTANCE = 50;
LUX_CALC_SCALAR = 12518931;
LUX_CALC_EXPONENT = -1.405;
while True:
rawData = ldr.read_u16()
print(f"Raw data: {rawData}")
resistorVoltage = rawData / MAX_ADC_READING * ADC_REF_VOLTAGE;
print(f"Resistor voltage: {resistorVoltage}")
ldrVoltage = ADC_REF_VOLTAGE - resistorVoltage;
print(f"LDR voltage: {ldrVoltage}")
ldrResistance = ldrVoltage/resistorVoltage * REF_RESISTANCE;
print(f"LDR resistance: {ldrResistance}")
ldrLux = LUX_CALC_SCALAR * pow(ldrResistance, LUX_CALC_EXPONENT);
print(f"Lux: {ldrLux}")
print("==========")
sleep(2)