Saturday, January 12, 2013

Raspberry Pi GPIO example code in python

Im building a system for controlling the lights in my home from my raspberry pi.
So i've hooked up two solid state relays to the gpio pins om my RPi and i've made this python script for controlling it.

This script requires that you have installed RPi.GPIO
http://code.google.com/p/raspberry-gpio-python/
download the .deb file here

And you need to run the script as root since that's a requirement for access to the GPIO pins.

So currently i can run this script from my computer or phone via SSH, wich is alot better than walking around hitting switches, but im on a mission to develop a web-interface so it will be even more easy to use. Since not everyone in my household is tech savvy enough to make easy use of things like SSH.









# GPIO-OnOff.py
# written by fredrik 12.january.2013
#
# raspberry pi GPIO extentions
# requires root for access to the GPIO pins
import RPi.GPIO as GPIO

#dont bug me with warnings
GPIO.setwarnings(False)

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

# set up GPIO output channels
GPIO.setup(18, GPIO.OUT)
GPIO.setup(16, GPIO.OUT)


x = 0
def on():
    print ("Lights On")
#    set RPi board pins high
    GPIO.output(18, GPIO.HIGH)
    GPIO.output(16, GPIO.HIGH)
 
def off():
    print ("Lights Off")
#    set RPi board pins low
    GPIO.output(18, GPIO.LOW)
    GPIO.output(16, GPIO.LOW)
 
menu = [off,on]
 
while x < len(menu) :
    print "Lights",menu[x].__name__,", press","["+str(x)+"]"
    x += 1
 
c = input()
menu[c]()




No comments:

Post a Comment