import machine, time, math
from machine import Pin, ADC, SoftI2C
from i2c_lcd import LiquidCrystalI2C
# LDR Characteristics
GAMMA = 0.7
RL10 = 50
#LCD characteristics
LCD_COLS = 20
LCD_ROWS = 4
# Intantiate the lcd object from the I2C class
i2c = SoftI2C(sda=Pin(21), scl=Pin(22))
lcd = LiquidCrystalI2C(i2c, 0x27, LCD_COLS, LCD_ROWS)
''' Two function that return the LDR LUX in raw value and in percentage '''
class LDR:
def __init__(self, pin):
self.ldr = machine.ADC(Pin(pin))
self.ldr.atten(ADC.ATTN_11DB)
self.ldr.width(ADC.WIDTH_12BIT)
def get_raw_value(self):
adc_value = self.ldr.read_u16()/64
voltage = adc_value / 1024. * 5
resistance = 2000 * voltage / (1 - voltage / 5)
return (pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA)), resistance)
def get_light_percentage(self):
return round(self.get_raw_value()/65535*100,2)
ldr = LDR(27)
while True:
LUX, Resistance =ldr.get_raw_value()
if (LUX >5000):
state = "Bright!"
elif(LUX>50 and LUX<=5000):
state = "Light!"
else:
state ="Dark! "
# Display the temperature values in both Celsius and Fahrenheit
lcd.backlight()
lcd.set_cursor(0, 0)
lcd.print("ROOM State: \n" + state)
lcd.set_cursor(0, 2)
lcd.print('LDR Lux: %.2f \n' % LUX)
lcd.set_cursor(0, 3)
lcd.print('LDR Res: %.2f' % Resistance)
lcd.display()
time.sleep(.1)