# mPy - LDR exercise with 0% and 100% calibration.
#    On esp32 pins 34-39 are input only.
# copyright by Anthony Vogelaar, Perth Scotland
# rev 0.10  2025-04-23  initial release

# https://docs.micropython.org/en/latest/esp32/quickref.html

import	time
from	machine		import	Pin, ADC

# ==================== hardware =========================

ldr    = ADC(35, atten=ADC.ATTN_11DB)		# 0.15 .. 2.45V
btn000 = Pin(14, Pin.IN, Pin.PULL_UP)		# calibrate button red      0%
btn100 = Pin(27, Pin.IN, Pin.PULL_UP)		# calibrate button yellow 100%

# ====================== Button =========================

# debounce button class
class Button:
    
    def __init__(self, btn):				# btn is instance of Pin
        self.btn   = btn
        self.count = 0						# debounce counter
        
        
    # call repeatedly ex @ 50 mSec
    def exe(self):
        if self.btn():						# if not pressed
            self.count = 0					
        elif self.count < 3:				# else pressed
            self.count += 1
            if self.count == 3: return True	# three consecutive samples low
                                            # else return None
            
# ====================== main ===========================

def main():
    btn_000   = Button(btn000)				# Button Red      0%
    btn_100   = Button(btn100)				# Button Yellow 100%
    level_000 = 0
    level_100 = 4095
    while True:
        y1 = ldr.read()						# 0..4095
        y2 = int(100 * (y1 - level_000) / (level_100 - level_000))
#        print(f'{y2:4}', end='')			# cpmpact shell presentation
        print(y2)							# for plotter
        if btn_000.exe(): level_000 = y1	# if red    button pressed for 0%
        if btn_100.exe(): level_100 = y1	# if yellow button pressed for 100% calibration
        time.sleep_ms(50)					# loop period
        
        
main()

# ======================= end ===========================
