New domain and blog

New domain and blog
Please head over to my new domain to view my blog and current projects

Wednesday, 29 August 2012

Raspberry Pi: GPIO input and output

So I got my Raspberry Pi yesterday and am super excited. I feel like a 10 year old on Christmas morning. I had already loaded the the Raspbian image onto an SD card so as soon as I got it I powered it up and away it ran.

The first thing that I wanted to get working was the GPIO pins. I did a bit of reading and some basic python examples and away I went. Have a look at this website for a very decent crash course in python.

The first thing you need to do is import the GPIO module. This can be installed from here

Then you need to tell python that you are going to use the Raspberry Pi's pin numbers when referencing the ports. The direction of the port is then set.

Once the setup is complete, you can start your code. In my hardware, I connected a push button switch to pin 11 and pin 18 and an LED to pin 3 and pin 5.

import RPi.GPIO as GPIO

#use the Raspberry Pi pin numbers
GPIO.setmode(GPIO.BOARD)

#set the input with pull up control
GPIO.setup(11, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP)

#set the output pins
GPIO.setup(3, GPIO.OUT)
GPIO.setup(5, GPIO.OUT)

while 1:
 if GPIO.input(11):
  GPIO.output(3, False)
 else:
  GPIO.output(3, True)

 if GPIO.input(18):
  GPIO.output(5, False)
 else:
  GPIO.output(5, True)

Above is the python code that I used. If you want to download the file you can get it here.

Once you have the file saved, run it in python and by pressing the buttons, the LED's will turn on. To stop the program running, press CTRL+z.

Greg