Skip to content

Instantly share code, notes, and snippets.

@tolleiv
Last active April 18, 2017 21:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tolleiv/8ac96c61a087740f3f573cdb010353bf to your computer and use it in GitHub Desktop.
Save tolleiv/8ac96c61a087740f3f573cdb010353bf to your computer and use it in GitHub Desktop.
Small project which sends measurements from an DHT22 sensor via MQTT into my home automation void.
/*
* This sketch sends data via HTTP GET requests to data.sparkfun.com service.
*
* You need to get streamId and privateKey at data.sparkfun.com and paste them
* below. Or just customize this script to talk to other HTTP servers.
*
*/
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <Adafruit_Sensor.h>
#include <PubSubClient.h>
#include <DHT.h>
#include <DHT_U.h>
extern "C" {
#include "user_interface.h"
}
#define DHT22PIN D6
#define DHT22TYPE DHT22
#define BKP_TEMP 66
#define BKP_HUM 67
#define DEVICE_NAME "diy-board-crimsonking"
#define CONFIG_TOPIC "homeassistant/diy/crimsonking/config"
#define CONFIG_PAYLOAD "{\"name\": \"crimsonking\", \"device_class\": \"sensor\"}"
#define HUMIDITY_TOPIC "homeassistant/diy/crimsonking/humidity"
#define TEMPERATURE_TOPIC "homeassistant/diy/crimsonking/temperature"
DHT_Unified dht22(DHT22PIN, DHT22TYPE);
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
char mqtt_server[50];
int mqtt_port;
int value = 0;
const char* ssid = "......";
const char* password = "......";
char hostString[16] = {0};
void setup() {
Serial.begin(115200);
delay(100);
dht22.begin();
// We start by connecting to a WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
sprintf(hostString, "ESP_%06X", ESP.getChipId());
Serial.print("Hostname: ");
Serial.println(hostString);
WiFi.hostname(hostString);
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());
if (!MDNS.begin(hostString)) {
Serial.println("Error setting up MDNS responder!");
}
while (true) {
Serial.println("Sending mDNS query");
int n = MDNS.queryService("mcmqtt", "tcp"); // Send out query for esp tcp services
Serial.println("mDNS query done");
if (n == 0) {
Serial.println("no services found");
delay(5000);
}
else {
Serial.print(n);
Serial.println(" service(s) found");
for (int i = 0; i < n; ++i) {
// Print details for each service found
Serial.print(i + 1);
Serial.print(": ");
Serial.print(MDNS.hostname(i));
Serial.print(" (");
Serial.print(MDNS.IP(i));
Serial.print(":");
Serial.print(MDNS.port(i));
Serial.println(")");
}
break;
}
Serial.println();
}
MDNS.IP(0).toString().toCharArray(mqtt_server, 51);
mqtt_port = MDNS.port(0);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
delay(100);
sensors_event_t event;
float temperature, humidity;
system_rtc_mem_read(BKP_TEMP, &temperature, 4);
system_rtc_mem_read(BKP_HUM, &humidity, 4);
if (temperature < -40.0 || temperature > 100.0) {
temperature = 0.0;
}
if (humidity < 0.0 || humidity > 100.0) {
humidity = 0.0;
}
// DHT22 -------------------------------------------------------
float dht22temp;
float dht22humi;
dht22.temperature().getEvent(&event);
if (isnan(event.temperature)) {
Serial.println("Error reading dht22 temperature!");
}
else {
dht22temp=event.temperature;
temperature=temperature*0.8+dht22temp*0.2;
}
dht22.humidity().getEvent(&event);
if (isnan(event.relative_humidity)) {
Serial.println("Error reading dht22 humidity!");
}
else {
dht22humi=event.relative_humidity;
humidity=humidity*0.8+dht22humi*0.2;
}
Serial.print("DHT22 Sample: ");
Serial.print(dht22temp); Serial.print(" *C, ");
Serial.print(dht22humi); Serial.println(" %");
Serial.println("MQTT Publish");
char* tPayload = f2s(temperature,2);
char* hPayload = f2s(humidity,0);
client.publish(TEMPERATURE_TOPIC, tPayload);
client.publish(HUMIDITY_TOPIC, hPayload);
system_rtc_mem_write(BKP_TEMP, &temperature, 4);
system_rtc_mem_write(BKP_HUM, &humidity, 4);
Serial.println("closing");
ESP.deepSleep(2 * 60 * 1000000);
delay(100);
Serial.println("wake");
}
void callback(char* topic, byte* payload, unsigned int length) {
}
/* float to string
* f is the float to turn into a string
* p is the precision (number of decimals)
* return a string representation of the float.
*/
char *f2s(float f, int p){
char * pBuff; // use to remember which part of the buffer to use for dtostrf
const int iSize = 10; // number of buffers, one for each float before wrapping around
static char sBuff[iSize][20]; // space for 20 characters including NULL terminator for each float
static int iCount = 0; // keep a tab of next place in sBuff to use
pBuff = sBuff[iCount]; // use this buffer
if(iCount >= iSize -1){ // check for wrap
iCount = 0; // if wrapping start again and reset
}
else{
iCount++; // advance the counter
}
return dtostrf(f, 0, p, pBuff); // call the library function
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
client.setServer(mqtt_server, mqtt_port);
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect(DEVICE_NAME)) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish(CONFIG_TOPIC, CONFIG_PAYLOAD);
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment