if statement stuck in loop, how to run it only once?

102 views Asked by At

I'm creating a system that will send texts every time a temperature sensor goes outwith the limit. I need this text to only be sent once but it keeps sending.

Code:

if(temp > (userTemp + 5.00))
    {
        ledState2=1;
        device.send("led2", ledState2);

        local smsState = 0; //State, if sms has been sent yet or not

        if(smsState==0)
        {
            smsState=1;
            //This is where the sms script will be put
            server.log("SMS should send: " + smsState);         
        }
    }

Output:

2014-11-20 10:12:58 UTC+0   [Device]    Set RED LED: 1
2014-11-20 10:13:08 UTC+0   [Device]    22.3245
2014-11-20 10:13:08 UTC+0   [Agent] SMS should send: 1
2014-11-20 10:13:09 UTC+0   [Device]    Set RED LED: 1
2014-11-20 10:13:18 UTC+0   [Device]    22.2814
2014-11-20 10:13:18 UTC+0   [Agent] SMS should send: 1
2014-11-20 10:13:19 UTC+0   [Device]    Set RED LED: 1
2014-11-20 10:13:28 UTC+0   [Device]    22.3245
2014-11-20 10:13:28 UTC+0   [Agent] SMS should send: 1
2014-11-20 10:13:29 UTC+0   [Device]    Set RED LED: 1
2014-11-20 10:13:38 UTC+0   [Device]    22.2814
2014-11-20 10:13:39 UTC+0   [Agent] SMS should send: 1
2014-11-20 10:13:39 UTC+0   [Device]    Set RED LED: 1
2014-11-20 10:13:48 UTC+0   [Device]    22.3245
2014-11-20 10:13:49 UTC+0   [Agent] SMS should send: 1
2014-11-20 10:13:49 UTC+0   [Device]    Set RED LED: 1
2014-11-20 10:13:58 UTC+0   [Device]    22.2814
2014-11-20 10:13:59 UTC+0   [Agent] SMS should send: 1
2014-11-20 10:13:59 UTC+0   [Device]    Set RED LED: 1
2014-11-20 10:14:08 UTC+0   [Device]    22.3029
2014-11-20 10:14:09 UTC+0   [Agent] SMS should send: 1

I can't see why would keep sending the server.log When i enter the smsState if statement that should only run once because i change the smsState to 1 This is on an electric imp if that changes anything but i don't think it does

1

There are 1 answers

0
Kelvin Shadewing On

It's pretty simple, really. Just add a variable that keeps track of whether or not the statement has been run.

local didSend = 0;

if(temp > (userTemp + 5.00) && !didSend)
{
    didSend = 1;

    ledState2=1;
    device.send("led2", ledState2);

    local smsState = 0; //State, if sms has been sent yet or not

    if(smsState==0)
    {
        smsState=1;
        //This is where the sms script will be put
        server.log("SMS should send: " + smsState);         
    }
}

Now the if statement will not run again until you change didSend back to 0 again.