Skip to content

Instantly share code, notes, and snippets.

@jpaulickcz
Last active February 4, 2021 17:11
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 jpaulickcz/6515700fcb5400ed7280229d5e82c942 to your computer and use it in GitHub Desktop.
Save jpaulickcz/6515700fcb5400ed7280229d5e82c942 to your computer and use it in GitHub Desktop.
Publishing data from HTU21D over MQTT with ESP8266
// Get ESP8266 going with Arduino IDE
// - https://github.com/esp8266/Arduino#installing-with-boards-manager
// Required libraries (sketch -> include library -> manage libraries)
// - PubSubClient by Nick ‘O Leary
// - DHT sensor library by Adafruit
// also based on https://gist.github.com/balloob/1176b6d87c2816bd07919ce6e29a19e9 (?)
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <Wire.h>
#include "SparkFunHTU21D.h"
HTU21D myHumidity;
#define wifi_ssid "SSID"
#define wifi_password "PASSWORD"
#define mqtt_server "hassio-pi.local"
#define humidity_topic "sensors/office/humidity"
#define temperature_topic "sensors/office/temperature"
#define client_id "bedroom_sensors" // (must be different if more boards are online connecting to the MQTT broker)
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
myHumidity.begin();
setup_wifi();
client.setServer(mqtt_server, 1883);
}
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(wifi_ssid);
WiFi.begin(wifi_ssid, wifi_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 reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
// If you do not want to use a username and password, change next line to
// if (client.connect("ESP8266Client")) {
if (client.connect(client_id)) {
Serial.println("connected");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
long lastMsg = 0;
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
long now = millis();
if (now - lastMsg > 300000) {
lastMsg = now;
float temp = myHumidity.readTemperature();
float humd = myHumidity.readHumidity();
{
Serial.print("Published temperature:");
Serial.println(String(temp).c_str());
client.publish(temperature_topic, String(temp).c_str(), true);
Serial.print("Published humidity: ");
Serial.println(String(humd).c_str());
client.publish(humidity_topic, String(humd).c_str(), true);
}
}
// delay(5000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment