I am working on a project were I am putting my board into deep sleep mode, and it wakes up with an interrupt from a sensor. When it wakes from deep sleep I would like to send a message to my MQTT broker. The wiring works, the interrupt works, however, the code does not.

When I use the posted code, everything looks fine in the console, I get all my print statements which would make me assume it is working. However, my MQTT broker does not show any messages. But, if I move "sendMQTTMessage()" to the loop function it works fine and the messages come through to my broker.

Any suggestions would be greatly appreciated

#include <ESP8266WiFi.h>
#include <PubSubClient.h>

const char* ssid = "*";
const char* ss_pswd = "*";
const char* mqtt_server = "*";
WiFiClient EspClient;
PubSubClient client(EspClient);

void wifi_setup() {
  Serial.print("Connecting to: ");
  WiFi.begin(ssid, ss_pswd);
  while (WiFi.status() != WL_CONNECTED) {
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
void reconnect() {
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    String ClientId = "ESP8266";
    ClientId += String(random(0xffff), HEX);
    if (client.connect(ClientId.c_str())) {
      client.publish("outtopic", "hello world, finally");
    } else {
      Serial.print("failed, rc=");
      Serial.println("Try again...");
void sendMQTTMessage() {
  Serial.println("sending your message");
  if (!client.connected()) {
  client.publish("belmont/sensor/pir/hallway", "on");
void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived: ");
  for (int i = 0; i < length; i++) {
void setup() {
  client.setServer(mqtt_server, 1883);
  Serial.println("going into deep sleep");
  ESP.deepSleep(10 * 1000000);

void loop() {
//  sendMQTTMessage();
//  delay(5000);
  • messages come through to my broker ..... so, what is the actual problem and what is your question?
    – jsotola
    Feb 3, 2019 at 1:50
  • They only come through my broker, when I place "sendMQTTMessage()" inside of the loop function WITHOUT putting it into a deep sleep. The minute I start using deep sleep I get no messages on broker. Feb 3, 2019 at 2:21
  • does any of Attempting MQTT connection... get output? Feb 3, 2019 at 2:48
  • 4
    try a delay after send
    – Juraj
    Feb 3, 2019 at 7:05

1 Answer 1


The answer for this actually goes to Juraj. It was the fact that I was missing a delay. In hindsight it makes sense, as even though I am competing tasks in order, the system is shutting down, before the actual message is sent. I added a delay(1000) between the "sendMQTTMessage()" and "ESP.deepsleep()" and it worked.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.