Turning an LED on/off using a push button
In the previous section, we accessed Raspberry Pi GPIO to turn LEDs on/off by program. Now we will learn how to turn an LED on/off using a push button, which is used as a GPIO input from Raspberry Pi GPIO.
The following hardware components are needed:
- A Raspberry Pi 2 board
- An LED
- A push button (https://www.sparkfun.com/products/97)
- 1 KΩ resistor
You can see the push button connection in the following figure:
Our hardware wiring is simple. You simply connect the LED to GPIO23 from Raspberry Pi. The push button is connected to Raspberry Pi GPIO on GPIO24. The complete hardware wiring can be seen in the following figure:
Furthermore, you can write a Python program to read the push button's state. If you press the push button, the program will turn on the LED. Otherwise, it will turn off the LED. This is our program scenario.
The following is the complete code for the Python program:
# ch01_02.py file import wiringpi2 as wiringpi # initialize wiringpi.wiringPiSetup() # define GPIO mode GPIO23 = 4 GPIO24 = 5 LOW = 0 HIGH = 1 OUTPUT = 1 INPUT = 0 PULL_DOWN = 1 wiringpi.pinMode(GPIO23, OUTPUT) # LED wiringpi.pinMode(GPIO24, INPUT) # push button wiringpi.pullUpDnControl(GPIO24, PULL_DOWN) # pull down # make all LEDs off def clear_all(): wiringpi.digitalWrite(GPIO23, LOW) try: clear_all() while 1: button_state = wiringpi.digitalRead(GPIO24) print button_state if button_state == 1: wiringpi.digitalWrite(GPIO23, HIGH) else: wiringpi.digitalWrite(GPIO23, LOW) wiringpi.delay(20) except KeyboardInterrupt: clear_all() print("done")
Save this code in a file named ch01_02.py
.
Now you can run this program via the terminal:
$ sudo python ch01_02.py
After this, you can check by pressing the push button; you should see the LED lighting up.
First, we define our Raspberry Pi GPIO's usage. We also declare our GPIO input to be set as pull down. This means that if the push button is pressed, it will return value 1.
GPIO23 = 4 GPIO24 = 5 LOW = 0 HIGH = 1 OUTPUT = 1 INPUT = 0 PULL_DOWN = 1 wiringpi.pinMode(GPIO23, OUTPUT) # LED wiringpi.pinMode(GPIO24, INPUT) # push button wiringpi.pullUpDnControl(GPIO24, PULL_DOWN) # pull down
We can read the push button's state using the digitalRead()
function from WiringPi as follows:
button_state = wiringpi.digitalRead(GPIO24)
If the push button is pressed, we turn on the LED; otherwise, we turn it off:
print button_state if button_state == 1: wiringpi.digitalWrite(GPIO23, HIGH) else: wiringpi.digitalWrite(GPIO23, LOW)