Mit dem ESP32 und DHT22 Daten per MQTT ausgeben

Chef_2

Cadet 3rd Year
Registriert
Mai 2020
Beiträge
40
Servus,

ich habe einen Schaltschrank, indem ich gerne die Temperatur und Luftfeuchtigkeit auslesen möchte...

Also 1x Sensor an Pin 12

Programm läuft (gut zusammen kopiert) ich habe nicht wirkich Ahnung vom Programmieren.

Aber ich bin ja kreativ und Schwabe... und da fangen meine Probleme an :D Ich dachte mir... ja klasse... der ESP hat ja mehrere Pins um DHT22 Sensoren zu installieren... also könnte ich noch die Außentemperatur und Raumtemperatur mit abnehmen und mir ausgeben lassen... aber so recht klappt das nicht...

Ich habe den zusätzlichen Sensor mal: DHT22PIN2 genannt... hab aber die veränderten Zeilen auskommentiert. Habe mal alle Änderungen "Fett" makiert.

Bei dem untersten Block hab ich schon mehrere Dinge ausprobiert... das kann ich nun aber nicht alles in einem Sketch wiedergeben.

Ich habs geschafft, dass er bei Node Red zwar auf Temp2 und Num2 einen Wert ausgibt... jedoch der selbe wie beim Sensor 1.


Hier mal mein Sketch:

/*
Rui Santos & Sara Santos - Random Nerd Tutorials
Complete project details at https://randomnerdtutorials.com/esp32-mqtt-publish-dht11-dht22-arduino/
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files.
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*/
#include "DHT.h"
#include <WiFi.h>
extern "C" {
#include "freertos/FreeRTOS.h"
#include "freertos/timers.h"
}
#include <AsyncMqttClient.h>
#include <ArduinoOTA.h>

#define WIFI_SSID ""
#define WIFI_PASSWORD ""

// Raspberry Pi Mosquitto MQTT Broker
#define MQTT_HOST IPAddress(192, 168, 1, 9)
// For a cloud MQTT broker, type the domain name
//#define MQTT_HOST ""
#define MQTT_PORT 1883

// Temperature MQTT Topics
#define MQTT_PUB_TEMP "esp32/dht/temperature"
#define MQTT_PUB_HUM "esp32/dht/humidity"
//#define MQTT_PUB_TEMP2 "esp32/dht/temperature2"
//#define MQTT_PUB_HUM2 "esp32/dht/humidity2"


// Digital pin connected to the DHT sensor
#define DHTPIN 12
//#define DHTPIN2 14

// Uncomment whatever DHT sensor type you're using
//#define DHTTYPE DHT11 // DHT 11
#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
//#define DHTTYPE DHT21 // DHT 21 (AM2301)

// Initialize DHT sensor
DHT dht(DHTPIN, DHTTYPE);
//DHT dht2(DHTPIN2, DHTTYPE);

// Variables to hold sensor readings
float temp;
float hum;
//float temp2;
//float hum2;


AsyncMqttClient mqttClient;
TimerHandle_t mqttReconnectTimer;
TimerHandle_t wifiReconnectTimer;

unsigned long previousMillis = 0; // Stores last time temperature was published
const long interval = 10000; // Interval at which to publish sensor readings

void connectToWifi() {
Serial.println("Connecting to Wi-Fi...");
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
}

void connectToMqtt() {
Serial.println("Connecting to MQTT...");
mqttClient.connect();
}

void WiFiEvent(WiFiEvent_t event) {
Serial.printf("[WiFi-event] event: %d\n", event);
switch(event) {
case ARDUINO_EVENT_WIFI_STA_GOT_IP:
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
connectToMqtt();
break;
case ARDUINO_EVENT_WIFI_STA_DISCONNECTED:
Serial.println("WiFi lost connection");
xTimerStop(mqttReconnectTimer, 0); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi
xTimerStart(wifiReconnectTimer, 0);
break;
}
}

void onMqttConnect(bool sessionPresent) {
Serial.println("Connected to MQTT.");
Serial.print("Session present: ");
Serial.println(sessionPresent);
}

void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
Serial.println("Disconnected from MQTT.");
if (WiFi.isConnected()) {
xTimerStart(mqttReconnectTimer, 0);
}
}

/*void onMqttSubscribe(uint16_t packetId, uint8_t qos) {
Serial.println("Subscribe acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
Serial.print(" qos: ");
Serial.println(qos);
}
void onMqttUnsubscribe(uint16_t packetId) {
Serial.println("Unsubscribe acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
}*/

void onMqttPublish(uint16_t packetId) {
Serial.print("Publish acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
}

void setup() {
Serial.begin(115200);
Serial.println();

dht.begin();

mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(connectToMqtt));
wifiReconnectTimer = xTimerCreate("wifiTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(connectToWifi));

WiFi.onEvent(WiFiEvent);

mqttClient.onConnect(onMqttConnect);
mqttClient.onDisconnect(onMqttDisconnect);
//mqttClient.onSubscribe(onMqttSubscribe);
//mqttClient.onUnsubscribe(onMqttUnsubscribe);
mqttClient.onPublish(onMqttPublish);
mqttClient.setServer(MQTT_HOST, MQTT_PORT);
// If your broker requires authentication (username and password), set them below
//mqttClient.setCredentials("REPlACE_WITH_YOUR_USER", "REPLACE_WITH_YOUR_PASSWORD");
connectToWifi();
ArduinoOTA.setHostname("OTA");
ArduinoOTA.begin();
}

void loop() {
ArduinoOTA.handle();
unsigned long currentMillis = millis();
// Every X number of seconds (interval = 10 seconds)
// it publishes a new MQTT message
if (currentMillis - previousMillis >= interval) {
// Save the last time a new reading was published
previousMillis = currentMillis;
// New DHT sensor readings
hum = dht.readHumidity();
//hum2 = dht2.readHumidity();
// Read temperature as Celsius (the default)
temp = dht.readTemperature();
//temp2 = dht2.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
//temp = dht.readTemperature(true);

// Check if any reads failed and exit early (to try again).
if (isnan(temp) || isnan(hum)) {
Serial.println(F("Failed to read from DHT sensor!"));
return;
}

// Publish an MQTT message on topic esp32/dht/temperature
uint16_t packetIdPub1 = mqttClient.publish(MQTT_PUB_TEMP, 1, true, String(temp).c_str());
Serial.printf("Publishing on topic %s at QoS 1, packetId: %i", MQTT_PUB_TEMP, packetIdPub1);
Serial.printf("Message: %.2f \n", temp);

// Publish an MQTT message on topic esp32/dht/humidity
uint16_t packetIdPub2 = mqttClient.publish(MQTT_PUB_HUM, 1, true, String(hum).c_str());
Serial.printf("Publishing on topic %s at QoS 1, packetId %i: ", MQTT_PUB_HUM, packetIdPub2);
Serial.printf("Message: %.2f \n", hum);

// Publish an MQTT message on topic esp32/dht/temperature2
//uint16_t packetIdPub3 = mqttClient.publish(MQTT_PUB_TEMP, 1, true, String(temp).c_str());
//Serial.printf("Publishing on topic %s at QoS 1, packetId: %i", MQTT_PUB_TEMP, packetIdPub1);
//Serial.printf("Message: %.2f \n", temp);

// Publish an MQTT message on topic esp32/dht/humidity2
//uint16_t packetIdPub4 = mqttClient.publish(MQTT_PUB_HUM, 1, true, String(hum).c_str());
//Serial.printf("Publishing on topic %s at QoS 1, packetId %i: ", MQTT_PUB_HUM, packetIdPub2);
//Serial.printf("Message: %.2f \n", hum);

}
}
 
willst du programmieren lernen oder die temps überwachen? weil für letzteres reicht auch z.b. shelly um 10/20€ (ohne/mit display) welches das lokal (http, mqtt, etc.) und optional und garantiert für immer gratis auch über cloud ermöglicht und damit nicht wirklich teurer ist, als ESP32 + DHT22 etc. und es gibt sie mit wasserdichten gehäusen, keine kabeln (batterien für monate/jahre oder usb-c) uvm. was du hier so nicht hast.
ansonsten fehlen ein wenig infos was genau nicht klappt etc..
hast du mal nur 1xDHT an dem 2ten pin der nicht geht probiert? also geht ein DHT an diesem pin überhaupt? ist evtl. der DHT defekt (durchtauschen)? dann weißt du mal ob jeder DHT und pin für sich so geht (dann wäre der fehler wohl eher in deinem code) oder z.b. auf dem pin nicht mgl. ist.
 
Ich bin zwar nicht so im Thema drin, aber ein "dht2.begin()" gibt es nicht?
 
Zuletzt bearbeitet:
  • Gefällt mir
Reaktionen: Darklanmaster und Jawohl
Servus @Chef_2, das ist ein Super Thread :)
wegen der Verwirrung PIN vs. logischer Name GPIO (der ich auch immer mal erliege)

... wo hängen deine beiden Sensoren drann und
welcher ESP 32 ist es denn genau (ein ESP 32-C3 .. ist bissel kleiner)

1743317654903.png


Erstmal Ahoi
.. muss nur gleich zur Orchideenmesse los
 
Servus, danke für die Antworten!

@sblive Ich möchte beides... Die Materie etwas verstehen und dabei noch was nützliches umsetzen.
Da die Sensoren frisch aus der Packung sind, habe ich jetzt noch nicht hin und her getauscht.... bei mir heißt das aber aktuell eher noch hin und her löten.

@wahli Kann sein... ich hab das mal so hinzugefügt... hätte ja gehen können.

@dms Es ist der

WEMOS LOLIN32 ESP32 Lite

An Pin 12 hängt der erste Sensor und der zweite auf Pin 14... im Programm also

#define DHTPIN 12
#define DHTPIN2 14

Hier jetzt mal der Aktuelle Sketch:

/*
Rui Santos & Sara Santos - Random Nerd Tutorials
Complete project details at https://randomnerdtutorials.com/esp32-mqtt-publish-dht11-dht22-arduino/
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files.
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*/
#include "DHT.h"
#include <WiFi.h>
extern "C" {
#include "freertos/FreeRTOS.h"
#include "freertos/timers.h"
}
#include <AsyncMqttClient.h>
#include <ArduinoOTA.h>

#define WIFI_SSID ""
#define WIFI_PASSWORD ""

// Raspberry Pi Mosquitto MQTT Broker
#define MQTT_HOST IPAddress(192, 168, 1, 9)
// For a cloud MQTT broker, type the domain name
//#define MQTT_HOST ""
#define MQTT_PORT 1883

// Temperature MQTT Topics
#define MQTT_PUB_TEMP "esp32/dht/temperature"
#define MQTT_PUB_HUM "esp32/dht/humidity"
#define MQTT_PUB_TEMP2 "esp32/dht/temperature2"
#define MQTT_PUB_HUM2 "esp32/dht/humidity2"

// Digital pin connected to the DHT sensor
#define DHTPIN 12
#define DHTPIN2 14

// Uncomment whatever DHT sensor type you're using
//#define DHTTYPE DHT11 // DHT 11
#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
//#define DHTTYPE DHT21 // DHT 21 (AM2301)

// Initialize DHT sensor
DHT dht(DHTPIN, DHTTYPE);
DHT dht2(DHTPIN2, DHTTYPE);

// Variables to hold sensor readings
float temp;
float hum;
float temp2;
float hum2;

AsyncMqttClient mqttClient;
TimerHandle_t mqttReconnectTimer;
TimerHandle_t wifiReconnectTimer;

unsigned long previousMillis = 0; // Stores last time temperature was published
const long interval = 10000; // Interval at which to publish sensor readings

void connectToWifi() {
Serial.println("Connecting to Wi-Fi...");
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
}

void connectToMqtt() {
Serial.println("Connecting to MQTT...");
mqttClient.connect();
}

void WiFiEvent(WiFiEvent_t event) {
Serial.printf("[WiFi-event] event: %d\n", event);
switch(event) {
case ARDUINO_EVENT_WIFI_STA_GOT_IP:
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
connectToMqtt();
break;
case ARDUINO_EVENT_WIFI_STA_DISCONNECTED:
Serial.println("WiFi lost connection");
xTimerStop(mqttReconnectTimer, 0); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi
xTimerStart(wifiReconnectTimer, 0);
break;
}
}

void onMqttConnect(bool sessionPresent) {
Serial.println("Connected to MQTT.");
Serial.print("Session present: ");
Serial.println(sessionPresent);
}

void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
Serial.println("Disconnected from MQTT.");
if (WiFi.isConnected()) {
xTimerStart(mqttReconnectTimer, 0);
}
}

/*void onMqttSubscribe(uint16_t packetId, uint8_t qos) {
Serial.println("Subscribe acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
Serial.print(" qos: ");
Serial.println(qos);
}
void onMqttUnsubscribe(uint16_t packetId) {
Serial.println("Unsubscribe acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
}*/

void onMqttPublish(uint16_t packetId) {
Serial.print("Publish acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
}

void setup() {
Serial.begin(115200);
Serial.println();

dht.begin();

mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(connectToMqtt));
wifiReconnectTimer = xTimerCreate("wifiTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(connectToWifi));

WiFi.onEvent(WiFiEvent);

mqttClient.onConnect(onMqttConnect);
mqttClient.onDisconnect(onMqttDisconnect);
//mqttClient.onSubscribe(onMqttSubscribe);
//mqttClient.onUnsubscribe(onMqttUnsubscribe);
mqttClient.onPublish(onMqttPublish);
mqttClient.setServer(MQTT_HOST, MQTT_PORT);
// If your broker requires authentication (username and password), set them below
//mqttClient.setCredentials("REPlACE_WITH_YOUR_USER", "REPLACE_WITH_YOUR_PASSWORD");
connectToWifi();
ArduinoOTA.setHostname("OTA");
ArduinoOTA.begin();
}

void loop() {
ArduinoOTA.handle();
unsigned long currentMillis = millis();
// Every X number of seconds (interval = 10 seconds)
// it publishes a new MQTT message
if (currentMillis - previousMillis >= interval) {
// Save the last time a new reading was published
previousMillis = currentMillis;
// New DHT sensor readings
hum = dht.readHumidity();
hum2 = dht2.readHumidity();
// Read temperature as Celsius (the default)
temp = dht.readTemperature();
temp2 = dht2.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
//temp = dht.readTemperature(true);

// Check if any reads failed and exit early (to try again).
if (isnan(temp) || isnan(hum)) {
Serial.println(F("Failed to read from DHT sensor!"));
return;
}

// Publish an MQTT message on topic esp32/dht/temperature
uint16_t packetIdPub1 = mqttClient.publish(MQTT_PUB_TEMP, 1, true, String(temp).c_str());
Serial.printf("Publishing on topic %s at QoS 1, packetId: %i", MQTT_PUB_TEMP, packetIdPub1);
Serial.printf("Message: %.2f \n", temp);

// Publish an MQTT message on topic esp32/dht/humidity
uint16_t packetIdPub2 = mqttClient.publish(MQTT_PUB_HUM, 1, true, String(hum).c_str());
Serial.printf("Publishing on topic %s at QoS 1, packetId %i: ", MQTT_PUB_HUM, packetIdPub2);
Serial.printf("Message: %.2f \n", hum);

// Publish an MQTT message on topic esp32/dht/temperature2
uint16_t packetIdPub3 = mqttClient.publish(MQTT_PUB_TEMP2, 1, true, String(temp2).c_str());
Serial.printf("Publishing on topic %s at QoS 1, packetId: %i", MQTT_PUB_TEMP2, packetIdPub3);
Serial.printf("Message: %.2f \n", temp2);
}
}

Jetzt zeigt er in Node-Red zumindest bei der zweiten Temperatur mal 0 an...

@iamahumanbeing Möchte nicht noch ein System anfangen... mir reicht jetzt Aktuell:

Arduino IDE, VS Code, Node-Red und Grafana
 
  • Gefällt mir
Reaktionen: dms
So, das Problem gelöst... oder auch nicht :D

Hab den DHT22 Sensor neu verbunden und dann kam ein Wert... Hab mitlerweile 3 Sensoren am ESP8266 und Sensor 1 und 3 funktionieren perfekt.... der zweite macht nach wie vor Probleme... daher gehe ich davon aus, dass der eine Macke hat.
 
  • Gefällt mir
Reaktionen: DTFM
Zurück
Oben