Let’s have a closer look at how useful the if-statement can be in your programming. First you need to connect two LEDs to your Pi. Because we will reference the color in the program, we would suggest you use the green and the yellow LEDs. Please be sure to check all of the connections before writing the program:
|Connections Pi||Connections LEDs|
|GPIO18||Long leg green LED|
|GPIO23||Long leg yellow LED|
|GND||Short legs LED + 220Ω Resistor|
How can we write the program so that we can interact with the components and make the decision for the color of the LED we want to turn on while it has already started? Well for this we can use the
input()- function. This function makes it possible to ask the user a question in the terminal and pass the user’s answer as in input parameter for the program. Have a look at the program below:
import RPi.GPIO as gpio import time gpio.setmode(gpio.BCM) gpio.setup(18, gpio.OUT) gpio.setup(23, gpio.OUT) color = input("yellow or green? ") if color == "yellow": gpio.output(23, gpio.HIGH) time.sleep(2) gpio.output(23, gpio.LOW) if color == "green": gpio.output(18, gpio.HIGH) time.sleep(2) gpio.output(18, gpio.LOW) gpio.cleanup()
Line 1 to 6 should be quite familiar to you. We need to first import the necessary libraries and then take care of the pin settings just as we did in the previous example. The only difference here is that in the last example we only used one led and now need to set up two.
In line 8 we get to the interesting part of the code. In this line we are creating the variable color but we don’t set the content of variable directly, instead we use the
input() function. You can see the parameter as text in the terminal after executing the program. The program halts at that point until there is something typed into the terminal (including enter to send the text). Everything that got entered is now saved as string into the variable color.
In line 10 the if-statement makes its great appearance. In this section we check the content of the variable and see if a certain color is entered. Depending on what the expression evaluates to we make the led of the appropriate color blink. To do this we created 2 if-statements, one for each color. We use the
== to check for the content. This also means that the LEDs will only blink if you entered yellow or green as the input.