The use of the ESP8266 in the world of IoT

User avatar
By crazysky
#89232 Hi,

the mqtt part of my code must have some mistake. I wonder because I thought I have just used it successfuly in another project.
Somehow it goes into a loop. Watch the attached picture to understand what I mean. I can't find the mistake.

Code: Select allvoid loop() {

if(WiFi.status() != WL_CONNECTED){
    while (WiFi.status() != WL_CONNECTED){
      connect();
      uint8_t timeout = 8;
      while (timeout && (WiFi.status() != WL_CONNECTED)) {
        timeout--;
        delay(1000);
      }
    }
  }

  if(!client.connected()){
 
      Serial.println("test nach client.connected");
       while(!client.connected()){
      Serial.println("Connecting to MQTT...");
      client.connect("ESP8266Client", mqttUser, mqttPassword);
      uint8_t timeout = 8;
      while (timeout && (!client.connected())){
        timeout--;
        delay(1000);
      }
  if (client.connect("ESP8266Client", mqttUser, mqttPassword )) {

      Serial.println("connected");
delay(2000);
    } else {

      Serial.print("failed with state ");
      Serial.print(client.state());

    }

    client.subscribe("bad/fenster");
    client.subscribe("kueche/fenster");

       }
  }


Unbenannt.JPG

Can anyone help?
(full code also attached)
You do not have the required permissions to view the files attached to this post.
User avatar
By urs_eppenberger
#89679 I ran your code through 'Auto Format' in the Arduino IDE to make it a little bit more readable.

There is one thing which is certainly worth looking into:
Code: Select all      if (client.connect("ESP8266Client", mqttUser, mqttPassword )) {
        Serial.println("connected");
        delay(2000);
      } else {

The 2 seconds delay afterwards is most probably not a good idea. The ESP needs time to handle WiFi/TCP/MQTT. Blocking it for two seconds with the delay command does not help here. I suggest to get rid of it.

If you do not exactly understand how to manage WiFi and MQTT connections, restarting them if they fail, etc, then I suggest to stick very closely to the provided examples and just add your own measurement routines to the example code. There are various ways to get it right, but the examples are the reference, for me too, btw.

Kind regards,

Urs Eppenberger
Switzerland