// Learn about the ESP32 WiFi simulation in
// https://docs.wokwi.com/guides/esp32-wifi
#include <WiFi.h>
#include <Wire.h>
#include <HTTPClient.h>
#include <ESP32Servo.h>
#include <ArduinoJson.h>
const char* apiKey = "SBL9Z3V7VJNO7SIO";
const char* channelId = "2376369";
const char* fieldId = "1";
const int servoPin = 33;
Servo myservo;
void setup() {
Serial.begin(115200);
myservo.setPeriodHertz(50);
myservo.attach(servoPin, 500, 2400);
WiFi.begin("Wokwi-GUEST", "", 6);
while (WiFi.status() != WL_CONNECTED) {
delay(250);
}
Serial.println("");
Serial.println("WiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
int readThingspeakChannel() {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
String url = "http://api.thingspeak.com/channels/" + String(channelId) + "/fields/" + String(fieldId) + ".json?api_key=" + apiKey + "&results=1";
http.begin(url);
int httpResponseCode = http.GET();
if (httpResponseCode > 0) {
String payload = http.getString();
// Use ArduinoJson to parse the JSON payload
const size_t capacity = JSON_ARRAY_SIZE(1) + JSON_OBJECT_SIZE(2) + JSON_OBJECT_SIZE(8) + JSON_OBJECT_SIZE(11) + 200;
DynamicJsonDocument doc(capacity);
deserializeJson(doc, payload);
int value = doc["feeds"][0]["field1"].as<int>();
return value;
} else {
Serial.print("Error on HTTP request: ");
Serial.println(httpResponseCode);
return -1;
}
http.end();
}
return -1;
}
void loop() {
int temperature = readThingspeakChannel();
Serial.print("Temperature: ");
Serial.println(temperature);
if (temperature != 0 && temperature != -1) {
// Adjust the servo motor angle based on the temperature read
if (temperature < 22) {
myservo.write(0); // Minimum angle
} else if (temperature >= 22 && temperature < 25) {
myservo.write(90); // Medium angle
} else {
myservo.write(180); // Maximum angle
}
}
delay(1000);
}