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.
Step by step
-
Add a pushbutton in Wokwi.
-
Wire one side of the button to GP14 and the other side to GND.
-
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:
Your task
Change the program so the lamp stays on after one press, and goes off after the next press, like a light switch. Hint: keep a variable that remembers whether the lamp is on.