Lights and buttons · Lesson 3 of 5· 15 min

Buttons: telling the robot something

Why this matters

So far the board only acts. Now it senses. A button is the simplest sensor there is: pressed or not pressed.

Wiring a button

Open a tool

Wokwi simulator

Free, nothing to install. Works best on a laptop; on a phone you can still read the steps and the code below.

Opens wokwi.com in a new tab. Come back here when you are done.

Open Wokwi simulator

Step by step

  1. Add a pushbutton in Wokwi.

  2. Wire one side of the button to GP14 and the other side to GND.

  3. Keep your LED from the last lesson on GP15.

Pull-up: why pressed reads 0

When nobody touches the button, the pin is not connected to anything and could read random values. A pull-up gently holds the pin at 1. Pressing the button connects it to GND, so it reads 0. That is why the code below checks for 0.

from machine import Pin
import time

button = Pin(14, Pin.IN, Pin.PULL_UP)
lamp = Pin(15, Pin.OUT)

while True:
    if button.value() == 0:   # pressed
        lamp.value(1)
    else:
        lamp.value(0)
    time.sleep(0.01)

Run it and click the button in the simulator. The lamp lights while you hold it.

Sense, think, act

You can try the thinking part right here, without the board. Press Run:

Python
You’re reading for free. Sign in to save your progress, ask questions on any lesson, and earn a certificate when you finish.Sign in to keep my progress →

Lesson 3 of 5