Getting Electron (0.5.1) to sleep after .publish

Hello,

I’m trying to publish some data and then go to sleep from an event callback function. The data gets published, but it seems that System.sleep never gets executed.

void onEvent() {
Particle.publish(“data”, “{“charged”:”+ String::format("%f",fuel.getSoC()) + “}”);
System.sleep(SLEEP_MODE_DEEP, 3600);
}

How is this onEvent() called?

If you wanted to publish and then sleep I’d add this in between the two lines

  for(uint32_t ms=millis(); millis()-ms < 10000; Particle.process());

For debugging purposes I’ve stripped down the code as much as possible.
The code below publishes the data and then Electron goes into SOS.

FuelGauge fuel;
Timer myTimer(1000, onTime);

void setup() {
myTimer.reset();
}

void onTime()
myTimer.stop();
Particle.publish(“data”, “{“charged”:”+ String::format("%f",fuel.getSoC()) + “}”);
for(uint32_t ms=millis(); millis()-ms < 10000; Particle.process());
System.sleep(SLEEP_MODE_DEEP, 30);
}

While the code below works just fine:

FuelGauge fuel;

void setup() {
Particle.publish(“data”, “{“charged”:”+ String::format("%f",fuel.getSoC()) + “}”);
for(uint32_t ms=millis(); millis()-ms < 10000; Particle.process());
System.sleep(SLEEP_MODE_DEEP, 30);
}

I am not sure what kind of interrupt the Timer generates, but it is generally bad idea to run any complex code in a interrupt handler.
Usually you set a flag in the interrupt, which you check in the main loop and if set, you run the real code. I don’t know what the rest of your code does, so I can’t be more specific.

Yup, having such code in a timer callback does in deed pose a problem.
AFAIK there is an open issue about System.sleep() in a timer callback - and adding that 10sec delay I proposed is not allowed in a timer callback either.

The easiest would be to set a flag in the callback and put the soft delay and sleep call back into loop() and fire when theflag is set.

Hello,

Moving System.sleep() outside the software timer callback function solved the RGB led blinking SOS problem.
The Particle.process() loop helps keeping the Electron up for publishing the data before getting shut down.

Thank you,
Silviu