Timer with Publish happens only once but expected repeat

See below code. This is supposed to send a test message periodically using the Timer, but it only does so once. The LED blink that accompanies the publish only occurs once as well. Thanks!

int boardLed = D7;

void sendHeartbeat() {
  blinkLed(3, 200);
  Particle.publish("bethesda_labs_heartbeat", "up");

}

Timer timer(1000 * 10, sendHeartbeat);

void setup() {
    timer.start();
    pinMode(boardLed, OUTPUT);
}

void loop() {
}

void blinkLed(int n, int t) {
    for(int i = 1; i <= n; i++) {
      digitalWrite(boardLed, HIGH);
      delay(t);
      digitalWrite(boardLed, LOW);
      delay(t);
    }
}

For me this works just as expected

Thanks, that’s strange.

Well, I have since refactored it to set a flag in the timer function rather than publish, and it works.

int boardLed = D7;
boolean publishFlag = true;

void triggerHeartbeat() {
  publishFlag = true;
}

Timer timer(1000 * 10, triggerHeartbeat);

void setup() {
    timer.start();
    pinMode(boardLed, OUTPUT);
    blinkLed(3, 200);
}

void loop() {
  if (publishFlag) {
    blinkLed(3, 200);
    Particle.publish("bethesda_labs_heartbeat", "up");
    publishFlag = false;
  }
}

void blinkLed(int n, int t) {
    for(int i = 1; i <= n; i++) {
      digitalWrite(boardLed, HIGH);
      delay(t);
      digitalWrite(boardLed, LOW);
      delay(t);
    }
}
1 Like

You should think about Timer callback like an interrupt service routine; very little should happen inside that function. You have placed some blocky code in there. I’d look to write non-blocking methods for that blinking.

Even if that isn’t responsible for the problem you are seeing, it could factor. I suspect this is a component of a larger program.

4 Likes

thanks!