Best approach to creating a delay without interruption when calling a function?

Hi!

Working on a project very similar to the gong tutorial. However, I need to delay the ‘else if/classStart’ section by 15 minutes. But…

  1. I can not use delay because then I can not trigger the ‘if/now’ section.
  2. I also can not use millis because the setup section does not loop.
  3. I tried @peekay123’s suggestion with elapsedMillis. But that’s not going to work either.

Any ideas would be greatly appreciated! The ultimate goal is for ‘now’ to turn ON until called again and for ‘classDelay’ to wait 15 minutes after being called to turn ON for a few minutes. The crux is I can not let ‘classDelay’ interrupt ‘Now’.

Thanks,
Ian

    int ledState = LOW;                      // start with system off
    unsigned long previousMillis = 0;        // will store last time LED was updated
    const long classDelay = 30000;           // delay from when calendar notification is recieved from IFTTT (15mins)
    const long bubbleTime = 60000;           

    void setup()
    {
    Particle.function("bubble", bubble);  
    pinMode(D7, OUTPUT);  
    }

    int bubble(String command)   
    {                          
    if(command == "now")   
    {
        if (ledState == LOW) {
            ledState = HIGH;
            } else {
                ledState = LOW;
                }
        digitalWrite(D7, ledState);
        return 1;
    }  

    else if(command == "classStart")     
    {
    unsigned long currentMillis = millis();  // last bubbling

        if (currentMillis - previousMillis >= classDelay) { 
            previousMillis = currentMillis; 
            
            digitalWrite(D7, HIGH);
            
            if (currentMillis - previousMillis >= bubbleTime) { 
                previousMillis = currentMillis;
                
                digitalWrite(D7, LOW);
            }
        }
        return 2;                   
    }
    }    

    void loop()
    {
    }

You could setup a one shot software timer to fire 15 minutes after timer.start().

Or you just delegate the timing stuff to loop() by means of flags to be set in your Particle.function().

BTW, when dealing with millis() you should not mix signed and unsigned types - not even in a compare instruction.

4 Likes

Thank you this worked well!

1 Like