#include <ESP32Servo.h>
#include <WiFi.h>
#include <ThingSpeak.h>
Servo tiltServo;
Servo elevationServo;
const int ldrPinTop = 1;
const int ldrPinBottom = 2;
const int ldrPinLeft = 3;
const int ldrPinRight = 4;
const int tiltServoPin = 38;
const int elevationServoPin = 7;
const char* ssid = "Wokwi-GUEST";
const char* password = "";
unsigned long myChannelNumber = 2721974 ;
const char* myWriteAPIKey = "KBIQMU1EV5SJ1NFW";
WiFiClient client;
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("WiFi connected");
ThingSpeak.begin(client);
tiltServo.attach(tiltServoPin);
elevationServo.attach(elevationServoPin);
pinMode(ldrPinTop, INPUT);
pinMode(ldrPinBottom, INPUT);
pinMode(ldrPinLeft, INPUT);
pinMode(ldrPinRight, INPUT);
}
void loop() {
int ldrValueTop = analogRead(ldrPinTop);
int ldrValueBottom = analogRead(ldrPinBottom);
int ldrValueLeft = analogRead(ldrPinLeft);
int ldrValueRight = analogRead(ldrPinRight);
Serial.print("Top: "); Serial.print(ldrValueTop);
Serial.print(" Bottom: "); Serial.print(ldrValueBottom);
Serial.print(" Left: "); Serial.print(ldrValueLeft);
Serial.print(" Right: "); Serial.println(ldrValueRight);
int verticalDifference = ldrValueTop - ldrValueBottom;
int horizontalDifference = ldrValueLeft - ldrValueRight;
int tiltPos = tiltServo.read();
int elevationPos = elevationServo.read();
if (horizontalDifference > 100) {
tiltPos += 1;
}
else if (horizontalDifference < -100) {
tiltPos -= 1;
}
if (verticalDifference > 100) {
elevationPos += 1;
} else if (verticalDifference < -100) {
elevationPos -= 1;
}
tiltPos = constrain(tiltPos, 0, 180);
elevationPos = constrain(elevationPos, 0, 180);
tiltServo.write(tiltPos);
elevationServo.write(elevationPos);
ThingSpeak.setField(1, ldrValueTop);
ThingSpeak.setField(2, ldrValueBottom);
ThingSpeak.setField(3, ldrValueLeft);
ThingSpeak.setField(4, ldrValueRight);
int x = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
if(x == 200){
Serial.println("Channel update successful.");
} else {
Serial.println("Problem updating channel. HTTP error code " + String(x));
}
delay(10000);
}