DHT11 Temperature Sensor
#include < ESP8266WiFi.h >
#include < PubSubClient.h >
#include <ArduinoJson.h>
#include <DHT.h>
// define message ID and its interval
#define REPORTING_INTERVAL 15000
#define MSG_ID 30001 // Your message ID given during message definition
// define the sensor interface
#define DHT_TYPE DHT11
#define DHT_PIN 5 // GPIO 5 for D1 Pin
// define device and wifi details
#define WIFI_SSID "WIFI_SSID" // Your Wifi name
#define WIFI_PSK "WIFI_PASSWORD" // Your Wifi password
#define DOMAIN_KEY "DOMAIN_KEY" // Your platform domain key
#define API_KEY "API_KEY" // Your platform API key
#define DEVICE_ID "DEVICE_ID" // Your device ID
#define DEVICE_MODEL "DEVICE_MODEL" // Your device model
#define FIRMWARE_VER "DEVICE_FW_VERSION" // Your device's firmware version
// define Boodskap Platform MQTT configurations
#define MQTT_SERVER "orientation.boodskap.io"
#define MQTT_PORT 1883
String mqttUser = "DEV_" + String(DOMAIN_KEY);
String mqttPassword = API_KEY;
String clientid = "DEV_" + String(DEVICE_ID);
String topic =
"/" + String(DOMAIN_KEY) + "/device/" + String(DEVICE_ID) + "/msgs/" + String(DEVICE_MODEL) + "/" + String(FIRMWARE_VER) + "/" + String(MSG_ID);
DHT dht(DHT_PIN, DHT_TYPE);
uint32_t lastReport = 0;
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
dht.begin();
WiFi.begin(WIFI_SSID, WIFI_PSK);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi .....");
}
Serial.println("Connected to the WiFi network");
client.setServer(MQTT_SERVER, MQTT_PORT);
}
void loop() {
if ((millis() - lastReport) >= REPORTING_INTERVAL) {
sendStatusMessage();
lastReport = millis();
}
}
// Send Messages to the platform
void sendStatusMessage() {
StaticJsonDocument < 256 > data;
float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(h) || isnan(t)) {
return;
} else {
data["temperature"] = t;
data["humidity"] = h;
}
while (!client.connected()) {
Serial.println("Connecting to MQTT...");
Serial.println(clientid);
if (client.connect(clientid.c_str(), mqttUser.c_str(), mqttPassword.c_str())) {
Serial.println("connected");
} else {
Serial.println("failed with state ");
Serial.println(client.state());
delay(2000);
}
}
char buffer[256];
serializeJson(data, buffer);
client.publish(topic.c_str(), buffer);
client.disconnect();
}
Updated over 3 years ago