Last active
October 10, 2019 19:07
-
-
Save Dvorson/82bed75b66f495cb4b91d42fe679fda5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <ESP8266WiFi.h> | |
#include "Adafruit_MQTT.h" | |
#include "Adafruit_MQTT_Client.h" | |
#include <Wire.h> | |
#include <Adafruit_BMP280.h> | |
#define WLAN_SSID "*" | |
#define WLAN_PASS "*" | |
#define SERVER "*" | |
#define SERVERPORT 1883 | |
#define PRESENCE_FEED "*" | |
#define TMPRTR_FEED "*" | |
#define PRSR_FEED "*" | |
#define SRVC_FEED "*" | |
#define SENSOR 13 | |
unsigned long lastPub = 0; | |
int sleepInterval = 1800000; | |
int awakeTimeout = 30000; | |
int state = 0; | |
int prevState = 0; | |
int detectedCount = 0; | |
WiFiClient client; | |
Adafruit_MQTT_Client mqtt(&client, SERVER, SERVERPORT); | |
Adafruit_MQTT_Publish presence = Adafruit_MQTT_Publish(&mqtt, PRESENCE_FEED); | |
Adafruit_MQTT_Publish tmprtr = Adafruit_MQTT_Publish(&mqtt, TMPRTR_FEED); | |
Adafruit_MQTT_Publish prsr = Adafruit_MQTT_Publish(&mqtt, PRSR_FEED); | |
Adafruit_MQTT_Publish srvc = Adafruit_MQTT_Publish(&mqtt, SRVC_FEED); | |
Adafruit_BMP280 bmp; | |
void MQTT_connect() { | |
int8_t ret; | |
if (mqtt.connected()) { | |
return; | |
} | |
uint8_t retries = 3; | |
while ((ret = mqtt.connect()) != 0) { | |
mqtt.disconnect(); | |
delay(5000); | |
retries--; | |
if (retries == 0) { | |
while (1); | |
} | |
} | |
} | |
void setup() { | |
pinMode(SENSOR, INPUT); | |
pinMode(LED_BUILTIN, OUTPUT); | |
WiFi.begin(WLAN_SSID, WLAN_PASS); | |
while (WiFi.status() != WL_CONNECTED) { | |
delay(500); | |
}; | |
MQTT_connect(); | |
srvc.publish("Started"); | |
Wire.begin(5, 4); | |
bmp.begin(0x76); | |
bmp.setSampling(Adafruit_BMP280::MODE_NORMAL, | |
Adafruit_BMP280::SAMPLING_X2, | |
Adafruit_BMP280::SAMPLING_X16, | |
Adafruit_BMP280::FILTER_X16, | |
Adafruit_BMP280::STANDBY_MS_500); | |
tmprtr.publish(bmp.readTemperature()); | |
prsr.publish(bmp.readPressure() / 133.322); | |
} | |
void loop() { | |
state = digitalRead(SENSOR); | |
digitalWrite(LED_BUILTIN, 1 - state); | |
if (state) { | |
if (!prevState) detectedCount++; | |
} | |
prevState = state; | |
if (millis() > awakeTimeout) { | |
MQTT_connect(); | |
presence.publish(detectedCount); | |
delay(500); | |
ESP.deepSleep(sleepInterval); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment