#include <WiFi.h>
#include <WiFiClient.h>
#include <ThingSpeak.h>
#include <ESP32Servo.h> // Use the standard Servo library compatible with ESP32
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#define SECRET_SSID "Wokwi-GUEST" // Replace with your WiFi SSID
#define SECRET_PASS "" // Replace with your WiFi Password
#define SECRET_CH_ID 2591486 // Replace with your channel number
#define SECRET_WRITE_APIKEY "UYPZFHSE771JQ2PB" // Replace with your channel write API Key
char ssid[] = SECRET_SSID;
char pass[] = SECRET_PASS;
WiFiClient client;
unsigned long myChannelNumber = SECRET_CH_ID;
const char * myWriteAPIKey = SECRET_WRITE_APIKEY;
int ldr, hujan;
Servo motor_1;
Servo motor_2;
LiquidCrystal_I2C lcd(0x27, 16, 2);
void setup() {
Serial.begin(115200);
// Initialize LCD
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("DTM PROJECT");
// Attach servos
motor_1.attach(25);
motor_2.attach(26);
// Connect to WiFi
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
// Initialize ThingSpeak
ThingSpeak.begin(client);
}
void loop() {
// Read sensors and map values
ldr = map(analogRead(34), 0, 4096, 100, 0);
hujan = map(analogRead(35), 0, 4096, 0, 100);
// Update motor state based on conditions
if (ldr < 20 || hujan > 45) {
motor_1.write(180);
motor_2.write(180);
Serial.println("Motors OFF");
} else {
motor_1.write(0);
motor_2.write(0);
Serial.println("Motors ON");
}
// Update ThingSpeak
ThingSpeak.writeField(myChannelNumber, 1, ldr, myWriteAPIKey);
ThingSpeak.writeField(myChannelNumber, 2, hujan, myWriteAPIKey);
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));
}
// Update LCD
lcd.setCursor(0, 1);
lcd.print("LDR: ");
lcd.print(ldr);
lcd.print(" Rain: ");
lcd.print(hujan);
// Simple blink effect for LCD backlight
lcd.backlight();
delay(50);
lcd.noBacklight();
delay(50);
// Wait 15 seconds to update the channel again
delay(15000);
// Print the error code at the end of loop
Serial.println("Problem updating channel. HTTP error code " + String(x));
}