This lesson is in the early stages of development (Alpha version)

Using GPIO Pins for Input

Overview

Teaching: 20 min
Exercises: 20 min
Questions
  • How can GPIO pins get information in?

Objectives
  • GPIO pins can detect change of state

Just like with the Arduino, you can detect events using the digital pins on the Raspberry Pi. If you leave the LED wired to pin 17 and connect the button to pin 3, you can detect the button press and turn the LED on with the GPIO Zero library.

Button with Raspberry Pi

#! /usr/bin/env python3

from gpiozero import LED, Button
from signal import pause

led = LED(17)
button = Button(3)

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

pause()

In this example, the LED stays lit as long as the button is pressed. But you could just as easily have each button press turn it on or off. I fact…

Try this:

Modify the program to turn the LED with one button press and turn it off with another. Extra credit for checking state (to make sure its off before turning it on.)

Some analog devices come with a “digital pin” that works with a threshold, meaning that if the value being measured exceeds some target, the pin turns on. Sometimes this is sufficient, e.g. an alarm. Or a trigger. For actually collecting analog data, however, you would need to use an analog-to-digital converter. Or select a sensor that communicates over a serial interface.

Key Points

  • The GPIO only has digital pins.