// thingSpeakRemote.ino - ESP32.
// Polls a ThingSpeak field and drives a pin from it, so the board can be
// switched from anywhere with an internet connection.
#include <WiFi.h>
#include <ThingSpeak.h>
const char* ssid = "YOUR_WIFI_NAME";
const char* password = "YOUR_WIFI_PASSWORD";
// From your own channel: Channel Settings, and the API Keys tab.
const unsigned long CHANNEL_ID = 0000000;
const char* READ_API_KEY = "YOUR_READ_API_KEY";
const unsigned int FIELD = 1;
const int OUTPUT_PIN = 13;
WiFiClient client;
void setup() {
Serial.begin(115200);
pinMode(OUTPUT_PIN, OUTPUT);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); }
Serial.println();
Serial.print("connected, IP = ");
Serial.println(WiFi.localIP());
ThingSpeak.begin(client);
}
void loop() {
long value = ThingSpeak.readLongField(CHANNEL_ID, FIELD, READ_API_KEY);
int status = ThingSpeak.getLastReadStatus();
if (status == 200) {
digitalWrite(OUTPUT_PIN, value ? HIGH : LOW);
Serial.print("field = ");
Serial.println(value);
} else {
// Do NOT drive the pin on a failed read - a network blip would otherwise
// switch the load off, because a failed read returns 0.
Serial.print("read failed, status ");
Serial.println(status);
}
// The free tier rate-limits to one update every 15 seconds. Polling faster
// just collects errors.
delay(20000);
}