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(35)
led1 = pin(2, Pin.OUT)
led2 = pin(4, Pin.OUT)
while True:
# read a value from the LDR
value = ldr.value()
print('value = {}'.format(value))
if value <=50
led1.on()
else value >= 80;
led2.on
else:
led1.off
led2.off
timesleep(0.5)
# a little delay
time.sleep(3)
esp:VIN
esp:GND.2
esp:D13
esp:D12
esp:D14
esp:D27
esp:D26
esp:D25
esp:D33
esp:D32
esp:D35
esp:D34
esp:VN
esp:VP
esp:EN
esp:3V3
esp:GND.1
esp:D15
esp:D2
esp:D4
esp:RX2
esp:TX2
esp:D5
esp:D18
esp:D19
esp:D21
esp:RX0
esp:TX0
esp:D22
esp:D23
ldr1:VCC
ldr1:GND
ldr1:DO
ldr1:AO
led1:A
led1:C
r1:1
r1:2