My 8 relay module is set up to control the heating and air conditioning in a remote building. I run 5v to all the relay coils - that is the high side. I run GPIO pins to the low side. The GPIO pins are normally high - 3.3v. When a GPIO pin is made to go down it looks like ground to the relay to which it is attached and the relay operates/closes.
# GPIO09 - Turn on or off a specified relay so
# it stays on or off after the program ends
# at power on all pins are in input state ready to sense hi or lo
#
import RPi.GPIO as GPIO ## Import GPIO library
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD) ## Use board pin numbering
pinarr=[3,5,7,11,13,15,19,21]
dirarr=["on","off"]
devarr=["Air Conditioning","Heater","Unused","Unused","Unused","Unused","Unused","Unused"]
## Use a dictionary as a lookup table to give a name to the GPIO_function return code
pin_use = {0:"GPIO.OUT",1:"GPIO.IN",40:"GPIO.SERIAL",41:"GPIO.SPI",
42:"GPIO.I2C",43:"GPIO.HARD_PWM",-1:"GPIO.UNKNOWN"}
for i in range(0,8): ## set pins to be outputs and at 3.3 volts
GPIO.setup(pinarr[i], GPIO.OUT)
for i in range(0,8):
print "\n"
print("GPIO09 Starting")
##for i in range(0,8): ## Print current relay usage
## fno = GPIO.gpio_function(pinarr[i]) ## get function number
## print "Relay " + str(i+1) + " pin " + str(pinarr[i]) + " usage is " + pin_use[fno]
while 1 == 1:
for i in range(0,8): ## get and display pin on/off status
func = GPIO.input(pinarr[i])
print "Relay " + str(i+1) + " " + devarr[i] + " pin " + str(pinarr[i]) + " is " + dirarr[func]
print " "
## Ask user for relay #
relno = raw_input("Enter number of relay to change: ")
if not relno:
print "exiting"
raise SystemExit
if(int(relno) < 1):
print "Bad choice - exiting"
raise SystemExit
if(int(relno) > 8):
print "Bad Choice - exiting"
raise SystemExit
relno = int(relno)
ans = raw_input("ON or OFF ? 1 or 0: ")
if (ans == "1"):
print "Turning on relay " + str(relno) + " Pin " + str(pinarr[relno -1])
GPIO.output(pinarr[relno - 1],False) ## Switch off pin = conduct
for i in range(0,2):
print "\n"
if (ans == "0"):
print "Turning off relay " + str(relno) + " Pin " + str(pinarr[relno -1])
GPIO.output(pinarr[relno - 1],True) ## Switch on pin = non-conduct
for i in range(0,2):
print "\n"