I am running a piece of python code on a raspberry pi.
The function of the code is that GPIO 5 is set as a pull up resistor with a momentary switch attached. When the switch is pressed it grounds the pull up resistor. I am attempting to use the button push to trigger a callback.
The callback works like this:
If the button is pressed and detected as still pressed it defines a variable called "t1" as the current time.
If the button is detected as no longer pressed it defines a variable called "t2" then subtracts "t1" from "t2" to find the time difference (amount of time button was held down for). It then converts that value to an integer defined as variable "deltaseconds". Then it takes action based on the length the button was held for. If more than 7 seconds, reboot the raspberry pi, if more than 1 second but less than 7 it toggles output GPIO(12) between high and low.
The issue I am experiencing is like this:
The code runs
When the button is pressed I see the print of "Button 5 pressed"
When the button is released I see the print "Button 5 released"
Then an error is display as "UnboundLocalError: local variable 't1' referenced before assignment"
The error is in reference to line 21 delta = t2-t1
The full code looks like this:
import os
import RPi.GPIO as GPIO
import webiopi
import time
import datetime
from datetime import datetime
GPIO.setwarnings(True)
GPIO.setmode(GPIO.BCM)
BUTTON_5 = 5
GPIO.setup(5, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(12,GPIO.OUT)
GPIO.output(12,1)
#Just to visually distinguish between setup steps and main program
def pressed(BUTTON_5):
if GPIO.input(5) == False:
t1 = datetime.now()
print "Button 5 pressed"
elif GPIO.input(5) == True:
print "Button 5 released"
t2 = datetime.now()
delta = t2-t1
deltaseconds = delta.total_seconds()
if (deltaseconds > 7) : # pressed for > 7 seconds
print "Restarting System"
subprocess.call(['shutdown -r now "System halted by GPIO action" &'], shell=True)
elif (deltaseconds > 1) : # press for > 1 < 7 seconds
print "Toggling GPIO 12"
GPIO.output(12, not GPIO.input(12))
GPIO.add_event_detect(BUTTON_5, GPIO.BOTH, bouncetime=200)
GPIO.add_event_callback(BUTTON_5, pressed)
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
GPIO.cleanup() # clean up GPIO on CTRL+C exit
t1todatetime.now()in the aboveifstatement, then you try to access it in the followingelifstatement.