/**in Blynk work with Distance device to turn on
and of LED and Distance sensor **/
//#define BLYNK_TEMPLATE_NAME "FirstLEDBlink"
//#define BLYNK_AUTH_TOKEN "85exgL7mVAscFviHlqQ5xTpfZpGWLFtJ"
//blynk code
#define BLYNK_TEMPLATE_ID "TMPL6Kgj2cRz2"
//#define BLYNK_TEMPLATE_NAME "FirstLEDBlink"
//#define BLYNK_AUTH_TOKEN "uznx4kiaXI2wlma9RwER0ZYhKYm1nU22"
#define BLYNK_TEMPLATE_NAME "FirstLEDBlink"
#define BLYNK_AUTH_TOKEN "85exgL7mVAscFviHlqQ5xTpfZpGWLFtJ"
#define SOUND_SPEED 0.034
#define CM_TO_INCH 0.393701
#include <WiFi.h>
#include <WiFiClient.h>
#include <BlynkSimpleEsp32.h>
// Name of the router and password
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const int led = 14;
const int trigPin = 16;
const int echoPin = 17;
long duration;
float distanceCm;
float distanceInch;
// BlynkTimer initialize
BlynkTimer timer;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
pinMode(led, OUTPUT);
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
// Start wifi - 2 parameters (ssid & password)
WiFi.begin(ssid, password);
Serial.println("Connecting to WiFi");
// Connection status
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
// Connection Info
Serial.println("");
Serial.println("WiFi connected!");
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
// 3 parameters - Token, ssid, password
Blynk.begin(BLYNK_AUTH_TOKEN, ssid, password);
// 2 parameters - 1. time (L = ms) , 2. Method_Name
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;
// Convert to inches
distanceInch = distanceCm * CM_TO_INCH;
// Prints the distance in the Serial Monitor
Serial.print("Distance (cm): ");
Serial.println(distanceCm);
// Write Distance Data into Blynk
// 2 parameters - 1. pin #, 2. Value
Blynk.virtualWrite(V1, distanceCm);
}
// From Blynk to Wowki we need to write the LED status
// to write we always use this method (Blynk method)
BLYNK_WRITE(V0) {
// get the status of the virtual switch V0
int status = param.asInt();
digitalWrite(led, status);
}
void loop() {
Blynk.run();
timer.run();
}