Best practice to use delay to publish + publish when value change

Hi

My first Topic here :slight_smile: but I always find a solution when searching but for now, I need advice.

My setup :

  • I use Photon and Electron with sensors and I make a Particle.publish every 5 minutes (In the Loop statement, I have a delay set to (300000) and my function to publish is called
  • I created a WebHook (particle Cloud) to retrieve my data on my server
  • I also have a function to control my Relays shield using a web page

Question :

  • I need to add to my setup a reed switch, and when the value change, I need to call my function publish. How is the best way to achieve sending every 5 minutes my publish function and manually send a publish when reed switch value change ?

THanks

2 Likes

you can use a millis() timer to publish instead of a delay like this pseudo code:

void loop(void)
{
  if((millis() - lastTransmitMillis > 5 * 60 * 1000)
  {
    Particle.publish("myEvent", "MyData");
    lastTransmitMillis = millis();
  }
  const bool reedValue = digitalRead(reedPin);
  if(reedValue != lastReedValue)
  {
    Particle.publish("reedEvent", itoa(reedValue));
    lastReedValue = reedValue;
  }
}

lastReedValue and lastTransmitMillis being declared static in loop() or global…

or… you can use a Software Timer.

There are other ways, but these two are amongst the more commonly used.

2 Likes

Thank you, I have tested and working.

1 Like

Thanks for the help @BulldogLowell!

1 Like