#include <WiFi.h>
#include <HTTPClient.h>
#include <ESP32Servo.h>
#include <Arduino_JSON.h>
const int ldr = 34;
const int trig = 19;
const int echo = 18;
int servoPin = 15;
int ldrValue;
long echotime;
float distance;
const char* ssid ="Wokwi-GUEST";
const char* pass ="";
String serverName = "https://sgp1.blynk.cloud/external/api/batch/update?token=6hEJQQNYFs0vP4klZ0Uoteugwe2JmVlw&v0=";
String serverName2 = "https://sgp1.blynk.cloud/external/api/get?token=6hEJQQNYFs0vP4klZ0Uoteugwe2JmVlw&v0&v1&v2";
Servo servo;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
servo.attach(servoPin, 500, 2400);
pinMode(trig, OUTPUT);
pinMode(echo, INPUT);
digitalWrite(trig, LOW);
WiFi.begin(ssid,pass);
while (WiFi.status() != WL_CONNECTED){
delay(500);
Serial.print('.');
}
Serial.print('wifi terhubung dengan ip address: ');
Serial.println(WiFi.localIP());
}
void loop() {
HTTPClient http;
String serverPath,mybuff;
int httpResponseCode;
byte dataservo;
// put your main code here, to run repeatedly:
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
echotime= pulseIn(echo, HIGH);
distance= 0.0001*((float)echotime*340.0)/2.0;
ldrValue= analogRead(ldr);
Serial.print("Nilai LDR :");
Serial.println(ldrValue);
Serial.print("Jarak :");
Serial.println(distance);
if (WiFi.status() == WL_CONNECTED){
serverPath = serverName + String(ldrValue) + "&v1=" + String(distance);
http.begin(serverPath);
httpResponseCode = http.GET();
if (httpResponseCode==200)
{
Serial.println("HTTP Response code: " + String(httpResponseCode));
}
http.end();
} // this speeds up the simulation
else
{
Serial.println("WiFi Disconnected");
}
if(WiFi.status()== WL_CONNECTED)
{
serverPath = serverName2;
http.begin(serverPath);
httpResponseCode = http.GET();
if (httpResponseCode==200)
{
String payload = http.getString();
JSONVar myObject = JSON.parse(payload);
if (JSON.typeof(myObject) == "undefined")
{
Serial.println("Parsing error bro!");
}
else
{
JSONVar mykeys = myObject.keys();
mybuff = JSON.stringify(myObject[mykeys[2]]);
Serial.print("ini valuenya: ");
Serial.println(mybuff); //json format from server is {"v0":29.6,"v1":89.1,"v2":1}
dataservo=mybuff.toInt();
Serial.println(dataservo);
servo.write(dataservo);
}
}
Serial.println(httpResponseCode);
http.end();
}
else
{
Serial.println("WiFi Disconnected");
}
delay(3000);
}