Search code examples
loopsif-statementbooleanstate-machine

Change a boolean inside a loop with multiple if conditions


I have 4 if conditions associated with a variable called ValveActive (changing from 1 to 4) inside a program loop which executes every second. Each if condition is true for 5 minutes. Inside each if condition I need to set a boolean PortSetto true for a defined amount of time and then set it false. I would like the process of turning on the boolean not to repeat when the loop repeats. The boolean represents turning on a relay and then turning it off, something that I would like to happen only once during the duration of each unique ValveActivestate.

Start of loop

If ValveActive=1
                    PortSet(9,1) 'Activate port
            'Do something 
                    Delay (1,25,mSec)
            PortSet(9,0)          'Deactivate port

ElseIf ValveActive=2
              PortSet(9,1)
            'Do something 
            Delay (1,25,mSec)
            PortSet(9,0)

ElseIf ValveActive=3
              PortSet(9,1)
            'Do something
            Delay (1,25,mSec)
             PortSet(9,0)

Else
              PortSet(9,1)
            'Do something  
            Delay (1,25,mSec)
             PortSet(9,0)

EndIf

Loop

I have experimented with setting up a boolean outside the loop to false then turning it to true inside the loop, but this does not work for multiple if conditions. How can I achieve this?


Solution

  • Create a new variable, such as PreviousValveActive, which remembers the value of ValveActive from the previous time through the loop. Then use PreviousValveActive as a test to determine whether to do the stuff that should happen only once in each state.

    Start of loop
    
    If ValveActive=1
        If PreviousValveActive != ValveActive
                PreviousValveActive = ValveActive
                PortSet(9,1) 'Activate port
                'Do something 
                Delay (1,25,mSec)
                PortSet(9,0)          'Deactivate port
        EndIf
    
    ElseIf ValveActive=2
        If PreviousValveActive != ValveActive
                PreviousValveActive = ValveActive
                PortSet(9,1)
                'Do something 
                Delay (1,25,mSec)
                PortSet(9,0)
        EndIf
    
    ElseIf ValveActive=3
        If PreviousValveActive != ValveActive
                PreviousValveActive = ValveActive
                PortSet(9,1)
                'Do something
                Delay (1,25,mSec)
                PortSet(9,0)
        EndIf
    
    Else
        If PreviousValveActive != ValveActive
                PreviousValveActive = ValveActive
                PortSet(9,1)
                'Do something  
                Delay (1,25,mSec)
                PortSet(9,0)
        EndIf
    
    EndIf
    
    Loop