Table of Contents
Sadly our easy button is not as easy as the Staples® easy button.
Keep the LED connected.
Adding a Button
Positioning these buttons correctly is rather tricky. Don’t worry. If you end up with the button turned the wrong way, all that will happen is that it will act as if it was always pressed. If that is what you are seeing, just rotate the button a quarter of way around.
Connect one pin of the button to GPIO 2 and the other to GND (ground).
This creates a second circuit (separate from LED circuit) in which no electricity flows unless the button is pressed. It is actually the commands you use on the Pi that turn on the LED.
When the button is pressed electricity flows from the GPIO2 (which acts as 3V3 volts), through a resistor inside the Pi, to GND (ground / 0 volts). The Pi senses this.
Extra Information (ignore if you wish): We call a circuit which is ‘on’ when it goes low (gets connected to ground) ‘active low’. Most of the time in digital electronics, devices are ‘active high’. (that is they are ‘on’ when connected to power / positive voltage).
Since we can tell the Pi to pause until it senses the button being pressed, we can send commands to the Pi to light the LED once the button is pressed.
Load the Code
It should contain
from gpiozero import LED, Button # Information the computer needs from time import sleep # More information the computer # needs led = LED(17) # Use GPIO 17 for the LED button = Button(2) # Use GPIO 2 for the Button button.wait_for_press() # Wait until the button is pressed led.on() # Turn LED on and leave it on sleep(1) # Wait for 1 second led.off() # Turn LED off and leave it off
How would you have Pi wait one second after the button is pressed before turning the LED on and off?
‘Hot potato!’ time
Make the Pi wait one second after the button is pressed before turning the LED on and off.
How would you make the Pi wait until the button is pressed to light the LED, light the LED (and leave it on), and then wait until you press the button again to turn the LED off?
Make the Pi wait until the button is pressed to light the LED, light the LED (and leave it on), and then wait until you press the button again to turn the LED off?
Take turns trying making interesting modifications to the programs you’ve worked with today.