Control an LED with a push button switch. When the button is pressed the LED turns ON; when released it turns OFF. Introduces the concept of input → control → output.
This 4-pin push button is a 2-pole switch. The two pins on each side are internally connected. When the button is pressed, the left and right sides connect, completing the circuit.

Left pins are always connected to each other; right pins are always connected to each other. Pressing the button bridges left and right.


Connections:

The internal pull-up (Pin.PULL_UP) in software replaces the need for an external pull-up resistor in this case, but the schematic uses external resistors for clarity.
Disconnect all power before building the circuit. Reconnect once verified.
File: 01_first_examples/code/ButtonAndLed.py
from machine import Pin
led = Pin(2, Pin.OUT)
# create button object from pin13, Set Pin13 to Input
button = Pin(13, Pin.IN, Pin.PULL_UP)
try:
while True:
if not button.value():
led.value(1) # button pressed → LED on
else:
led.value(0) # button released → LED off
except:
pass
Micropython_Codes/02.1_ButtonAndLed/.ButtonAndLed.py.Sets GPIO13 as input with the internal pull-up resistor enabled. When the button is not pressed, the pin reads HIGH (1). When pressed (connected to GND), it reads LOW (0).
button = Pin(13, Pin.IN, Pin.PULL_UP)
button.value() returns 0 when pressed. not 0 is True, so the LED turns on. When released, button.value() returns 1, so the LED turns off.
if not button.value():
led.value(1)
else:
led.value(0)
if not button.value(): checks for LOW (pressed) state; equivalent to if button.value() == 0Adapted from Python_Tutorial.pdf Project 2.1