// HTTP client that periodically sends WiFi status values to a ThingSpeak.com channel. // Based on below page, but modified for educational purposes: // http://nothans.com/measure-wi-fi-signal-levels-with-the-esp8266-and-thingspeak #include // WiFi credentials and client object const char* WIFI_SSID = ""; const char* WIFI_PWD = ""; WiFiClient client; // request buffer const int REQ_SIZE_MAX = 1024; const int BODY_SIZE_MAX = 512; String body; // ThingSpeak settings and HTTP POST routine const int TS_channelID = ; const char* TS_writeAPIKey = ""; const char* TS_server = "api.thingspeak.com"; const int TS_postDelay = 20 * 1000; // 20 secs between each post void postToThingSpeak(const String body) { // on first pass, reserve space for the static request string static String request = ""; if (!request.length()) { request.reserve(REQ_SIZE_MAX); } // build HTTP request for ThingSpeak API request = "POST /update HTTP/1.1\r\n" "Host: "; request.concat(TS_server); request.concat("\r\n" "Connection: close\r\n" "X-THINGSPEAKAPIKEY: "); request.concat(TS_writeAPIKey); request.concat("\r\n" "Content-Type: application/x-www-form-urlencoded\r\n" "Content-Length: "); request.concat(body.length()); request.concat("\r\n\r\n"); request.concat(body); request.concat("\r\n\r\n"); // send HTTP request to ThingSpeak API client.print(request); Serial.println(request); } // simplify handling of builtin LED; note that it is inverted w/ regards to HIGH/LOW void ledInit() { pinMode(LED_BUILTIN, OUTPUT); } boolean ledIsOn() { return (digitalRead(LED_BUILTIN) == LOW); } void ledOff() { digitalWrite(LED_BUILTIN, HIGH); } void ledOn() { digitalWrite(LED_BUILTIN, LOW); } void ledFlip() { ledIsOn() ? ledOff() : ledOn(); } // main application logic in setup() and loop() void setup() { Serial.begin(115200); body.reserve(BODY_SIZE_MAX); ledInit(); // connect to WiFi Serial.println(); Serial.println(); Serial.print("Connecting to "); Serial.print(WIFI_SSID); WiFi.begin(WIFI_SSID, WIFI_PWD); while (WiFi.status() != WL_CONNECTED) { Serial.print("."); ledFlip(); delay(250); } Serial.print(" connected, IP "); Serial.println(WiFi.localIP().toString()); } void loop() { static boolean firstPass = true; ledOn(); // connect to the ThingSpeak API server if (client.connect(TS_server, 80)) { // construct ThingSpeak request body (RSSI, SSID count, seconds since powerup, optional status msg) body = "field1="; body.concat(String(WiFi.RSSI())); body.concat("&field2="); body.concat(String(WiFi.scanNetworks())); body.concat("&field3="); body.concat(String(millis() / 1000)); if (firstPass) { body.concat("&status=> Just woke up in "); body.concat(String(millis())); body.concat(" msecs at IP "); body.concat(WiFi.localIP().toString()); firstPass = false; } // send body to ThingSpeak through a HTTP POST request postToThingSpeak(body); } client.stop(); ledOff(); // wait before repeat delay(TS_postDelay); }