While function crashes - weird data. (use of Spark.subscribe(); )

Hello! :smile:
With the new DO family (NOTE in this case) from IFTTT I wanted to send commands to my core. Every command has to trigger a while statement until another command is given.

Code:

void setup() {
  Spark.subscribe("Update_Arrow", LedFunction, MY_DEVICES); //, MY_DEVICES because my trigger settings is set to private
  Serial.begin(9600);
}

void loop() {
}

void LedFunction(const char *event, const char *data) {
  Serial.print(event);
  Serial.print(", data: ");
  Serial.println(data);

  if(0 ==strcmp(data, "hi"))  {
    Serial.println("hello! :)");
    Serial.println(data);
  }
    while(0 == strcmp(data, "cake")) {
    Serial.println("YUM! cake! :)");
    Serial.println(data);
    delay(500);
    }
}

It works quite well, except that after some time the while statement crashes. This can be seen in the serial monitor:

Opening serial monitor for com port: "COM13"
Update_Arrow, data: cake
cake
cake
cake
cake
cake
cake
cake
cake
cake
cake
cake
cake
cake
cake
cake
cake
cake
cake
cake
cake
cake
cake
cake
cake
cake
cake
cake
cake
cake
cake
cake
cake
cake
cake
cake
cake
cake
cake
cake
cake
cake
cake
cake
cake
cake
cake
cake
cake
cake
cake
cake
??♥8
???&L▬?~a5▼??↕??▲☻→Y??K2 ???{???W

I do not sent any new data through note. When I sent “cake” again, it plays the while again if nothing happens.
The time it takes for the while loop to crash is shorter when I run it for the first time.

(in case you’re wondering why I used strcmp; when I would use while(data == “cake”) it wouldn’t notice any new commands :/)

Yes, my code skills are still developing :blush:. So if you know a smarter way of doing this, your suggestion is appreciated! The idea that some while statement are executed until a new command arrives, and others are only being educated for 5 seconds and than e.g. the data string changes.

-Mark

I’m not sure if it’s related to the problems you’re seeing, but the way you’re treating your subscription handler isn’t ideal. Rather than executing all sorts of code inside your Handler, you should try to treat it as an interrupt. Set a flag inside it, which get checked in the loop. That might help, and if not, it’s still neater :wink:

Thanks! Could you give me an example?
I’m not sure what you mean :blush:

Something like this (pseudo-code):

boolean flag;

void setup() {
  Spark.subscribe("Update_Arrow", LedFunction, MY_DEVICES);
}

void loop() {
    if (flag){
    	//do stuff
    }
    else{
    	//don't do stuff, or do other stuff
    }
}

void LedFunction(const char *event, const char *data) {
	flag = true;
}