[Logo for The C Shore Landing Page]
The C Shore

Using Buttons to Get Input

Table of Contents

Using buttons to get input

Now you're able to control an output component (an LED), let's connect and control an input component: a button.

  • Connect a button to another GND pin and GPIO pin 2, like this:


  • Create a new file by clicking New.

  • Save the new file by clicking Save. Save the file as gpio_button.py.

  • This time you'll need the Button class, and to tell it that the button is on pin 2. Write the following code in your new file:

    from gpiozero import Button
    button = Button(2)
    
  • Recall that from gpiozero import Button pulls in code that someone else has written. They've put it in a library called gpiozero. And, since we're working with a button, we are specifically requesting the Button class.


  • Similar to the way in which a daffodil is a type of flower, the button variable is a type of the Button class. The button variable in this case is a instance of Button associated with GPIO 2 (which is why we write Button(2) ). In the case of a daffodil it could be considered an instance of flower that has bell-shaped yellow top, and a long green stem. Each of these facts about the daffodil are known as ‘properties’ of the class Flower that create a unique flower.

  • Now you can get your program to do something when the button is pushed. Add these lines:

    while True:
        button.wait_for_press()
        print('You pushed me')
    
  • The complete program is therefore:

    from gpiozero import button
    
    while True:
        button.wait_for_press()
        print('You pushed me')
    
  • Save and run the code.

  • Press the button on the breadboard and your text will appear on on the screen.


Manually controlling the LED

You can now combine your two programs written so far to control the LED using the button.

As we did in Module 1, connect the LED to the GPIO 17 of the Pi through a resistor, while leaving the button connected as in the previous section.

The button and LED are not electrically connected. The Pi will accept input from the button and control the LED.

  • Create a new file by clicking New.

  • Save the new file by clicking Save. Save the file as gpio_control.py.

  • Now write the following code:

    from gpiozero import LED, Button
    from time import sleep
    
    led = LED(17)
    button = Button(2)
    
    while True:
        button.wait_for_press()
        led.on()
        sleep(3)
        led.off()
    
  • Save and run your program. When you push the button the LED should come on for three seconds.