#define BLYNK_PRINT Serial
// Define Blynk credentials
#define BLYNK_TEMPLATE_ID "TMPL6VrPKQvlx"
#define BLYNK_TEMPLATE_NAME "Quickstart Template"
#define BLYNK_AUTH_TOKEN "-Z1qKckQCir1Mj_pOycTqdpjXZ6Vns6-"
#include <WiFi.h>
#include <WiFiClient.h>
#include <BlynkSimpleEsp32.h>
#include <LiquidCrystal_I2C.h>
// WiFi credentials
char ssid[] = "Wokwi-GUEST"; // Your WiFi network name
char pass[] = ""; // Your WiFi password
char auth[] = "-Z1qKckQCir1Mj_pOycTqdpjXZ6Vns6-"; // Your Blynk authentication token
// Ultrasonic sensor pins
int DISTANCIA = 0;
int pinLed = 2; // LED pin
int pinEco = 12; // Echo pin
int pinGatillo = 13; // Trigger pin
int pinBuzzer = 14; // Buzzer pin
// LCD initialization (I2C address 0x27, 16 columns, 2 rows)
LiquidCrystal_I2C lcd(0x27, 16, 2);
// Function to read the distance from the ultrasonic sensor
long readUltrasonicDistance(int triggerPin, int echoPin) {
pinMode(triggerPin, OUTPUT);
digitalWrite(triggerPin, LOW); // Turn off the trigger
delayMicroseconds(2); // Wait for 2 microseconds
digitalWrite(triggerPin, HIGH); // Send the trigger pulse
delayMicroseconds(10); // Wait for 10 microseconds
digitalWrite(triggerPin, LOW); // End the trigger pulse
pinMode(echoPin, INPUT); // Set echoPin as input
return pulseIn(echoPin, HIGH); // Measure the pulse duration
}
// Blynk virtual pin handler to control the LED
BLYNK_WRITE(V0) {
int value = param.asInt(); // Get value from the app (0 or 1)
digitalWrite(pinLed, value);
}
// Setup function
void setup() {
Serial.begin(115200); // Start the serial communication
// Initialize WiFi and Blynk
Blynk.begin(BLYNK_AUTH_TOKEN, ssid, pass);
// Initialize the LCD
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Starting...");
delay(2000); // Display "Starting..." for 2 seconds
lcd.clear();
// Initialize LED and buzzer pins
pinMode(pinLed, OUTPUT);
pinMode(pinBuzzer, OUTPUT);
}
// Main loop
void loop() {
Blynk.run(); // Run Blynk
// Calculate the distance in centimeters
DISTANCIA = 0.01723 * readUltrasonicDistance(pinGatillo, pinEco);
// Send distance to Blynk gauge (Virtual Pin V1)
Blynk.virtualWrite(V1, DISTANCIA);
// Check the distance and update the LCD, LED, and buzzer
if (DISTANCIA < 100) {
digitalWrite(pinLed, HIGH); // Turn on the LED
digitalWrite(pinBuzzer, HIGH); // Turn on the buzzer
lcd.setCursor(0, 0);
lcd.print("Stock is low");
lcd.setCursor(0, 1);
lcd.print("Please restock");
} else {
digitalWrite(pinLed, LOW); // Turn off the LED
digitalWrite(pinBuzzer, LOW); // Turn off the buzzer
lcd.setCursor(0, 0);
lcd.print("Stock Available");
lcd.setCursor(0, 1);
lcd.print(" "); // Clear the second row
}
delay(500); // Update every 500ms
}