from machine import Pin, PWM
from time import sleep
# Set up PWM for an LED connected to GPIO 2
led = PWM(Pin(2), freq=1000) # Operating at 1 kHz
led.duty(0) # Begin with the LED turned off
# Set up a button on GPIO 0
button = Pin(0, Pin.IN, Pin.PULL_UP) # Enable pull-up resistor
# Initialize brightness settings
duty_cycle = 0
is_increasing = True # Flag to track brightness direction
while True:
# Detect button press (active low)
if not button.value():
led.duty(0) # Turn off the LED while the button is held
duty_cycle = 0 # Reset brightness to zero
else:
# Adjust brightness only when the button is released
if is_increasing:
if duty_cycle < 1023:
duty_cycle += 10 # Brighten the LED
if duty_cycle > 1023: # Limit to maximum value
duty_cycle = 1023
else:
is_increasing = False # Start dimming
else:
if duty_cycle > 0:
duty_cycle -= 10 # Dim the LED
if duty_cycle < 0: # Limit to minimum value
duty_cycle = 0
else:
is_increasing = True # Start brightening
led.duty(duty_cycle) # Apply the current brightness setting
sleep(0.01) # Brief pause for smooth transitions