#include <WiFi.h>
#include <HTTPClient.h>
#include <ESP32Servo.h>
Servo myServo;
// WiFi credentials
const char* ssid = "Wokwi-GUEST"; // or your WiFi
const char* password = "";
// ThingSpeak
String apiKey = "TUSV7NT31EFEZXJE";
const char* server = "http://api.thingspeak.com/update";
// Pins
const int sensorPin = 34;
const int servoPin = 18;
void setup() {
Serial.begin(115200);
myServo.attach(servoPin);
// WiFi connect
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nWiFi Connected!");
Serial.println(WiFi.localIP());
}
void loop() {
if (WiFi.status() == WL_CONNECTED) {
int sensorValue = analogRead(sensorPin);
int angle = map(sensorValue, 0, 4095, 0, 180);
myServo.write(angle);
Serial.print("Sensor: ");
Serial.print(sensorValue);
Serial.print(" | Angle: ");
Serial.println(angle);
// Send to ThingSpeak
HTTPClient http;
String url = String(server) +
"?api_key=" + apiKey +
"&field1=" + String(sensorValue) +
"&field2=" + String(angle);
http.begin(url);
int response = http.GET();
if (response > 0) {
Serial.println("Data sent to ThingSpeak");
} else {
Serial.println("Failed to send data");
}
http.end();
}
delay(15000); // IMPORTANT for ThingSpeak
}