Instantly share code, notes, and snippets.

Embed
What would you like to do?
IoT BOT to monitor mailbox using ESP8266 and tilt switch
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#define DEBUG
#define PIN_LED 4
#define SSID "{your_ssid}"
#define PASSWORD "{your_password}"
#define IFTTT_HOST "maker.ifttt.com"
#define IFTTT_PATH "/trigger/{your_event}/with/key/{your_key}"
WiFiClientSecure client;
void setup()
{
//LED点灯
pinMode(PIN_LED, OUTPUT);
digitalWrite(PIN_LED, HIGH);
#ifdef DEBUG
//デバッグ用にシリアルを開く
Serial.begin(115200);
Serial.println("PG start");
#endif
//WiFi接続
WiFi.mode(WIFI_STA);
//WiFi.printDiag(Serial);
WiFi.begin(SSID, PASSWORD);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
#ifdef DEBUG
Serial.print(".");
#endif
}
#ifdef DEBUG
Serial.println("");
Serial.println("WiFi connected");
//WiFi.printDiag(Serial);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
#endif
//バッテリ電圧測定
float v = readVoltage();
#ifdef DEBUG
Serial.print("Voltage: ");
Serial.print(v, 2);
Serial.println("[V]");
#endif
//IFTTTへ送信
sendIftttEvent(v);
//WiFi切断
WiFi.disconnect();
while (WiFi.status() != WL_IDLE_STATUS)
{
delay(500);
#ifdef DEBUG
Serial.print(".");
#endif
}
#ifdef DEBUG
Serial.println("");
Serial.println("WiFi disconnected");
#endif
//LED消灯
digitalWrite(PIN_LED, LOW);
// deep sleep
ESP.deepSleep(0 , WAKE_RF_DEFAULT);
delay(1000);
}
void loop() {
}
void sendIftttEvent(float voltage)
{
if (client.connect(IFTTT_HOST, 443))
{
Serial.println("Connected to IFTTT");
char buf[64];
char data[64];
int data_len = sprintf(data, "{\"value1\" : %0.2f}", voltage);
sprintf(buf, "POST %s HTTP/1.1\n", IFTTT_PATH);
client.print(buf);
sprintf(buf, "Host: %s\n", IFTTT_HOST);
client.print(buf);
client.print("User-Agent: ESP8266/1.0\n");
client.print("Connection: close\n");
client.print("Content-Type: application/json\n");
sprintf(buf, "Content-Length: %d\n\n", data_len);
client.print(buf);
client.print(data);
delay(100);
String response = client.readString();
int bodypos = response.indexOf("\r\n\r\n") + 4;
#ifdef DEBUG
Serial.println(response.substring(bodypos));
#endif
client.stop();
}
else
{
#ifdef DEBUG
Serial.println("Connection failed");
#endif
}
}
float readVoltage()
{
int cnt = 3;
float val = 0.0;
for(int i=0; i<cnt; i++)
{
val += analogRead(A0);
delay(100);
}
val /= 3;
return val * 490 / 100 / 1023;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment