If you want to build electronic devices, at some point you're going to need to read data through GPIO. In this exercise, we're going to read the value of a push button on a breadboard.
Set up the circuit as shown in the pictures on the right. Note that one end of the 4.7kOhm resistor connected to pin 23 is connected to the positive supply rail. The red jum[er cable links the positive rail on the breadboard to the 3.3V pin on the GPIO header. The green jumper wire connected to one of the pins on the button is connected to the negative rail on the breadboard, and there's another jumper cable linking that negative supply rail to a GND pin on the GPIO header.
The resistor is used to pull up the voltage on pin 23 to logic 1. Without it, pin 23 would have an indeterminate value. When the button is pressed, pin 23 is connected directly to ground, so it switches to logic 0.
Save the following code in a file called button.py
#!/usr/bin/env python import time import RPi.GPIO as GPIO def main(): # tell the GPIO module that we want to use the # chip's pin numbering scheme GPIO.setmode(GPIO.BCM) # setup pin 25 as an output GPIO.setup(23,GPIO.IN) GPIO.setup(24,GPIO.OUT) GPIO.setup(25,GPIO.OUT) GPIO.output(25,True) while True: if GPIO.input(23): # the button is being pressed, so turn on the green LED # and turn off the red LED GPIO.output(24,True) GPIO.output(25,False) print "button true" else: # the button isn't being pressed, so turn off the green LED # and turn on the red LED GPIO.output(24,False) GPIO.output(25,True) print "button false" time.sleep(0.1) print "button pushed" GPIO.cleanup() if __name__=="__main__": main()
Make it executable with this command:
This code uses GPIO pins 24 and 25 to control two LEDs, so they are set up as outputs. Pin 23 is used to read the button, so it's set up to be an input.
In the while loop, the 'if' statement checks to see if the button is being pushed. If it is, the green LED is turned on and the red LED is turned off. When the button is released, the green LED goes back off and the red one is turned on again.
The program pauses for 0.1 seconds after the if statment, and then goes back to the top of the while loop.
To run the program, type this command: