Published function only works once

I have a function to turn on/off diagnostic Publish calls for troubleshooting field devices. I’d rather they be off most of the time and only turn them on as needed.

I have a variable declared as:

bool diagnose = false;

I then have the following published function:

int toggleDiagnose (String command) {
  int _command = command.toInt();
  if (_command==2186) {
    diagnose = !diagnose;
    return 1;
  else {
    return 0;

Obviously, in my setup() function, I have the following:


In my code (state machine) I have logic similar to this in various state functions:

  if (diagnose) {

This helps me see what state the application is in. It seems that I can call the toggleDiagnose function once and any additional calls seem to return “Error”.

Also, is there any difference in declaring a variable “bool” vs “boolean”? They both seem to be accepted by the compiler.

bool or boolean doesn’t matter.
But the symptoms you describe may suggest some problem with the cloud connection.
Could it be that this flag also influences some reconnect code or any loops that may trap your code flow?

Just to be on the safe side, I’d also add a Particle.connected() check like this

  if (diagnose && Particle.connected()) {

It is not safe to call Particle.publish() from a Particle.function() yet, I think. The storage for Particle events/functions/variables can get corrupted.

Instead I would set a global flag in the function that does the publish once in loop() and clears the flag.

1 Like

Thanks, @bko. I forget that rule and it seems to have cleared things up.

1 Like