Electron particle publish causes hard fault when embedded in a timer call back

This code works

   pinMode(led, OUTPUT);
   pinMode(led2,OUTPUT);
   timer.start();
    
}

void loop(){

 digitalWrite(led,HIGH);
 delay(3000);
 String Temp2 = String(random(40,70));
 Particle.publish("temp2", Temp2, PRIVATE);
 digitalWrite(led, LOW);
 delay(3000);
 }

void statusUpdate(){
  digitalWrite(led2,HIGH);
 //Particle.publish("temp2", Temp2, PRIVATE);       
 delay(3000);
 digitalWrite(led2,LOW); 
    
}

This code causes a hard fault

int led = D7;
int led2 = D6;
int Temp1 = A0;
int Temp2 = A4;
short batmon = A7;
bool highwater = D0;
bool intru = D2;
Timer timer(5000, statusUpdate);

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

void loop(){
 digitalWrite(led,HIGH);
 delay(3000);
 //String Temp2 = String(random(40,70));
 //Particle.publish("temp2", Temp2, PRIVATE);
 digitalWrite(led, LOW);
 delay(3000);
 
 }

void statusUpdate(){
 digitalWrite(led2,HIGH);
 delay(3000);
 String Temp2 = String(random(40,70));
 Particle.publish("temp2", Temp2, PRIVATE);
 digitalWrite(led2, LOW);
 delay(3000);
    
}

@wselrahc12, as indicated in the documenation, Software Time callbacks need to be treated like ISRs and need to be “lite”. In other words, making Cloud function calls like Particle.Publish() is not going to work, as you noticed. Instead, set a flag in your callback and sample that flag in loop() and take action there (ie. do the publish there). :wink:

1 Like

One obvious “fault” in that timer callback is that the timer is firing every 5sec, but the callback takes at least 6sec, due to the delays. That will evemtually fill up your call stack causing an SOS.

But as @peekay123 already said, even without that, you should not do extensive work in timers anyway.

1 Like