Home > Back-end >  How to have a if statement which is nested within a while statement only complete its function once
How to have a if statement which is nested within a while statement only complete its function once

Time:03-06

I'm trying to have my code only complete its process once. (If res = on only do it once but when it becomes off it detects that and does the off data encode once.) Here is my current code and my function onoff if needed as well

def onoff():
    result = firebase.get('/Data', 'Condition')
    return result

while True:
    res = onoff()
    data = res ","
    if res == 'on':
        ser.write(data.encode())
        print(data)
        time.sleep(1)
    elif ser.write(data.encode()):
        print(data)
        time.sleep(1)```

CodePudding user response:

def onoff():
    result = firebase.get('/Data', 'Condition')
    return result
switch = True
while True:
    res = onoff()
    data = res ","
    if res == 'on' and switch:
        ser.write(data.encode())
        print(data)
        switch = False
        time.sleep(1)
    elif ser.write(data.encode()):
        print(data)
        time.sleep(1)```

CodePudding user response:

Got it too work, had to include 2 switches to control it

    result = firebase.get('/Data', 'Condition')
    return result

switch = False
switch2 = True

while True:
    res = onoff()
    data = res ","
        
 
    if res == 'on':
        if run_once == 0 and switch:
            ser.write(data.encode())
            print(data)
            switch2 = True
            switch = False
            time.sleep(1)
    

    if res == 'off':
        if run_once == 0 and switch2:
            ser.write(data.encode())
            print(data)
            switch = True
            switch2 = False
            time.sleep(1)
  • Related