We are always told to call
GPIO.cleanup() before we exit our Pi programs. I've seen people using
try ... catch ... finally to achieve this. But hey, we are doing python here, an elegant programming language. Do you guys think this is a more elegant solution?
# SafeGPIO.py from RPi import GPIO class SafeGPIO(object): def __enter__(self): return GPIO def __exit__(self, *args, **kwargs): GPIO.cleanup()
Use like this:
from SafeGPIO import SafeGPIO import time with SafeGPIO() as GPIO: GPIO.setmode(GPIO.BOARD) GPIO.setup(7, GPIO.OUT) GPIO.output(7, True) GPIO.setup(8, GPIO.OUT) GPIO.output(8, True) val = 0 for i in xrange(10): val = (val + 1) % 2 active_pin = 7 + val inactive_pin = 7 + (val + 1) % 2 GPIO.output(active_pin,True) GPIO.output(inactive_pin,False) time.sleep(2)