Sprinkler System Code:
This post documents the code deployed to the Raspberry Pi that interacts between the between the Pi, GPIO and SainSmart Relay Switch in order to activate the sprinkler system solenoid valves. This will be the first post in a series that documents the ‘brains’ of the controller and exactly how it works. At this point in the process, I am only documenting the interaction, not the final code with the appropriate switching order, timing, etc…

Steps Taken:

Reset GPIO
I’ve noticed that when I power up or reboot the Raspberry Pi while connected to the relay card, several of the relay LED’s light up. They aren’t powered on, but the LED’s come on. The following code resets the GPIO / Relay Switch connectivity and turns off the LEDS. This was written to work on the SainSmart 16 Port Relay switch (notice the extra pins defined), but it also works on the 8 port relay switch. I plan to run this script when the Pi boots up. More on this later.


#!/usr/bin/python  
import RPi.GPIO as GPIO  
import time  

GPIO.setmode(GPIO.BCM)  

# init list with pin numbers  

pinList = [2, 3, 4, 17, 27, 22, 10, 9, 11, 5, 6, 13, 19, 26, 21, 20]  

# loop through pins and set mode and state to 'low'  

for i in pinList:  
    GPIO.setup(i, GPIO.OUT)  
    GPIO.output(i, GPIO.HIGH)  

GPIO.cleanup()  

GPIO Blink Test
The next script is written to power on each relay port and print the associated port number. The script is to ensure that proper connectivity and coding can be verified.


#!/usr/bin/python
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)

# init list with pin numbers

pinList = [2, 3, 4, 17, 27, 22, 10, 9, 11, 5, 6, 13, 19, 26, 21, 20]

# loop through pins and set mode and state to 'low'

for i in pinList:
    GPIO.setup(i, GPIO.OUT)
    GPIO.output(i, GPIO.HIGH)

# time to sleep between operations in the main loop

SleepTimeL = 2

# main loop

try:
  GPIO.output(2, GPIO.LOW)
  print "ONE"
  time.sleep(SleepTimeL);
  GPIO.output(3, GPIO.LOW)
  print "TWO"
  time.sleep(SleepTimeL);
  GPIO.output(4, GPIO.LOW)
  print "THREE"
  time.sleep(SleepTimeL);
  GPIO.output(17, GPIO.LOW)
  print "FOUR"
  time.sleep(SleepTimeL);
  GPIO.output(27, GPIO.LOW)
  print "FIVE"
  time.sleep(SleepTimeL);
  GPIO.output(22, GPIO.LOW)
  print "SIX"
  time.sleep(SleepTimeL);
  GPIO.output(10, GPIO.LOW)
  print "SEVEN"
  time.sleep(SleepTimeL);
  GPIO.output(9, GPIO.LOW)
  print "EIGHT"
  time.sleep(SleepTimeL);
  
  GPIO.cleanup()
  print "Good bye!"

# End program cleanly with keyboard
except KeyboardInterrupt:
  print "  Quit"

  # Reset GPIO settings
  GPIO.cleanup()