简体   繁体   中英

Raspberry Pi: Python try/except loop

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.

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

# !/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"

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.

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.

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

Just use a while True loop, something like:

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

I agree with reptilicus, you just need to add a while loop. "while True" will run forever, until you hit ctrl-C to break. You just need to add a second delay to hold the relay off for 180 seconds before looping. You can create a different sleep time variable, or I just multiply the one you have by 2.

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

  #Reset GPIO settings
    GPIO.cleanup()
    time.sleep(2*SleepTimeL)

  # end program cleanly
  except KeyboardInterrupt:
    print "done"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM