#define BLYNK_PRINT Serial
#include <ESP32Servo.h>
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <BlynkSimpleEsp32.h> // Include the Blynk library for ESP32
#define BLYNK_TEMPLATE_ID "TMPL6V2sCAw8G"
#define BLYNK_TEMPLATE_NAME "ULTRASONIK BLYNK"
#define BLYNK_AUTH_TOKEN "zQzEcBMSbCqfcCJsoanzJPcTGM_YPaOV"
char ssid[] = "Wokwi-GUEST"; // Replace with your Wi-Fi SSID
char pass[] = ""; // Replace with your Wi-Fi password
// Pin setup
const int trigPin = 5;
const int echoPin = 18;
const int ledPin = 2;
const int servoPin = 4;
// Threshold distances in centimeters
const int distanceThreshold = 350; // 3.5 meters (or 350 cm)
const int closeDistanceThreshold = 30; // 30 cm
Servo myServo;
void setup() {
// Initialize pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ledPin, OUTPUT);
// Attach the servo
myServo.attach(servoPin, 500, 2400); // Attach with PWM limits for ESP32
myServo.write(0); // Initial servo position
Serial.begin(115200);
// Initialize Blynk with the authentication token and Wi-Fi credentials
Blynk.begin(BLYNK_AUTH_TOKEN, ssid, pass);
}
BLYNK_WRITE(V0) {
int ledValue = param.asInt();
digitalWrite(ledPin, ledValue); // Mengontrol LED melalui Blynk
}
void loop() {
Blynk.run();
// Measure distance
long duration, distance;
// Trigger the ultrasonic pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echo pulse duration
duration = pulseIn(echoPin, HIGH);
// Calculate distance in centimeters
distance = duration * 0.034 / 2;
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Condition for distance less than 3.5 meters and more than 30 cm
if (distance >= distanceThreshold) {
digitalWrite(ledPin, HIGH); // Turn LED on
myServo.write(90); // Move servo to 90 degrees
}
// Condition for distance 30 cm or less
else if (distance <= closeDistanceThreshold) {
digitalWrite(ledPin, LOW); // Turn LED off
myServo.write(0); // Move servo to 0 degrees
}
delay(500); // Delay for stability
}