As you can now tell, loops are a great tool, and we can use them for way more than just blinking LEDs. Have you ever asked yourself how a computer mouse is actually working?
The operating system (including Windows, Android or often Raspbian on the Pi) is constantly checking if the mouse was moved or if there has been a mouse click. For this, “always” is a loop like the while loop..
In this chapter we discuss and work with the button component. Similar to the PC Mouse, a button is something that requires us to constantly be checking if it was pressed down.
|Connections Pi||Connection LED/Button|
|GPIO18||Long leg LED|
|GND (Ground)||short leg LED + 220Ω Resistor|
|GPIO23||Button one side|
|GND (Ground)||Button one side + 10 000Ω Resistor|
And with the following code we will bring light to the button:
import RPi.GPIO as gpio import time gpio.setmode(gpio.BCM) gpio.setup(23,gpio.IN,pull_up_down=gpio.PUD_UP) gpio.setup(18, gpio.OUT) while True: buttonPressed = gpio.input(23) if buttonPressed == 1: gpio.output(18, gpio.LOW) if buttonPressed == 0: gpio.output(18, gpio.HIGH)
Exactly three things are new in this program. You will find the first thing in line 6. Until now we only used the
gpio.setup() function for LEDs and creating the electronic circuit. This time we want to use it to read if the button was pressed.
In this case, we want to check if there is a voltage/closed circuit. There is only a closed circuit if the button is pressed. To do this we need to make the setup that is done in line 6. We can check the state of the pin with
gpio.input() and use the pin number as a parameter. We do this in line 10 of our program. The state is either 1 (or HIGH) when the button is pressed or it is 0 (or LOW) when the button is not pressed.
The third new thing is that we have no comparison expression in line 9 for the while loop. Because we want the while loop to continue no matter what, the condition is simply:
while True: so that the while loop always runs.
The intended block is for reading the state of the pin and saving it into the variable buttonPressed and then checking it with the two if-statements. You can combine if-statements and while-loops into infinity but it gets harder and harder to keep track of the indents.
If you have had enough of the program you can always close the program by pressing
ctrl + c.
Now it’s your turn! Can you connect a second button and a second LED? Hint: You don’t need more than one while loop ;)