FLASHLIGHT

In Using Buttons With GPIO, we were able to get button input from a GPIO.  In this project, we’re going to use that input to control another circuit.

For this project, you'll want to read the following concept lesson before you get started:  While Loops.

For the hardware in this project, we’re going to wire two completely independent circuits:

  1. The first circuit will consist of a button wired to a GPIO (like we did in Using Buttons With GPIO);

  2. The second circuit will consist of an LED wired to a separate GPIO (like we did in General Purpose Input/Output)

Here is what the breadboard should look like with the two circuits wired.  If you have any questions about how to wire either of these two circuits, refer back to the projects referenced above.

You’ll notice that our button is wired to GPIO18 and our LED is wired to GPIO14. 

Now that we have the circuits built and ready to go, it’s time to write our software.  For this project, our software is going to do two things:

  1.  Read the state of the button (pressed or unpressed) using a GPIO as input

  2.   If the button is pressed, turn on the LED using a GPIO as output, and if the button is not pressed, turn off the LED using the GPIO as output

Here is the code that will accomplish this:

Let's to through the code line-by-line and take a look at what it's doing:

Notice that with this code, the button status is only read one time when the program is run.  So, if you want the LED to illuminate, you need to be holding the button when you run the code.  If you’re not holding down the button at the time the program is run, the code will see that the button is unpressed and the LED will not illuminate.

To make this program more useful, we can put the code that reads the button into a loop so that it will continually read the button state and update the LED every time it changes.  To do this, we simply put the last four lines of the code (the lines that test the state of the button and turn the LED on or off) in a while True: loop, like this:

Give it a try…the flashlight will continue to work until you manually stop the program.

prev| next