使用多个if条件在循环内更改布尔值

时间:2019-07-10 13:22:22

标签: loops if-statement boolean state-machine

我有4个if条件,它们与每秒执行一次的程序循环内的名为ValveActive(从1变为4)的变量相关联。 每个if条件在5分钟内为真。在每个if条件内,我需要在定义的时间内为PortSet设置一个布尔值true,然后将其设置为false。我希望在重复循环时打开布尔值的过程不重复。布尔值表示先打开继电器再关闭继电器,我希望在每个唯一的ValveActive状态期间仅发生一次。

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

我已经尝试过在循环外将布尔值设置为false,然后在循环内将其变为true,但这不适用于多个if条件。我该如何实现?

1 个答案:

答案 0 :(得分:1)

创建一个新变量,例如PreviousValveActive,该变量会记住上次循环中ValveActive的值。然后使用PreviousValveActive作为测试来确定是否执行在每种状态下仅应发生一次的事情。

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