Skip to content

Instantly share code, notes, and snippets.

@mojiAh
Created February 20, 2017 07:55
Show Gist options
  • Save mojiAh/8e3e2f728db38986caf0bbb55e3b32c9 to your computer and use it in GitHub Desktop.
Save mojiAh/8e3e2f728db38986caf0bbb55e3b32c9 to your computer and use it in GitHub Desktop.
ESP8266 code to pub/sub mqtt topic (Temperature and Humidity)
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>
// DHT settings
#define DHTTYPE DHT11
const int buttonPin = 14;
int buttonState = 0;
const int DHTPIN = 12;
DHT dht(DHTPIN, DHTTYPE);
//Wifi Settings
const char* ssid = "ssid";
const char* password = "wifi password";
//mqtt settings
const char* mqtt_server = "server ip";
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, mqtt port);
client.setCallback(callback);
reconnect();
}
void setup_wifi(){
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
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]);
}
if((char)payload[0] == 'o' && (char)payload[1] == 'n') //on
digitalWrite(4,HIGH);
else if((char)payload[0] == 'o' && (char)payload[1] == 'f' && (char)payload[2] == 'f') //off
digitalWrite(4,LOW);
Serial.println();
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ESP8266Client", "username" , "password")) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("ESP8266/connection status", "Connected!");
// ... and resubscribe
client.subscribe("ESP8266/connection status");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void dhtMeasureNow(float &h, float &t) {
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
h = dht.readHumidity();
// Read temperature as Celsius (the default)
t = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
float f = dht.readTemperature(true);
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Compute heat index in Fahrenheit (the default)
float hif = dht.computeHeatIndex(f, h);
// Compute heat index in Celsius (isFahreheit = false)
float hic = dht.computeHeatIndex(t, h, false);
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" *C ");
Serial.print(f);
Serial.print(" *F\t");
Serial.print("Heat index: ");
Serial.print(hic);
Serial.print(" *C ");
Serial.print(hif);
Serial.println(" *F");
}
void loop() {
if (!client.connected()) {
reconnect();
}
//client.loop();
delay(1000);
float humidity, temperature;
dhtMeasureNow(humidity, temperature);
char sTemp[10], sHumi[10];
dtostrf (humidity, 6, 2, sHumi);
dtostrf (temperature, 6, 2, sTemp);
char shadow[100];
strcpy(shadow, "{\"state\":{\"reported\": {\"temperature\":");
strcat(shadow, sTemp);
strcat(shadow, ", \"humidity\":");
strcat(shadow, sHumi);
strcat(shadow, "}}}");
Serial.println(shadow);
client.publish("test", shadow);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment