refined button handler

This commit is contained in:
mandlm 2016-01-07 15:59:21 +01:00
parent 34e18d2748
commit 0e8bc288b8

View File

@ -10,10 +10,18 @@ greenLed = 18
buttonPin = 27
sleepTime = 0.25
sleepTimes = [1, 0.5, 0.25, 0.125]
sleepTimeIndex = 0
def buttonHandler(channel):
global sleepTimeIndex
print 'button pushed'
sleepTimeIndex = (sleepTimeIndex + 1) % len(sleepTimes)
def setLeds(yellow, red, green):
GPIO.output(yellowLed, yellow)
GPIO.output(redLed, red)
GPIO.output(greenLed, green)
try:
GPIO.setmode(GPIO.BCM)
@ -26,21 +34,12 @@ try:
GPIO.add_event_detect(buttonPin, GPIO.FALLING, callback=buttonHandler, bouncetime=1000)
while True:
GPIO.output(yellowLed, 1)
GPIO.output(redLed, 0)
GPIO.output(greenLed, 0)
sleep(sleepTime)
GPIO.output(yellowLed, 0)
GPIO.output(redLed, 1)
GPIO.output(greenLed, 0)
sleep(sleepTime)
GPIO.output(yellowLed, 0)
GPIO.output(redLed, 0)
GPIO.output(greenLed, 1)
sleep(sleepTime)
except KeyboardInterrupt:
GPIO.output(yellowLed, 0)
GPIO.output(redLed, 0)
GPIO.output(greenLed, 0)
setLeds(1, 0, 0)
sleep(sleepTimes[sleepTimeIndex])
setLeds(0, 1, 0)
sleep(sleepTimes[sleepTimeIndex])
setLeds(0, 0, 1)
sleep(sleepTimes[sleepTimeIndex])
finally:
setLeds(0, 0, 0)
GPIO.cleanup()