[Solved] Spark Interval Timer and MQTT publish

Hi guys,

I am using Spark Interval Timer library and MQTT library to control publishing interval.

But in the interrupt function, the MQTT publish function can’t act then the entire code is stopped.

Then the photon blink stops(light blue)

Here is my entire code


#include "SparkIntervalTimer.h"
#include "MQTT.h"

// Declare timer class
IntervalTimer myTimer;

char buf[250];

void callback(char* topic, byte* payload, unsigned int length);
void interruptFunc();

// Set the server domain and port
MQTT client("quickstart.messaging.internetofthings.ibmcloud.com", 1883, callback);



void setup() {
    
    delay(5000);
    Serial.begin(9600);
    
    pinMode(A0,INPUT);
    
    // connect to the server
    client.connect("d:quickstart:Photon:00FFBBCCDE10");
    Serial.println("Connected");
    
    
    myTimer.begin(interruptFunc,2000,hmSec);
    
}

// recieve message
void callback(char* topic, byte* payload, unsigned int length) {

}

// Interrupt Function
void interruptFunc(){

    sprintf(buf, "{\"d\":{\"myName\":\"Photon\",\"potentiometer\": %d }}", analogRead(A0));
    client.publish("iot-2/evt/status/fmt/json",buf);
    

}

void loop(void) {

    if (client.isConnected()) {

    }
    
    else {
        Serial.println("Disconnected");
        client.connect("d:quickstart:Photon:00FFBBCCDE10");
    }

}

I think something is crashed between Interval Timer function and MQTT publish function.

What do you think about this problem?

1 Like

I solve the problem!

As the manual of Interval Timer, in the interrupt function, just using flag variable works well.

If someone who want to using these two library, this code may be helpful.

Thank you guys.

void interruptFunc(){
    Tempflag = 1;
}

void loop(void) {

    if (client.isConnected()) {
        if (Tempflag){
            sprintf(buf, "{\"d\":{\"myName\":\"Photon\",\"potentiometer\": %d }}", 100);
            client.publish("iot-2/evt/status/fmt/json",buf);
            Serial.println("Send");
            Tempflag = 0;
        }
        else{
            Serial.println("wait");
        }
    }
    
    else {
        Serial.println("Disconnected");
        client.connect("d:quickstart:Photon:00FFBBCCDE10");
    }

}
2 Likes

Oh phew, I’m so glad I found your post bc I have been going nuts trying to make this work…

THANK YOU!

  • Henry