# ESP32 and Mycropython: Programming your Hardware
# Author: Mordechai Bar Natan
#
# Lesson 3: Toggle the LED with a button
# https://wokwi.com/projects/394060853608068097
#
# Remember:
# On a LED, the long leg is the anode (+). Connect it to pin #2.
# The short leg is the cathode (-). Connect it to GND.
# On a momentary switch (button), connect one side to pin #16 and the other side to GND.
#
# References
# https://docs.micropython.org/en/latest/library/machine.Pin.html
from machine import Pin
from time import sleep
# Connect a LED with pin #2
red_led_pin = 2
# Connect a momentary switch to pin #16
button_pin = 4
red_led_state = 0
button_state = 0
red_led = Pin(red_led_pin, Pin.OUT)
button = Pin(button_pin, Pin.IN, Pin.PULL_UP)
# toggle the LED when the button is pressed
while True:
last_state = button_state
button_state = button.value()
if button_state == 0 and last_state == 1:
red_led_state = not(red_led_state)
red_led.value(red_led_state)
sleep(0.1)