Friday, May 26, 2017

Byte: Raspberry Picraft Weekend - Challenge 2



Challenge 2: Push button to work as a light switch

As impressive as our achievement in the first challenge was, you may have noticed that whenever you want to turn on a light, you don’t need to stand around holding the switch down to keep the light on. This is for two reasons: one, that would be incredibly annoying and you’d have to employ someone to hold down the button every time you wanted to turn on a light; and two, for this very reason, lights tend to be connected to circuits using switches, rather than push buttons. So how can we turn our push button into a switch, so that we don’t have to keep pressing whenever we want our LED to turn on? You use code, of course! (Well, you could use an actual switch instead of a push button, but where’s the fun in that?!?)

The obvious place to start is with the code that imports all the necessary libraries to command the buttons and the LEDs, and await further instructions. ‘Save As’ your current script and rename it appropriately to reflect the intended functionality of the new code: lightswitch.py or something similar. Then trim back the code to the following starting point:

#import necessary libraries
from gpiozero import LED, Button
from time import sleep

#define variables
red = LED(17)
amber = LED(18)
green = LED(23)
blue = LED(24)
button1 = Button(5)
button2 = Button(6)
button3 = Button(12)
button4 = Button(13)
while True:

We need the sleep library, as we’re going to have to put in small time delays so that the buttons can act as a toggle switch, rather than a push button. We will also need to use a slightly different method with the push buttons to accept inputs, as we want to leave the LEDs on or off until the script registers a user input. So rather than using the is_pressed() method, we will use the wait_for_press() method of the push button instead.

#import necessary libraries
from gpiozero import LED, Button
from time import sleep

#define variables
red = LED(17)
amber = LED(18)
green = LED(23)
blue = LED(24)
button1 = Button(5)
button2 = Button(6)
button3 = Button(12)
button4 = Button(13)
#turn off the LEDs to ensure they are all off before the main script runs
red.off()
amber.off()
 green.off()
 blue.off()
while True:
    #poll for input from the buttons
    button1.wait_for_press()
    red.toggle()
    sleep(0.2)
    button2.wait_for_press()
    amber.toggle()
    sleep(0.2)  
    button3.wait_for_press()
    green.toggle()
    sleep(0.2)
    button4.wait_for_press()
    blue.toggle()
    sleep(0.2)

Huzzah! Our script now turns the LEDs on and off at the push of a button masquerading as a switch! It’s almost like we’re masters of technology developed in the 19th century! (In case you didn’t know, the ‘quick break’ light switch, which is still used today, was invented in 1884 by John Henry Holmes, an English pioneer of electrical engineering and lighting. You can read about him on Wikipedia.)
Post a Comment