Learning how to use GPIO

by solusipse

GPIO is very cool feature. When I managed to light a diode using it, I decided to check how input works. I made such configuration with switch, diode and resistors:

We’ve got now four wires connected to our RPi – one is ground (GND), one is power (VCC 3.3V), one is output (PIN23) and one is input(PIN24).  The only new thing, when we compare this to configuration from last post, is that now we have a switch connected to the input. Don’t forget to connect it from PIN24 side to GND with 10k resistor. This is how you should connect it to RPi:

Now it’s time to write a python program that will handle it.

Type in console:

cat > button.py

You will create a new file and start to edit its contents so type then:

import RPi.GPIO as GPIO
GPIO.setup(23, GPIO.OUT)
GPIO.setup(24, GPIO.IN)
test = 0
while True:
           if GPIO.input(24):
                GPIO.output(23, True)
                if test == 0:
                             print 'You pushed the button!'
                             test = 1
                GPIO.output(23, False)
                test = 0

Then press ctrl + d. You can do that of course with any text editor you want (nano for example). Just make sure that file have such content.

Try to run it:

python button.py

Now if you press the button the led diode should light up and you should see on your screen a message.