Sleep Electron if no cell connection is available

I have an Electron that wakes up, publishes data to the cloud, then goes back to sleep. Sometimes I am out of cellular service range though. Is there a way to run a timer and put the Electron to sleep after some set time if there is no cellular connection available?

It’s all in the docs: https://docs.particle.io/reference/firmware/electron/#waiting-for-the-system

That doesn’t seem to be working. The waitFor() function never times out.
My Electron (without the antenna connected) blinks green indicating it is searching for cellular. But it won’t be able to find it so I want it to time out and go to sleep. It won’t timeout. Am I missing something?

SYSTEM_MODE(SEMI_AUTOMATIC);
SYSTEM_THREAD(ENABLED);

void setup() {
    Serial.begin(9600);
    delay(2000);
    Serial.println("Connecting");
    Particle.connect();
    
}

void loop() {
    if (waitFor(Particle.connected, 2000)) {
        if (Particle.connected()) {
            Serial.println("connected");
        } else {
            Serial.println("timed out");
        }
        delay(100000);
    }
}

A cellular connection will hardly be established in two seconds from cold start. I can take up to 5 minutes (300000ms).

And after you entered the true branch of the if(waitFor()) condition, I’d be rather surprised if you ever got a timed out message since the very fact that you find yourself there already means Particle.connected() has to be true and nothing else.

Rather try this

    if (waitFor(Particle.connected, 60000)) {
      Serial.println("connected");
    } else {
      Serial.println("timed out");
    }
2 Likes

I am trying to put the Electron to sleep if there is no cellular connection available. So, yes, I expect to NOT receive a connection in 2 seconds.

But I see I was mis-interpreting the waitFor function. I want it to evaluate to false when there is no connection. I was able to fix the code to do what I want. Thanks @ScruffR

SYSTEM_MODE(SEMI_AUTOMATIC);

void setup() {
    Serial.begin(9600);
    delay(2000);
    Serial.println("Connecting");
    Particle.connect();
    
}

void loop() {
    if (waitFor(Particle.connected, 10000)) {
        Serial.println("connected");
        delay(100000);
    } else {
        Serial.println("timed out");
        System.sleep(SLEEP_MODE_DEEP, 15);
    }
}

OK, but 2sec is even too little to even check whether there would be a cellular network available.

Even with 10sec your device will probably never do anything else than go back to sleep.

2 Likes

Understood. That was just for testing (to guarantee no connection).