0

MQTT connection not being recognised in the void loop
Moderators: adafruit_support_bill, adafruit

Forum rules
If you're posting code, please make sure your code does not include your Adafruit IO Active Key or WiFi network credentials.
Please be positive and constructive with your questions and comments.

MQTT connection not being recognised in the void loop

by ajayraj1992 on Wed Dec 09, 2020 6:26 am

I am trying to publish MPU 9250 readings in the adafruit io sending the data from ESP 32. The WiFi connection is being established, but the code is not going inside the "if(mqtt.connected())" inside the 'void loop' whereas its going inside the same command inside the 'void setup'. I am sure there is no connection issues because once I change "if(mqtt.connected())" to "while(mqtt.connected())" inside setup, code is going inside while loop continuously.

Why is the code not going inside the if command and how can this be solved?

I also tried using "MQTT_connect()" defined in the adafruit tutorial. It is giving connection failed output.

Code: Select all | TOGGLE FULL SIZE
#include <WiFi.h >
#include <Adafruit_MQTT_Client.h>
#include <MPU9250.h>

#define wifi "********"
#define password "********"
#define server "io.adafruit.com"
#define port 1883
#define username "*******"
#define key "********"

WiFiClient esp;
MPU9250 IMU(Wire,0x68);

Adafruit_MQTT_Client mqtt(&esp,server,port,username,key);
Adafruit_MQTT_Publish feed=Adafruit_MQTT_Publish(&mqtt,username"feeds/accelerodata");

void setup() {
 
  Serial.begin(115200);
  delay(10);
  Serial.println("Adafruit MQTT Demo");
  Serial.println("Connecting to");
  Serial.println(wifi);
  WiFi.begin(wifi,password);
 
  while(WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.println("Connecting...");
    }
  Serial.println("Connected");
  Serial.println("IP Address: ");
  Serial.println(WiFi.localIP());
  Serial.println("Connecting to MQTT");
 
  if(mqtt.connect())
  {
    Serial.println("MQTT Connected");
    }
}

void loop ()
 {
  Serial.println("Test line to check if code reaches inside loop");
  delay(1000);
   if(mqtt.connected())
  {
    int data=IMU.getAccelX_mss();
    Serial.println("\nSending accelero data");
    Serial.println(data);
    Serial.println("....");
    if(feed.publish(data))
    {
      Serial.println("Success");
    }
  else
   {
    Serial.println("Fail");
   }
  delay(800);
  }
 }

ajayraj1992
 
Posts: 1
Joined: Wed Dec 09, 2020 6:07 am

Re: MQTT connection not being recognised in the void loop

by jwcooper on Wed Dec 09, 2020 1:24 pm

I would suggest first trying one of the basic examples from this library and get that to work:
https://github.com/adafruit/Adafruit_IO_Arduino

Then add in your MPU 9250 readings into that example code.

jwcooper
 
Posts: 743
Joined: Tue May 01, 2012 9:08 pm

Please be positive and constructive with your questions and comments.