Hello,
I am trying to connect my ESP 01 WIFI module + Arduino Uno to the mosquitto broker in order to publish the collected data from the DHT22 sensor. The connection to the wifi succeeds. However it fails with the MQTT broker and I get the message
"[WiFiEsp] connecting to test.mosquitto.org
Echec de la connexion au broker MQTT"
Can you help me to solve the problem please. Thank you in advance.
This is my code:
#include <SoftwareSerial.h>
#include <SPI.h>
#include <WiFiEsp.h>
#include <WiFiEspClient.h>
#include <PubSubClient.h>
#include <DHT.h>
SoftwareSerial espSerial(2, 3); // RX, TX
char ssid[] = "............";
char password[] = "....................";
char mqtt_server[] = "test.mosquitto.org";
char mqtt_username[] = "Manel_mqtt";
char mqtt_password[] = "manelmqtt";
// Initialize the Wi-Fi client and the MQTT client
WiFiEspClient espClient;
PubSubClient client(espClient);
// DHT22
#define DHTPIN 7
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
espSerial.begin(9600);
// Initialisation of the Wi-Fi
WiFi.init(&espSerial);
// Connetion to Wi-Fi
while (WiFi.status() != WL_CONNECTED) {
Serial.println("Tentative de connexion au WiFi...");
if (WiFi.begin(ssid, password) == WL_CONNECTED) {
Serial.println("Connecté au WiFi");
} else {
delay(5000);
}
}
// Configuration of MQTT client
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
dht.begin();
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
//read data from DHT22
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();
if (isnan(humidity) || isnan(temperature)) {
Serial.println("Erreur de lecture du capteur DHT22");
delay(2000);
return;
}
String temperatureString = String(temperature);
String humidityString = String(humidity);
// Publish
client.publish("sensorM/temperature", temperatureString.c_str());
client.publish("sensorM/humidity", humidityString.c_str());
delay(10000); // Publier toutes les 10 secondes
}
void callback(char* topic, byte* payload, unsigned int length) {
// Handle the MQTT received message if necessary
}
void reconnect() {
while (!client.connected()) {
Serial.println("Tentative de connexion MQTT...");
if (client.connect("ESP8266Client", mqtt_username, mqtt_password)) {
Serial.println("Connecté au broker MQTT");
client.subscribe("command"); // Abonnez-vous aux commandes MQTT si nécessaire
} else {
Serial.print("Échec de la connexion au broker MQTT, réessai dans 5 secondes...");
delay(5000);
}
}
}