Skip to content

Instantly share code, notes, and snippets.

@bgulla
Created March 16, 2018 02:20
Show Gist options
  • Save bgulla/e82d4e888313bccd70e4a85008439510 to your computer and use it in GitHub Desktop.
Save bgulla/e82d4e888313bccd70e4a85008439510 to your computer and use it in GitHub Desktop.
#include <ESP8266WiFi.h>
#include <Wire.h>
#include <PubSubClient.h>
#include <Adafruit_BMP085.h>
//#include <Adafruit_HDC1000.h>
#define wifi_ssid "ssid"
#define wifi_password "redacted"
#define mqtt_server "10.0.1.11"
//#define mqtt_user "your_username"
//#define mqtt_password "your_password"
#define humidity_topic "patio/humidity"
#define temperature_topic "patio/temperature"
WiFiClient espClient;
PubSubClient client(espClient);
Adafruit_BMP085 bmp;
double floatmod(double a, double b)
{
return (a - b * floor(a / b));
}
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("ESP8266Client", mqtt_user, mqtt_password)) {
if (client.connect("ESP8266Client")) {
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);
}
}
}
bool checkBound(float newValue, float prevValue, float maxDiff) {
return !isnan(newValue) &&
(newValue < prevValue - maxDiff || newValue > prevValue + maxDiff);
}
long lastMsg = 0;
float temp = 0.0;
float hum = 0.0;
float diff = 1.0;
void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
Wire.pins(0, 2);
Wire.begin(0, 2);
if (!bmp.begin()) {
Serial.println("No BMP180 / BMP085");// we dont wait for this
// while (1) {}
}
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
long now = millis();
if (now - lastMsg > 1000) {
lastMsg = now;
float newTemp = bmp.readTemperature() * 9/5 + 32;
float newHum = bmp.readPressure();
if (checkBound(newTemp, temp, diff)) {
temp = newTemp;
Serial.print("New temperature:");
Serial.println(String(temp).c_str());
client.publish(temperature_topic, String(temp).c_str(), true);
}
if (checkBound(newHum, hum, diff)) {
hum = newHum;
Serial.print("New humidity:");
Serial.println(String(hum).c_str());
client.publish(humidity_topic, String(hum).c_str(), true);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment