Raspberry Pi :  Button and LED

I used GPIOzero for this button and LED project. Most tutorials on the internet use RPi.GPIO, which works very well, but I've found GPIOzero to be much more intuitive.

In order to use the code below, first set up your button and LED with a breadboard. Set up your button, LED, and 220 ohm resistor the same way that GPIOzero does on their page.

My code is different than theirs but does the same thing. Their code is shorter but mine is more robust; especially in the case that you'd like to import and run any of the functions written below.

One quick thing that I learned through this simple project is GPIOzero's use of pause(), the missing parentheses when assigning an action to a function, and the lack of an infinite loop. For example, in my code, under the main function, there is button.when_pressed = turn_on_led. Notice the lack of parenthases after turn_on_led. Previously in the code, I declare a function called def turn_on_led():. It turns out, the lack of parenthases, pause(), and missing infinite loop are related.

Assigning button.when_pressed to turn_on_led instead of turn_on_led() creates what is known as a reference to the function instead of calling the function. Typically, a program will call a function to run/perform some operation at a specific time. Every time that function is called to run, it runs right away. In this code though, the function runs everytime a specific action happens. In this case, everytime the button is pressed (button.when_pressed) the turn_on_led() function is run.

The advantage to using this method is that there is no longer any need for an infinite loop. This frees up processing power and simplifies the algorithm.

pause() is used at the end of the code to tell the program to wait before closing out. If pause() is removed from the end of the code, the program will do everything you want, i.e. assign the button being pressed to turning on the LED, but after that action is assigned, the program will close out. It doesn’t know to wait to be used. pause() doesn’t need to be used in a program that uses an infinite loop, seen in other RPi button/LED tutorials because in that case, the infinite loop continuously runs until the operator commands a break of the loop.

Here's the code:

from gpiozero import LED, Button
from signal import pause

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

def turn_on_led():
   led.on()
   print("LED on!")

def turn_off_led():
   led.off()
   print("LED off!")

if __name__ == '__main__':
   button.when_pressed = turn_on_led
   button.when_released = turn_off_led

   pause()

Give it a whack.

Leave a Reply