# PubSubClient callback not executing

**URL:** <https://forum.arduino.cc/t/pubsubclient-callback-not-executing/1134281>\
**Category:** 3rd Party Boards\
**Created:** [June 3, 2023, 4:45pm UTC](https://forum.arduino.cc/t/pubsubclient-callback-not-executing/1134281 "2023-06-03T16:45:46Z")\
**Posts on this page:** 13\
**Page:** 1

<div class="post-metadata">

**Author:** ![ab173](https://avatars.discourse-cdn.com/v4/letter/a/f08c70/32.png) [@ab173](https://forum.arduino.cc/u/ab173)\
**Post date:** [June 3, 2023, 4:45pm UTC](https://forum.arduino.cc/t/pubsubclient-callback-not-executing/1134281/1 "2023-06-03T16:45:46Z")

</div>

Hi! I am using ESP32-C3-DevKitM-1, HC-SR04 ultrasonic sensor and external LED. For MQTT I am using PubSubClient library. Publishing works fine but receiving doesn't work. I think that callback function is not executing, because in MQTT Explorer I am receiving messages, but I don't see in monitor "Starting callback". I don't know what to do anymore, please help

```arduino
#include <TimeLib.h>
#include <WiFi.h>
#include <PubSubClient.h>

// WiFi credentials
const char* ssid = "ssid";
const char* pass = "pass";

// MQTT broker details
const char* mqttServer = "xxx.xx.xx.xx";
const int mqttPort = 30000;
const char* mqttTopic = "json/BR_Real";
const char* username = "user";
const char* password = "pass";

// HC-SR04 Ultrasonic Sensor
const int trigPin = 4;
const int echoPin = 5;

// External LED
const int ledPin = 3;

WiFiClient wifiClient;
PubSubClient mqttClient(wifiClient);

float readDistance();
void connectToWiFi();
void connectToMQTT();
void publish(float distance, int led);
void callback(char* topic, byte* payload, unsigned int length);

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.println("Starting callback");
}

float readDistance() {
  // Trigger the ultrasonic sensor
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Read the echo duration
  long duration = pulseIn(echoPin, HIGH);
  // Calculate the distance based on the speed of sound
  float distance = duration * 0.034 / 2;

  return distance;
}

void connectToWiFi() {
  WiFi.begin(ssid, pass);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");
}

void connectToMQTT() {
  mqttClient.setServer(mqttServer, mqttPort);
  mqttClient.setCallback(callback);
  while (!mqttClient.connected()) {
    Serial.println("Connecting to MQTT...");
    if (mqttClient.connect("ESP32-c3", username, password)) {
      Serial.println("Connected to MQTT");
      bool result = mqttClient.subscribe("all/BR_Real", 0);
      Serial.printf("Subscribed: %d\n", result);
      mqttClient.setKeepAlive(90);
    } else {
      Serial.print("Failed to connect to MQTT, rc=");
      Serial.println(mqttClient.state());
      delay(2000);
    }
  }
}

void publish(float distance, int led) {
    time_t timestamp = now();
    char msg[300];
    snprintf(msg, sizeof(msg),
        "\"header\":{\"timeStamp\":%ld},"
        "\"body\":{"
        "\"BikeRentalActuator\":{\"BikeRentalLed\":%d},"
        "\"BikeRentalHC-SR04\":{\"BikeRentalDistance\":%.2f}}}", 
          timestamp, led, distance);

    bool status = mqttClient.publish(mqttTopic, msg);

    if (status) {
      Serial.printf("Sending `%s` to topic `%s`\n", msg, mqttTopic);
    } else {
      Serial.printf("Failed to send message to topic %s.", mqttTopic);
    }
}

void reconnect() {
  while (!mqttClient.connected()) {
    if (mqttClient.connect("clientID", username, password)) {
      Serial.println("Connected to MQTT");
      bool result = mqttClient.subscribe("all/BR_Real");
      Serial.printf("Subscribed: %d\n", result);
      mqttClient.setKeepAlive(90);
    } else {
      Serial.print("Failed to connect to MQTT, rc=");
      Serial.println(mqttClient.state());
      delay(2000);
    }
  }
}

void setup() {
  Serial.begin(115200);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW); 

  connectToWiFi();
  connectToMQTT();
  delay(2000);
}

void loop() {
  if (!mqttClient.connected()) {
    reconnect();
  }
  mqttClient.loop(); // Maintain MQTT communication
  delay(100);

  float distance = readDistance();

  if (distance < 0.5) {
    digitalWrite(ledPin, LOW); 
  } else {
    digitalWrite(ledPin, HIGH); 
    publish(distance, 0);

  }

  delay(1000);
}

```

Monitor output is:

```arduino
Connecting to WiFi...
Connecting to WiFi...
Connecting to WiFi...
Connected to WiFi
Connecting to MQTT...
Connected to MQTT
Subscribed: 1
Sending `"header":{"timeStamp":6},"body":{"BikeRentalActuator":{"BikeRentalLed":0},"BikeRentalHC-SR04":{"BikeRentalDistance":0.00}}}` to topic `json/BR_Real`
Connected to MQTT
Subscribed: 1

```

---

<div class="post-metadata">

**Author:** ![UKHeliBob](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/ukhelibob/32/215663_2.png) [@UKHeliBob](https://forum.arduino.cc/u/UKHeliBob)\
**Post date:** [June 3, 2023, 5:58pm UTC](https://forum.arduino.cc/t/pubsubclient-callback-not-executing/1134281/2 "2023-06-03T17:58:40Z")

</div>

Welcome to the forum

If you do not see the message indicating that the callback() function has been executed then the obvious conclusion would be that no message has been received

Does the sketch connect to WiFi ?  
Does the sketch ever connect to the broker ?  
Do you see the printouts indicating that the message has been sent ?

---

<div class="post-metadata">

**Author:** ![ab173](https://avatars.discourse-cdn.com/v4/letter/a/f08c70/32.png) [@ab173](https://forum.arduino.cc/u/ab173)\
**Post date:** [June 3, 2023, 6:15pm UTC](https://forum.arduino.cc/t/pubsubclient-callback-not-executing/1134281/3 "2023-06-03T18:15:52Z")

</div>

It prints out "Connected to WiFi" and "Connected to MQTT", so I think sketch is connected to broker and WiFi? I think that message is arrived beacuse I see message in [MQTT Explorer](http://mqtt-explorer.com/). Sorry I am new to Arduino.

---

<div class="post-metadata">

**Author:** ![UKHeliBob](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/ukhelibob/32/215663_2.png) [@UKHeliBob](https://forum.arduino.cc/u/UKHeliBob)\
**Post date:** [June 3, 2023, 6:51pm UTC](https://forum.arduino.cc/t/pubsubclient-callback-not-executing/1134281/4 "2023-06-03T18:51:58Z")

</div>

Look closely at the topic that you are publishing to and the topic that you are subscribing to

Are they the same ?

---

<div class="post-metadata">

**Author:** ![ab173](https://avatars.discourse-cdn.com/v4/letter/a/f08c70/32.png) [@ab173](https://forum.arduino.cc/u/ab173)\
**Post date:** [June 3, 2023, 6:59pm UTC](https://forum.arduino.cc/t/pubsubclient-callback-not-executing/1134281/5 "2023-06-03T18:59:58Z")

</div>

How they can be same? Publishing is working correctly

---

<div class="post-metadata">

**Author:** ![UKHeliBob](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/ukhelibob/32/215663_2.png) [@UKHeliBob](https://forum.arduino.cc/u/UKHeliBob)\
**Post date:** [June 3, 2023, 7:04pm UTC](https://forum.arduino.cc/t/pubsubclient-callback-not-executing/1134281/6 "2023-06-03T19:04:13Z")

</div>

If you publish to json/BR\_Real but do not subscribe to it would you expect to receive any massages from it ?

---

<div class="post-metadata">

**Author:** ![ab173](https://avatars.discourse-cdn.com/v4/letter/a/f08c70/32.png) [@ab173](https://forum.arduino.cc/u/ab173)\
**Post date:** [June 3, 2023, 7:17pm UTC](https://forum.arduino.cc/t/pubsubclient-callback-not-executing/1134281/7 "2023-06-03T19:17:09Z")

</div>

I have to publish to json/BR\_Real but subsribe to all/BR\_Real

---

<div class="post-metadata">

**Author:** ![UKHeliBob](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/ukhelibob/32/215663_2.png) [@UKHeliBob](https://forum.arduino.cc/u/UKHeliBob)\
**Post date:** [June 3, 2023, 7:34pm UTC](https://forum.arduino.cc/t/pubsubclient-callback-not-executing/1134281/8 "2023-06-03T19:34:19Z")

</div>

That does not answer my question

Why do you need to publish to one topic and subscribe to another ?

As an experiment try publishing and subscribing to the same topic

---

<div class="post-metadata">

**Author:** ![ab173](https://avatars.discourse-cdn.com/v4/letter/a/f08c70/32.png) [@ab173](https://forum.arduino.cc/u/ab173)\
**Post date:** [June 4, 2023, 7:40am UTC](https://forum.arduino.cc/t/pubsubclient-callback-not-executing/1134281/9 "2023-06-04T07:40:35Z")

</div>

Because purpose of subscribing is to receive messages from a topic and publishing is meant for sending messages to a topic. It is recommended to use two different topic for publishing and subsribing. That's how it is configured in platform that I am connecting to publish and subsribe.

---

<div class="post-metadata">

**Author:** ![UKHeliBob](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/ukhelibob/32/215663_2.png) [@UKHeliBob](https://forum.arduino.cc/u/UKHeliBob)\
**Post date:** [June 4, 2023, 7:43am UTC](https://forum.arduino.cc/t/pubsubclient-callback-not-executing/1134281/10 "2023-06-04T07:43:50Z")

</div>

Please explain in simple terms what the sketch is supposed to do. What is publishing to the all/BR\_Real topic ?

---

<div class="post-metadata">

**Author:** ![ab173](https://avatars.discourse-cdn.com/v4/letter/a/f08c70/32.png) [@ab173](https://forum.arduino.cc/u/ab173)\
**Post date:** [June 4, 2023, 6:36pm UTC](https://forum.arduino.cc/t/pubsubclient-callback-not-executing/1134281/11 "2023-06-04T18:36:44Z")

</div>

I have to receive message from all/BR\_Real topic. Meesage contains LED status, if LED = 1 turn on external LED, wait 10 seconds and then turn off external LED. I have to publish to json/BR\_Real my distance returned from ultrasonic sensor and led status. Therefore I have to subscribe to all/BR\_Real topic and publish to json/BR\_Real

---

<div class="post-metadata">

**Author:** ![UKHeliBob](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/ukhelibob/32/215663_2.png) [@UKHeliBob](https://forum.arduino.cc/u/UKHeliBob)\
**Post date:** [June 4, 2023, 9:25pm UTC](https://forum.arduino.cc/t/pubsubclient-callback-not-executing/1134281/12 "2023-06-04T21:25:37Z")

</div>

Now we are getting somewhere

So, something is publishing to the all/BR\_Real topic.  
Are you sure that this is happening correctly ?

---

<div class="post-metadata">

**Author:** ![system](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/system/32/1140315_2.png) [@system](https://forum.arduino.cc/u/system)\
**Post date:** [December 1, 2023, 9:26pm UTC](https://forum.arduino.cc/t/pubsubclient-callback-not-executing/1134281/13 "2023-12-01T21:26:28Z")

</div>

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