Using MQTT to publish from Photon

I’m trying to publish to the mosquitto test server when there’s a button press in the Photon. However, it only runs once even though there’s a loop present.

if(buttonState == LOW)

    // if light is currently off, switch to on
    if(ledStatus == "off")
        ledStatus = "on";
        if (client.isConnected())
            digitalWrite(led7, HIGH);
            client.publish("doorOpen", "Door Opened");
            //client.publish("timeStamp", Time.timeStr());
        digitalWrite(led, HIGH);
        digitalWrite(led7, LOW);
        ledStatus = "off";
        digitalWrite(led, LOW);

    // else light must be on, so switch to off


// wait 0.2 seconds before checking button again

Not too sure what I’m doing wrong. I also noticed that it won’t publish at all if the if(client.isConnected()) is located after the delay(20000);

You have 25+ seconds of delay in your loop() after the initial button press, so that doesn’t help responsiveness :wink:

It’s highly advisable to avoid delay() entirely.

Also when already checking for client.isConnected() it would make sense to do something in case that is not the case - i.e. reconnect.

We are also missing some context

  • can ledStatus be changed anywhere else than in the code shown?
  • if not, that “flag” is superfluous
  • if yes, then whenever the current state is "on" no button press will have any effect until the state gets reset to "off" somewhere else
  • what does the rest of your code do?
1 Like

Would the delay be a reason to not publish at all?

I’ll add more functionality for the if client isn’t connected. Thanks !

As for the context, that is pretty much the main body of the code. I just skipped copying the setup and the initializing parts of the code. ledstatus is originally set as off. As for the project, it’s sort of a concept demo I’m working on for proper hand sanatization timer. So I can’t take the delays out. Or rather I need some method to create that 25 second gap.

You can, you just need to be clever about it :wink:
For simple time stuff like that you can use millis() as a base and measure the time between the last state to the next.
For more elaborate stuff FSM would be the paradigm to follow.

Alternatively you can use Software Timers.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.