from machine import Pin
import time
# Pin setup
BUTTON_PIN = 18 # Button connected to GPIO18
LED_PIN = 15 # LED connected to GPIO15
# Initialize button and LED
button = Pin(BUTTON_PIN, Pin.IN, Pin.PULL_UP) # Button with pull-up resistor
led = Pin(LED_PIN, Pin.OUT) # LED as output
def main():
"""Main function to toggle the LED with a button press."""
led_state = True # LED initially OFF
previous_button_state = 0 # Button not pressed initially (pull-up state is HIGH)
print("Press the button to toggle the LED.")
while True:
# Read the current state of the button
current_button_state = button.value()
if current_button_state == 1 and previous_button_state == 0:
# Button was just pressed
led_state = not led_state # Toggle the LED state
led.value(led_state) # Update the LED state
print("LED ON" if led_state else "LED OFF")
time.sleep(0.3) # Debounce delay to avoid multiple toggles
# Update the previous button state
previous_button_state = current_button_state
time.sleep(0.01) # Short delay for smooth looping
# Run the main function
if __name__ == "__main__":
main()