Skip to content

Instantly share code, notes, and snippets.

@artem-smotrakov
Created January 5, 2021 21:01
Show Gist options
  • Save artem-smotrakov/63bfcf5ebf7aa2cfc4effefe456c6cd4 to your computer and use it in GitHub Desktop.
Save artem-smotrakov/63bfcf5ebf7aa2cfc4effefe456c6cd4 to your computer and use it in GitHub Desktop.
Reading a photoresistor on ESP32 with MicroPython
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(34)
while True:
# read a value from the LDR
value = ldr.value()
print('value = {}'.format(value))
# a little delay
time.sleep(3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment