Skip to content

Instantly share code, notes, and snippets.

@zufardhiyaulhaq
Created September 27, 2019 15:03
Show Gist options
  • Save zufardhiyaulhaq/4a6176fd4a8d305477498f682a22204f to your computer and use it in GitHub Desktop.
Save zufardhiyaulhaq/4a6176fd4a8d305477498f682a22204f to your computer and use it in GitHub Desktop.
// DHT
#include <dht.h>
// Wifi
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
// MQTT
#include <PubSubClient.h>
// DHT11 Parameter
dht DHT;
int POWER = D5;
#define DHT11_PIN D6
// WiFi parameters to be configured
const char* ssid = "TelkomUniversity";
const char* password = "ajabingung";
// MQTT
const char *MQTT_SERVER = "10.10.10.247";
const char *MQTT_USER = "iotuser";
const char *MQTT_PASSWORD = "iotpassword";
#define MQTT_TOPIC_HUMIDITY "home/sleepingroom/humidity"
#define MQTT_TOPIC_TEMPERATURE "home/sleepingroom/temperature"
#define MQTT_TOPIC_STATE "home/sleepingroom/status"
#define MQTT_PUBLISH_DELAY 3000
#define MQTT_CLIENT_ID "sleepingroom"
long lastMsgTime = 0;
WiFiClient espClient;
PubSubClient mqttClient(espClient);
void setup(){
Serial.begin(9600);
// DHT11
pinMode(POWER, OUTPUT);
digitalWrite(POWER, HIGH);
// Set WiFi to station mode and disconnect from an AP if it was Previously
// connected
WiFi.mode(WIFI_STA);
WiFi.disconnect();
delay(100);
// WiFi
// Print the IP address
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println(WiFi.localIP());
// MQTT
mqttClient.setServer(MQTT_SERVER, 1883);
}
void loop(){
if (!mqttClient.connected()) {
mqttReconnect();
}
mqttClient.loop();
long now = millis();
if (now - lastMsgTime > MQTT_PUBLISH_DELAY) {
lastMsgTime = now;
// Read DHT11
int chk = DHT.read11(DHT11_PIN);
// Publish
mqttPublish(MQTT_TOPIC_TEMPERATURE, DHT.temperature);
mqttPublish(MQTT_TOPIC_HUMIDITY, DHT.humidity);
}
}
void mqttReconnect() {
while (!mqttClient.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (mqttClient.connect(MQTT_CLIENT_ID, MQTT_USER, MQTT_PASSWORD)) {
Serial.println("connected");
// Once connected, publish an announcement...
mqttClient.publish(MQTT_TOPIC_STATE, "connected", true);
} else {
Serial.print("failed, rc=");
Serial.print(mqttClient.state());
Serial.println(" try again in 3 seconds");
delay(3000);
}
}
}
void mqttPublish(char* topic, float payload) {
Serial.print(topic);
Serial.print(": ");
Serial.println(payload);
mqttClient.publish(topic, String(payload).c_str(), true);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment