Raspberry Pi: Python try/except loop
<p>I've just picked up my first Raspberry Pi and 2 channel relay.  I'm trying to learn how to code in Python so I figured a Pi to play with would be a good starting point.  I have a question regarding the timing of my relays via the GPIO pins.  </p>

<p>Firstly though, I'm using Raspbian Pixel and am editing my scripts via Gedit.  Please see below for the script I have so far:</p>

<pre><code># !/usr/bin/python
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)

# init list with pin numbers
pinList = [14]

# loop through pins and set mode and state to 'high'
for i in pinList:
  GPIO.setup(i, GPIO.OUT)
  GPIO.output(i, GPIO.HIGH)

# time to sleep between operations in the main loop
SleepTimeL = 60 #1 minute

# main loop
try:
  GPIO.output(14, GPIO.LOW)
  print "open"
  time.sleep(SleepTimeL);
  GPIO.cleanup()

#Reset GPIO settings
  GPIO.cleanup()

# end program cleanly
except KeyboardInterrupt:
  print "done"
</code></pre>

<p>Now that works pretty well, it opens the relay attached to pin 14 no problem.  It cycles through 60 seconds as requested and then ends the program.  Once the program has ended, the GPIO settings are reset and the relay closes, but that's the end of the program and it's where my problem starts.</p>

<p>What I want this script to do is open the relay for 60 seconds, then close it for 180 seconds.  Once it reaches 180 seconds it must re-run the 'try' statement and open the relay for another 60 seconds and so on.  In short, I would like an infinite loop that can only be interrupted by cancelling the script from running.  I am unsure of how to tell Python to close the relay for 180 seconds and then re-run the try statement, or how to make it an infinite loop for that matter.</p>

<p>I'd really appreciate some input from the community.  Any feedback or assistance is greatly appreciated.  Thanks All.</p>

<p>Just use a <code>while True</code> loop, something like:</p>

<pre><code># main loop
while True:
    GPIO.output(14, GPIO.LOW)
    print "open"
    time.sleep(SleepTimeL);
GPIO.cleanup()
print "done"
</code></pre>

python exception try-catch gpio