#include <ESP32Servo.h>
#include <WiFi.h>
#include <ThingSpeak.h>
// Create Servo objects
Servo tiltServo;
Servo elevationServo;
// LDR pin assignments (adjust for your specific ESP32)
const int ldrPinTop = 34; // LDRs for sunlight detection
const int ldrPinBottom = 35;
const int ldrPinLeft = 32;
const int ldrPinRight = 33;
// Servo pin assignments
const int tiltServoPin = 18; // Tilt servo
const int elevationServoPin = 15; // Elevation servo
// WiFi and ThingSpeak credentials
const char* ssid = "Wokwi-GUEST"; // WiFi SSID
const char* password = ""; // WiFi Password
unsigned long myChannelNumber = 2725487 ; // ThingSpeak Channel Number
const char* myWriteAPIKey = "BQAYRDU8FZP7Q8RV"; // ThingSpeak Write API Key
WiFiClient client;
void setup() {
Serial.begin(115200);
// Connect to WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("WiFi connected");
// Initialize ThingSpeak
ThingSpeak.begin(client);
// Attach servos to pins
tiltServo.attach(tiltServoPin);
elevationServo.attach(elevationServoPin);
// Set LDR pins as input
pinMode(ldrPinTop, INPUT);
pinMode(ldrPinBottom, INPUT);
pinMode(ldrPinLeft, INPUT);
pinMode(ldrPinRight, INPUT);
}
void loop() {
// Read LDR values
int ldrValueTop = analogRead(ldrPinTop);
int ldrValueBottom = analogRead(ldrPinBottom);
int ldrValueLeft = analogRead(ldrPinLeft);
int ldrValueRight = analogRead(ldrPinRight);
// Print LDR values to Serial
Serial.print("Top: "); Serial.print(ldrValueTop);
Serial.print(" Bottom: "); Serial.print(ldrValueBottom);
Serial.print(" Left: "); Serial.print(ldrValueLeft);
Serial.print(" Right: "); Serial.println(ldrValueRight);
// Calculate differences
int verticalDifference = ldrValueTop - ldrValueBottom;
int horizontalDifference = ldrValueLeft - ldrValueRight;
// Read current servo positions
int tiltPos = tiltServo.read();
int elevationPos = elevationServo.read();
// Adjust tilt servo position based on horizontal difference
if (horizontalDifference > 100) {
tiltPos += 1;
}
else if (horizontalDifference < -100) {
tiltPos -= 1;
}
// Adjust elevation servo position based on vertical difference
if (verticalDifference > 100) {
elevationPos += 1;
} else if (verticalDifference < -100) {
elevationPos -= 1;
}
// Constrain servo positions
tiltPos = constrain(tiltPos, 0, 180);
elevationPos = constrain(elevationPos, 0, 180);
// Move the servos to new positions
tiltServo.write(tiltPos);
elevationServo.write(elevationPos);
// Update ThingSpeak with LDR values
ThingSpeak.setField(1, ldrValueTop);
ThingSpeak.setField(2, ldrValueBottom);
ThingSpeak.setField(3, ldrValueLeft);
ThingSpeak.setField(4, ldrValueRight);
// Write to ThingSpeak
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 before the next loop
delay(10000);
}