pb pbaumgarten.com
Courses Python Reference Button press
Login
Course
Python Reference
Topic
MicroPython
Python Reference

Button press

Wiring:

Button Leg Connect To
Leg 1 GPIO pin (e.g., GPIO 0)
Leg 2 GND

Use Pin.PULL_UP to enable the internal pull-up resistor. Without it, the pin "floats" and gives unreliable readings.

Logic: - Button NOT pressed: pin reads 1 (HIGH, pulled up to 3.3V) - Button pressed: pin reads 0 (LOW, connected to GND)

This is called active-low.

import machine, time

# Using GP27 and GND for button
button = machine.Pin(27, machine.Pin.IN, machine.Pin.PULL_UP)
print("Waiting...")
while True:
    if not button.value():
        print("Button pressed")
        time.sleep(0.3)
    time.sleep(0.1)