from machine import Pin, SoftI2C, ADC
from math import log
import time
import ssd1306
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)
# create an object ADC
self.adc = ADC(Pin(pin))
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(34)
led = Pin(23, Pin.OUT)
# ESP32 Pin assignment
i2c = SoftI2C(sda=Pin(21), scl=Pin(22))
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
def show_value(raw):
oled.text("Value:", 30, 20)
oled.text(str(raw), 30, 30)
oled.show()
def clear():
oled.fill(0)
oled.show()
prev_value = ldr.value()
show_value(prev_value)
while True:
c_value = ldr.value()
if c_value != prev_value:
clear()
show_value(c_value)
prev_value = c_value
if c_value < 20:
led.on()
else:
led.off()
time.sleep(3)