MicroPython button interrupt on an ESP32
MicroPython on an ESP32 DevKit: Pin.irq() on D15 with the pin’s pull-up counts each press of a button, debounced, and toggles the board’s LED. The whole build, an ESP32 DevKit and 1 more part, runs here in your browser on the firmware below; open it in the editor to change the wiring or the code and run it again.
Teaching? Assign it to your class in one click.
Beginner Runs in your browser. Free, and no account needed.
The parts retail for about $9.10. On Mokxi they're free.
The code
The MicroPython code exactly as the editor opens it. Change a line there and press Run: the board runs it on the official MicroPython firmware, with nothing to compile.
# MicroPython on an ESP32 DevKit: count button presses with an interrupt.
# The button joins D15 to ground. The pin's own pull-up holds it at 1, so a
# press pulls it to 0 and IRQ_FALLING calls pressed().
from machine import Pin
import time
led = Pin(2, Pin.OUT) # the DevKit's blue LED
button = Pin(15, Pin.IN, Pin.PULL_UP)
presses = 0
flag = False
def pressed(pin):
global flag
flag = True # keep a handler short: set a flag
button.irq(trigger=Pin.IRQ_FALLING, handler=pressed)
print("Press the button")
while True:
if flag:
time.sleep_ms(20) # let the contacts stop bouncing
flag = False
if button.value() == 0: # still down: a real press
presses += 1
led.value(not led.value())
print("presses", presses)
time.sleep_ms(5)
Parts list
2 parts, plus the jumper wires. They retail for about $9.10; on Mokxi they're free.
- 1 × ESP32 DevKit V1
- 1 × Pushbutton
How it is wired
2 connections, pin by pin, read from the circuit itself. Each line is one set of pins joined together, by a jumper wire or a breadboard strip.
- ESP32 DevKit V1 pin D15; Pushbutton pin 1a
- Ground: Pushbutton pin 2b
Change it and keep it
Open it in the editor, change the circuit or the code, and keep your version in a free account.