#define BLYNK_TEMPLATE_ID "TMPL63dRKf-UV"
#define BLYNK_TEMPLATE_NAME "Pet Feeder"
#define BLYNK_AUTH_TOKEN "P1baa8WyM-De5hoJH0bC9prd6HXHIct9"
// Include the Blynk ESP32 library
#include <WiFi.h>
#include <BlynkSimpleEsp32.h>
#include <ESP32Servo.h>
Servo s;
int degree = 0;
// Blynk authorization token
char auth[] = BLYNK_AUTH_TOKEN;
// WiFi credentials
char ssid[] = "Wokwi-GUEST";
char pass[] = "";
// Create a Blynk timer object
BlynkTimer timer;
// Ultrasonic sensor pins
#define trig 4
#define echo 2
long duration;
int distance;
WidgetLED led1(V3);
// Function to get sonar data
void sonardata() {
digitalWrite(trig, LOW); // Makes trigPin low
delayMicroseconds(2); // 2 microsecond delay
digitalWrite(trig, HIGH); // trigPin high
delayMicroseconds(10); // trigPin high for 10 microseconds
digitalWrite(trig, LOW); // trigPin low
duration = pulseIn(echo, HIGH); // Read echo pin, time in microseconds
distance = duration * 0.034 / 2; // Calculating actual/real distance
Serial.print("Distance = "); // Output distance on Arduino serial monitor
Serial.println(distance);
if (distance == 50) {
Serial.println("Distance is 50 cm, turning LED on.");
led1.on(); // Turn on the LED
} else {
led1.off(); // Turn off the LED if distance is not 50 cm
}
Blynk.virtualWrite(V3, distance);
}
// This function will be called every time a widget in the Blynk app writes to Virtual Pin 0
BLYNK_WRITE(V0) {
int buttonState = param.asInt(); // Get the state of the button from the Blynk app
if (buttonState == 1) {
s.write(90); // Rotate the servo to 90 degrees
} else {
s.write(0); // Rotate the servo back to 0 degrees
}
}
void setup() {
// Begin serial communication at a baud rate of 115200
Serial.begin(115200);
Serial.println("Connecting to Blynk...");
// Set up pin modes for the ultrasonic sensor
pinMode(trig, OUTPUT); // Sets the trigPin as an Output
pinMode(echo, INPUT); // Sets the echoPin as an Input
// Initialize Blynk
Blynk.begin(auth, ssid, pass);
// Attach the servo to pin 21
s.attach(21);
// Set timer to call sonardata function every second
timer.setInterval(1000L, sonardata);
}
void loop() {
Blynk.run(); // Run Blynk
timer.run(); // Run the timer
}