RaspberryPi GPIO Python

To access GPIO of Raspberry Pi using python, you need to have following dependencies installed.

to install python-dev and python-pip:

$ sudo apt-get install python-dev python-pip

to install RPi.GPIO:

$  pip install RPi.GPIO 

Once this is done you are all set to use the RPi GPIO.

The sample code for taking input from a gpio pin is given below

#! /usr/bin/python

from RPi import GPIO as io
import time

#Use the actual pin numbers on the board in the code.
io.setmode(io.BOARD)

#Configure pin no. 18 as input and make it a pull down.
#Meaning to get an input you need to giv that pin a logic 1.
io.setup(18, io.IN, pull_up_down=io.PUD_DOWN) 

def check_button_state():
    while True:
        try:
            if io.input(18) == 1:
                print("pressed")
                time.sleep(1)
            else:
                pass
        except KeyboardInterrupt as ke:
            io.cleanup()
            break

if __name__ == '__main__':
    check_button_state()