#define BLYNK_TEMPLATE_ID "TMPL6fEPryszK"
#define BLYNK_TEMPLATE_NAME "WorkwiBlynk"
#define BLYNK_AUTH_TOKEN "7uaSyyRtFjNVAwVswZm_OfzMAjlRGmQe"
#include <WiFi.h>
#include <WiFiClient.h>
#include <BlynkSimpleEsp32.h>
#include <ESP32Servo.h>
// Define Servo
Servo s;
int degree =0;
// Define the LED pin
int led = 14;
// UltraSonic
const int trigPin = 18;
const int echoPin = 19;
//define sound speed in cm/uS
#define SOUND_SPEED 0.034
#define CM_TO_INCH 0.393701
long duration;
float distanceCm;
float distanceInch;
// Blynk authorization token
char auth[] = BLYNK_AUTH_TOKEN;
// WiFi credentials
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
// Create a Blynk timer object
BlynkTimer timer;
//Led Controll
BLYNK_WRITE(V0)
{
// Get the state of the button from the Blynk app
int buttonstate = param.asInt();
if(buttonstate ==1){
digitalWrite(led,HIGH);
}
else{
digitalWrite(led,LOW);
}
}
//Servo Controll
BLYNK_WRITE(V1)
{
// Get the state of the button from the Blynk app
int buttonState = param.asInt();
// If the button is pressed (value is 1)
if (buttonState == 1) {
// Rotate the servo clockwise
s.write(180); // Set the servo position to the desired angle (e.g., 90 degrees)
} else {
// Stop the servo when the button is released
s.write(0); // Set the servo position to the stop position (e.g., 0 degrees)
}
}
void setup() {
Serial.begin(115200);
pinMode(led,OUTPUT);
s.attach(17); // Attach the servo to pin 17
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
// Connect WiFi
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(300);
}
Serial.println();
Serial.println("Connected with IP: " + WiFi.localIP().toString());
//Blynk Connection
Serial.println("Connecting to Blynk...");
Blynk.begin(auth, WIFI_SSID, WIFI_PASSWORD);
if (Blynk.connected()) {
Serial.println("Connected to Blynk!");
} else {
Serial.println("Failed to connect to Blynk.");
}
// Connect to Blynk server with the auth token and WiFi credentials
Blynk.begin(BLYNK_AUTH_TOKEN, WIFI_SSID, WIFI_PASSWORD);
//2 PARAMETERS - 1.Time 2.Method_Name (Read to Blynk)
timer.setInterval(1000L, DistanceData);
}
void DistanceData() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculate the distance
distanceCm = duration * SOUND_SPEED/2;
// Prints the distance in the Serial Monitor
Serial.print("Distance (cm): ");
Serial.println(distanceCm);
// Send the distance data to Blynk
Blynk.virtualWrite(V2, distanceCm);
}
void loop() {
delay(10);
Blynk.run();
timer.run();
}