I haven't tested this, but something like this might work (if not you should be able to get the idea of it....):
#!/usr/bin/env python
from time import sleep
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setup(22, GPIO.OUT)
GPIO.setup(11, GPIO.IN)
#the above bit of script sets up the required modules and stuff
state = 0
while True:
if ( GPIO.input(11) == True ):
if (state == 1):
state = 0
elif (state == 0):
state = 1
if (state == 1):
print("Output On")
GPIO.output(22, True)
elif (state == 0):
print("Output Off")
GPIO.output(22, False)
sleep(0.2)
First, it checks whether the switch is on, and changes state
if the switch is on. Then it should turn on or turn off the output accordingly, as well as printing what is doing, useful in the case of dodgy wiring.
Also when I do scripts on the Pi, and want to do something else with it afterwards without rebooting, I do a cleanup script top run afterwards, or after a script has crashed due to an error. In the case it should be something like:
#!/usr/bin/env python
import RPi.GPIO as GPIO
import os
import sys
from time import sleep
GPIO.setmode(GPIO.BOARD)
GPIO.setup(22, GPIO.OUT)
while True:
GPIO.output(22, False)
print "This should now finish"
GPIO.cleanup()
sys.exit()
I haven't had much chance to do Python for a while, so this should work...
Magpi
which has useful beginner tutorials.sleep
bit at the bottom