0

The problem is, variable t1 is inside the loop, but I can't use it outside (because it's not defined); So the program returns "UnboundLocalError: local variable 't1' referenced before assignment". I don't know other ways to measure the time between this two events, each time the first starts (self explanatory with the code below).

if status in STATUSON:
        t1 = 0
        GPIO.output(17,GPIO.HIGH)
        time.sleep(0.5)
        GPIO.output(17,GPIO.LOW)
        return statement('Ok')
        t1 = time.time()
    elif status in STATUSOFF and time.time() - t1 >= 5:
        GPIO.output(17,GPIO.HIGH)
        time.sleep(0.5)
        GPIO.output(17,GPIO.LOW)
        return statement('Ok')
    elif status in STATUSOFF and time.time() - t1 <= 5:
        GPIO.output(17,GPIO.HIGH)
        time.sleep(0.5)
        GPIO.output(17,GPIO.LOW)
        time.sleep(2)
        GPIO.output(17,GPIO.HIGH)
        time.sleep(0.5)
        GPIO.output(17,GPIO.LOW)
        return statement('Ok')
  • I rolled back your last edit. Please add the solution in the answer space. We do not allow edits that add a solution in the question. – Dharman Jan 20 '21 at 21:33

2 Answers2

0

Your problem is here:

        return statement('Ok')
        t1 = time.time()

You are returning before setting the t1 variable. Try reversing those 2 lines.

Also, as you're using return statement, I guess you're in a function, you should then return the t1 variable (maybe use a tuple?), or set it as a global variable (less recommended) to be able to do calculations in your main/top function.

Gugu72
  • 2,052
  • 13
  • 35
0

Solved:

I've used pickle to solve the problem. It can convert Python objects to a character stream, and save it, so the next loop can access this data anytime (new code below).

    if status in STATUSON:
        t1 = time.time()
        with open('time.pickle', 'wb') as f:
            pickle.dump(t1, f)       
        GPIO.output(17,GPIO.HIGH)
        time.sleep(0.5)
        GPIO.output(17,GPIO.LOW)
        return statement('Ok')
    elif status in STATUSOFF:
        with open('time.pickle', 'rb') as f:
            t1 = pickle.load(f)        
        if time.time() - t1 >= 15:
            GPIO.output(17,GPIO.HIGH)
            time.sleep(0.5)
            GPIO.output(17,GPIO.LOW)
            open("time.pickle", "w").close()
            return statement('Ok')
        elif time.time() - t1 <= 15:
            GPIO.output(17,GPIO.HIGH)
            time.sleep(0.5)
            GPIO.output(17,GPIO.LOW)
            time.sleep(2)
            GPIO.output(17,GPIO.HIGH)
            time.sleep(0.5)
            GPIO.output(17,GPIO.LOW)
            return statement('Ok')
        else:
            GPIO.output(17,GPIO.HIGH)
            time.sleep(0.5)
            GPIO.output(17,GPIO.LOW)
            return statement('Ok')

Full codes: old, new