Thuta Learning
IntermediateHardwarebeginner

Reading Input — Buttons & Sensors

Relax. We'll talk through this in plain words — no textbook voice.

What you'll walk away with

  • Understand Reading Input — Buttons & Sensors without any of the intimidation
  • Be able to run the hardware wiring/code yourself
  • Apply this concept right away in a real project

Let's think about it this way for a moment

Wire a button to a GPIO pin and your code can detect its presses and releases — with gpiozero's Button class you can check it two ways: .is_pressed (a property, true/false) or .when_pressed (a callback function, the event-driven pattern). The event-driven pattern (when_pressed) is efficient because it doesn't need to constantly check (poll) inside a loop — the function fires automatically the moment the button is pressed.

Let's connect it to a real scenario

Combine a Button and an LED and you get the classic beginner circuit: 'light the LED while the button is pressed.' Just assign the function references directly — button.when_pressed = led.on, button.when_released = led.off — and you're done (this is one of gpiozero's nice syntax conveniences). Analog sensors like temperature/humidity sensors (DHT11/DHT22), though, need a dedicated library (Adafruit_DHT) and are more involved than plain GPIO digital read/write.

Let's look at it together

python
from gpiozero import LED, Button
from signal import pause

led = LED(17)
button = Button(2)  # BCM pin 2

button.when_pressed = led.on
button.when_released = led.off

pause()  # keep script running to listen for button events
You should see
The LED stays lit while the button is held down, and turns off as soon as you release it.

5-minute try-it

Wire up a Button + LED circuit (if you have one) and write the code yourself using when_pressed/when_released events.

A quick word of caution

Watch out for the difference between when_pressed = led.on() (calls the function immediately) and when_pressed = led.on (a function reference) — parentheses or no parentheses is one of the classic beginner mistakes in Python.

Easy traps

  • Wiring a button without understanding the pull-up/pull-down resistor concept, leaving the pin floating (random on/off) — gpiozero's Button class actually auto-handles a default internal pull-up for you
  • Writing when_pressed = led.on() (with parentheses), which calls the function immediately instead of assigning it — you need to assign the function reference itself, without parentheses

Now try it yourself

Wire up a Button + LED circuit (if you have one) and write the code yourself using when_pressed/when_released events.

You'll know it worked when: The LED stays lit while the button is held down, and turns off as soon as you release it.