#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
// Dados WiFi (Wokwi)
const char* ssid = "Wokwi-GUEST";
const char* password = ""; // normalmente não precisa
// Configurações ThingSpeak
const String channelID = "3127767"; // coloque o seu channel ID aqui
const String readAPIKey = " LQZP6TX01HEP6CDN"; // chave de leitura do ThingSpeak (se configurado)
// Variáveis para status dos interruptores
bool st_sala = false;
bool st_quarto = false;
bool st_cozinha = false;
// Função para ler um campo do ThingSpeak e retornar o último valor como int
int readField(int fieldNumber) {
HTTPClient http;
String url = "https://api.thingspeak.com/channels/" + channelID + "/fields/" + String(fieldNumber) + ".json?results=1";
if (readAPIKey.length() > 0) {
url += "&api_key=" + readAPIKey;
}
http.begin(url);
int httpCode = http.GET();
if (httpCode > 0) {
String payload = http.getString();
http.end();
// Parse JSON usando ArduinoJson
StaticJsonDocument<1024> doc;
DeserializationError error = deserializeJson(doc, payload);
if (!error) {
// Acesse o último feed
JsonArray feeds = doc["feeds"];
if (feeds.size() > 0) {
const char* fieldValue = feeds[0][("field" + String(fieldNumber)).c_str()];
if (fieldValue != nullptr) {
return atoi(fieldValue);
}
}
} else {
Serial.println("Erro ao parsear JSON");
}
} else {
Serial.println("Erro HTTP: " + String(httpCode));
http.end();
}
return -1; // erro
}
void setup() {
Serial.begin(115200);
delay(1000);
Serial.println("Conectando ao WiFi...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nWiFi conectado!");
}
void loop() {
// Ler os campos do ThingSpeak
int salaVal = readField(1);
int quartoVal = readField(2);
int cozinhaVal = readField(3);
if (salaVal != -1) {
st_sala = (salaVal == 1);
}
if (quartoVal != -1) {
st_quarto = (quartoVal == 1);
}
if (cozinhaVal != -1) {
st_cozinha = (cozinhaVal == 1);
}
Serial.println("Estado dos interruptores:");
Serial.printf("Sala: %d, Quarto: %d, Cozinha: %d\n", st_sala, st_quarto, st_cozinha);
delay(10000); // espera 10 segundos para próxima leitura
}