#define BLYNK_TEMPLATE_ID "TMPL5jE9tzQIO"
#define BLYNK_TEMPLATE_NAME "traindistanceIOT"
#define BLYNK_AUTH_TOKEN "ctoi6u_sXsBQxV1_GYMVkH4dMft1edGz"
#include <Wire.h>
#include <WiFi.h>
#include <WiFiClient.h>
#include <BlynkSimpleEsp32.h>
#include <LiquidCrystal_I2C.h>
// Define the Wi-Fi credentials
char auth[] = BLYNK_AUTH_TOKEN;
char ssid[] = "wokwi-GUEST";
char pass[] = "";
// Define the pins for the ultrasonic sensor, LED, relay module, and push button
#define TRIG_PIN 26
#define ECHO_PIN 25
#define LED_PIN 27
#define RELAY_PIN 27
#define BUTTON_PIN 32
// Define the I2C address of the LCD display
#define LCD_ADDR 0x27
// Initialize the LCD display
LiquidCrystal_I2C lcd(LCD_ADDR, 16, 2);
int pinValue = 0;
bool blink_mode = false;
bool motor_work = false;
bool enter_state = false;
float current_distance = 0.0;
void setup() {
Serial.begin(115200);
// Initialize Blynk
Blynk.begin(auth, ssid, pass);
if (Blynk.connected()) {
Serial.println("Connected to Blynk server");
} else {
Serial.println("Failed to connect to Blynk server");
}
// Initialize pins
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(LED_PIN, OUTPUT);
pinMode(RELAY_PIN, OUTPUT);
pinMode(BUTTON_PIN, INPUT_PULLUP);
// Initialize the LCD
Serial.println("Initializing LCD...");
lcd.init();
lcd.backlight();
lcd.print("Train Distance");
lcd.setCursor(0, 1);
lcd.print("Management");
delay(2000);
lcd.clear();
}
BLYNK_WRITE(V2) {
pinValue = param.asInt();
Serial.print("Received value: ");
Serial.println(pinValue);
}
void loop() {
Blynk.run();
// Read the push button state with debounce
bool reading = digitalRead(BUTTON_PIN);
// Send a trigger pulse to the ultrasonic sensor
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Measure the time it takes for the echo pulse to return
long duration = pulseIn(ECHO_PIN, HIGH);
// Calculate the distance to the water surface
float distance = duration * 0.034 / 2;
// Push the water level % to Blynk
float dist_percent = ((400 - distance) / 400) * 100;
Blynk.virtualWrite(V0, dist_percent);
// Update the LCD with the current distance
lcd.clear();
lcd.print("Dist: ");
lcd.print(distance, 1);
lcd.print(" cm");
// Auto mode conditions check
if (abs(current_distance - distance) >= 5 && !blink_mode) {
if (distance > 100) {
motor_work = true;
digitalWrite(RELAY_PIN, LOW);
lcd.setCursor(0, 1);
lcd.print("Motor ON");
} else {
motor_work = false;
digitalWrite(RELAY_PIN, HIGH);
lcd.setCursor(0, 1);
lcd.print("Motor OFF");
}
}
}