ATOM Lite(ESP32)でWiFiに常時接続してHTTP POSTする

めっちゃググったりして頑張ったのでその結果をまとめておく。

#define FASTLED_INTERNAL

#include <M5Atom.h>
#include <WiFi.h>
#include <ArduinoJson.h>
#include <HttpClient.h>

const char* ssid = "**********";
const char* password = "**********";

void post(const char* content) {
  DynamicJsonDocument doc(JSON_OBJECT_SIZE(2));
  doc["title"] = "ATOM Lite Wifi Test";
  doc["content"] = content;
  String json;
  serializeJson(doc, json);

  HTTPClient http;
  http.begin("http://httpbin.org/post");
  http.addHeader("Content-Type", "application/json");
  http.POST(json);
  Serial.println(http.getString());
  http.end();
}

void setup() {
  M5.begin(true, false, true);
  Serial.println();
}

void loop() {
  if (WiFi.status() == WL_CONNECTED) {
    if (M5.Btn.wasPressed()) {
      post("The button was pressed.");
    } 
  delay(50);
  M5.update();
  } else {
    M5.dis.drawpix(0, 0x001000);
    WiFi.begin(ssid, password);
    int wifiReconnectCount = 0;
    while (WiFi.status() != WL_CONNECTED) {
      if (wifiReconnectCount >= 300) { ESP.restart(); }
      wifiReconnectCount++;
      delay(100);
    }
    post("It's now online.");
    M5.dis.drawpix(0, 0x100000);
  }
}