Search code examples
pythonflasktimegpioflask-ask

Error when using time with multiple conditions in Python


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')

Solution

  • 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