Skip to content

Instantly share code, notes, and snippets.

@download13
Created September 8, 2016 19:19
  • Star 10 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save download13/c7c34a04d9704808fb21f73116c2858a to your computer and use it in GitHub Desktop.
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#define WIFI_SSID "yourssid"
#define WIFI_KEY "yourkey"
#define NOTIFY_URL "http://maker.ifttt.com/trigger/<eventname>/with/key/<yourkey>"
#define SECOND 1000
#define QUARTER_SECOND 250
#define SENSOR_PIN D1
bool machineRunning = false;
bool lastState = false;
int lastTripped = 0;
int tripBucket = 0;
int tripBucketLastDripped = 0;
void setup() {
Serial.begin(115200);
pinMode(SENSOR_PIN, INPUT);
}
void loop() {
int now = millis();
int sinceLastTripped = now - lastTripped;
int sinceLastDrip = now - tripBucketLastDripped;
if (tripBucket > 0 && sinceLastDrip > SECOND) {
tripBucket--;
tripBucketLastDripped = now;
Serial.print("Drip! ");
Serial.println(tripBucket);
}
// Read the state and see if the sensor was tripped
bool state = digitalRead(SENSOR_PIN) == 0 ? false : true;
if (lastState != state) {
lastState = state;
// Can be tripped a maximum of once per second
if (sinceLastTripped > QUARTER_SECOND) {
lastTripped = now;
if (tripBucket < 300) {
tripBucket++;
}
}
}
if (machineRunning && tripBucket == 0) {
machineRunning = false;
Serial.println("Machine stopped");
sendDoneNotification();
}
if (!machineRunning && tripBucket > 60) {
machineRunning = true;
Serial.println("Machine started");
}
delay(5);
}
void sendDoneNotification() {
WiFi.begin(WIFI_SSID, WIFI_KEY);
while((WiFi.status() != WL_CONNECTED)) {
delay(100);
}
HTTPClient http;
http.begin(NOTIFY_URL);
int httpCode = http.GET();
if(httpCode > 0) {
// HTTP header has been send and Server response header has been handled
Serial.printf("[HTTP] GET... code: %d\n", httpCode);
// file found at server
if(httpCode == HTTP_CODE_OK) {
String payload = http.getString();
Serial.println(payload);
}
} else {
Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
WiFi.disconnect();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment