#include <ESP32Servo.h>
#define ldrPin 2
#include <WiFi.h>
#include <ThingSpeak.h>
WiFiClient client;
long myChannelNumber = 2653668;
const char * myWriteAPIKey = "LR7BXMDH4HRHKWG9";
int statusCode;
char ssid[] = "Wokwi-GUEST";
char pass[] = "";
const int servoPin = 18;
const float gama = 0.7;
const float rl10 = 50;
Servo servo;
void setup() {
Serial.begin(115200);
Serial.println("Hello");
servo.attach(servoPin, 500, 2400);
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client); // Attach servo with pulse range
}
void loop() {
int nilaiLDR = analogRead(ldrPin);
// Convert the analog reading to a voltage value (0 to 5V)
nilaiLDR = map(nilaiLDR, 4095, 0, 1024, 0);
float voltase = nilaiLDR / 1024.0 * 5.0;
// Calculate resistance and brightness (lux) from the LDR reading
float resistansi = 2000 * voltase / (5.0 - voltase);
float kecerahan = pow(rl10 * 1e3 * pow(10, gama) / resistansi, (1 / gama));
// Map the brightness to a servo angle between 0 and 180 degrees
int servoAngle = map(kecerahan, 0, 5000, 0, 180); // Adjust 1000 based on your LDR sensitivity range
servoAngle = constrain(servoAngle, 0, 180); // Ensure angle is within bounds
// Set servo position based on light intensity
servo.write(servoAngle);
// Print the data to the Serial Monitor
Serial.print("Intensity of light = ");
Serial.print(kecerahan);
Serial.print(" lx, Servo Angle = ");
Serial.println(servoAngle);
ThingSpeak.setField(1,kecerahan);
ThingSpeak.setField(2,servoAngle);
statusCode = ThingSpeak.writeFields(myChannelNumber,myWriteAPIKey);
if(statusCode == 200) {
Serial.println("Channel update successful.");
}
else {
Serial.println("Problem Writing data. HTTP error code :" + String(statusCode));
}
delay(1000); // Delay to avoid too frequent updates
}