#include <ESP32Servo.h>
#include <WiFi.h>
#include "ThingSpeak.h"
WiFiClient client;
const char* WIFI_NAME = "Wokwi-GUEST";
const char* WIFI_PASSWORD = "";
const int myChannelNumber =2486907;
const char* myApiKey = "F3N6CUS1T8T62Q6J";
const char* server = "api.thingspeak.com";
Servo myServo; // Objek untuk mengontrol motor servo
int potPin = 36; // Pin ADC untuk membaca nilai potensiometer
int potValue; // Variabel untuk menyimpan nilai potensiometer
int angle; // Variabel untuk sudut motor servo
int servo = 4;
int LEDRED = 16;
int LEDGREEN = 17;
int LEDYELLOW = 5;
const int switchPin = 8;
bool switchState = false;
void setup() {
myServo.attach(servo); // Hubungkan motor servo ke pin 2
pinMode(LEDRED, OUTPUT);
pinMode(LEDGREEN, OUTPUT);
pinMode(LEDYELLOW, OUTPUT);
pinMode(switchPin, INPUT_PULLUP);
Serial.begin(115200);
WiFi.begin(WIFI_NAME, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED){
Serial.print("*");
delay(100);
}
Serial.println("Wifi connected !");
Serial.println("Local IP: " + String(WiFi.localIP()));
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client);
}
void loop() {
switchState = digitalRead(switchPin);
if (!switchState){
potValue = analogRead(potPin); // Baca nilai potensiometer
angle = map(potValue, 0, 4095, 0, 180); // Ubah nilai potensiometer menjadi sudut (0-180 derajat)
ThingSpeak.setField(1,angle);
Serial.print("Potensiometer Value: ");
Serial.print(potValue);
Serial.print(" | Servo Angle: ");
Serial.println(angle);
if(angle <= 60){
LED(LOW,LOW,HIGH);
ThingSpeak.setField(4,1);
} else if (angle >= 120){
LED(HIGH,LOW,LOW);
ThingSpeak.setField(2,1);
} else {
LED(LOW,HIGH,LOW);
ThingSpeak.setField(3,1);
}
// Set sudut motor servo
delay(500); // Delay untuk stabilisasi
myServo.write(angle);
}else {
LED(LOW,LOW,LOW);
}
int x = ThingSpeak.writeFields(myChannelNumber,myApiKey);
if(x == 200){
Serial.println("Data terkirim");
}else{
Serial.println("data tidak tekirim" + String(x));
}
Serial.println("---");
}
void LED(bool x, bool y, bool z){
digitalWrite(LEDRED,x);
digitalWrite(LEDGREEN,y);
digitalWrite(LEDYELLOW,z);
}