简体   繁体   中英

Not able to Receive subscribed Message with PubSubClient.h in Arduino WeMos D1 R32

I'm using Arduino Wemos Esp32 D1 R32. I'm trying to make an MQTT connection between My Arduino board and a MQTT Broker. When I try to send messages from my Arduino, It works just fine. (I'm using a pullup button to send a message.) Whenever I press the button a message is sent. But when I try to read a message and write it on the Serial with the callback function it just doesn't work. Could someone please help me with that issue?

Here is my code:

[code]
#include <ETH.h>
#include <WiFi.h>
#include <WiFiAP.h>
#include <WiFiClient.h>
#include <WiFiGeneric.h>
#include <WiFiMulti.h>
#include <WiFiScan.h>
#include <WiFiServer.h>
#include <WiFiSTA.h>
#include <WiFiType.h>
#include <WiFiUdp.h>


#include <PubSubClient.h>


#define BUFFER_SIZE 100
#define pinBotao1 25  //input botao pullup
#define led 26        //output acende led
#define pot 4         //input Resistor

//WiFi
const char* SSID = "******";                // SSID / nome da rede WiFi que deseja se conectar
const char* PASSWORD = "******";   // Senha da rede WiFi que deseja se conectar
WiFiClient wifiClient;                        

//MQTT Server
const char* BROKER_MQTT = "mqtt.eclipse.org"; //URL do broker MQTT que se deseja utilizar
int BROKER_PORT = 1883;                      // Porta do Broker MQTT
#define ID_MQTT  "BCI0111"            
#define TOPIC_PUBLISH "BCIBotao111"   



PubSubClient MQTT(wifiClient);        // Instancia o Cliente MQTT passando o objeto espClient

//Declaração das Funções
void mantemConexoes();  //Garante que as conexoes com WiFi e MQTT Broker se mantenham ativas
void conectaWiFi();     //Faz conexão com WiFi
void conectaMQTT();     //Faz conexão com Broker MQTT
void enviaPacote();     //Envia uma mensagem ao Broker.

void callback(char* topic, byte* payload, unsigned int length) {
 Serial.print("Message arrived [");
 Serial.print(topic);
 Serial.print("] ");
 for (int i=0;i<length;i++) {
    Serial.print((char)payload[i]);
 }
 Serial.println();
 }

void setup() {
  pinMode(pinBotao1, INPUT_PULLUP);
  pinMode(led, OUTPUT);         

  Serial.begin(115200);

  conectaWiFi();
  MQTT.setServer(BROKER_MQTT, BROKER_PORT);   
  MQTT.setCallback(callback);
}

void loop() {
  mantemConexoes();
  enviaValores();
  MQTT.loop();
}

void mantemConexoes() {
    if (!MQTT.connected()) {
       conectaMQTT(); 
    }

    conectaWiFi(); //se não há conexão com o WiFI, a conexão é refeita
}

void conectaWiFi() {

  if (WiFi.status() == WL_CONNECTED) {
     return;
  }

  Serial.print("Conectando-se na rede: ");
  Serial.print(SSID);
  Serial.println("  Aguarde!");

  WiFi.begin(SSID, PASSWORD); // Conecta na rede WI-FI  
  while (WiFi.status() != WL_CONNECTED) {
      delay(1000);
      Serial.print(".");
      WiFi.begin(SSID, PASSWORD);
  }

  Serial.println();
  Serial.print("Conectado com sucesso, na rede: ");
  Serial.print(SSID);  
  Serial.print("  IP obtido: ");
  Serial.println(WiFi.localIP()); 
}

void conectaMQTT() { 
    while (!MQTT.connected()) {
        Serial.print("Conectando ao Broker MQTT: ");
        Serial.println(BROKER_MQTT);
        //if (MQTT.connect(ID_MQTT,USER_MQTT,PASSWORD_MQTT)) {
        if (MQTT.connect(ID_MQTT)) {
            Serial.println("Conectado ao Broker com sucesso!");
        } 
        else {
            Serial.println("Nao foi possivel se conectar ao broker.");
            Serial.println("Nova tentativa de conexao em 10s");
            delay(10000);
        }
    }
}

void enviaValores() {
  bool estadoBotao1;
  int estadoPot;

  estadoBotao1 = digitalRead(pinBotao1);
  estadoPot = char(analogRead(pot));

  if (estadoBotao1==LOW) {

        //Botao Apertado     
        MQTT.publish(TOPIC_PUBLISH, "estadoPot");
        Serial.println("Botao1 APERTADO. Payload enviado.");

     }
     delay(1000);
}

You need to subscribe to one or more topics to receive messages. Typically you subscribe to the topic(s) you are interested in after connecting to MQTT, but you may also subscribe at other times based on your app's logic.

In this case you can change conectaMQTT like this:

void conectaMQTT() { 
    while (!MQTT.connected()) {
        Serial.print("Conectando ao Broker MQTT: ");
        Serial.println(BROKER_MQTT);
        //if (MQTT.connect(ID_MQTT,USER_MQTT,PASSWORD_MQTT)) {
        if (MQTT.connect(ID_MQTT)) {
            Serial.println("Conectado ao Broker com sucesso!");
            if (MQTT.subscribe(TOPIC_SUBSCRIBE)) {
                Serial.println("Succesful subscription.");
            } else {
                Serial.println("Subscription failed.");
            }
        } 
        else {
            Serial.println("Nao foi possivel se conectar ao broker.");
            Serial.println("Nova tentativa de conexao em 10s");
            delay(10000);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM