#define BLYNK_TEMPLATE_ID "TMPL3xaTZGogz"
#define BLYNK_TEMPLATE_NAME "NM EV IOT004"
#define BLYNK_AUTH_TOKEN "5PrFpuTp3limNn1srkoJRHxy9udXoPyX"
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <BlynkSimpleEsp32.h>
// WiFi credentials
char auth[] = BLYNK_AUTH_TOKEN;
char ssid[] = "Wokwi-GUEST";
char pass[] = "";
// Pin definitions
#define TRIG_PIN 18
#define ECHO_PIN 19
#define RED_PIN 5
#define GREEN_PIN 23
#define BLUE_PIN 22
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
// Display objects
LiquidCrystal_I2C lcd(0x27, 16, 2);
Adafruit_SSD1306 oled(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
// Function declarations
double readDistance();
void setRGBColor(int red, int green, int blue);
void setup() {
Serial.begin(115200);
// Initialize Blynk
Blynk.begin(auth, ssid, pass);
// Initialize LCD
lcd.init(); // Use init() instead of begin() for LiquidCrystal_I2C library
lcd.backlight();
// Initialize OLED
if (!oled.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
while (true); // Halt on failure
}
oled.clearDisplay();
oled.display();
// Initialize ultrasonic sensor
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
// Initialize RGB LED pins
pinMode(RED_PIN, OUTPUT);
pinMode(GREEN_PIN, OUTPUT);
pinMode(BLUE_PIN, OUTPUT);
// Set up PWM channels for the RGB LED
ledcSetup(0, 5000, 8); // Channel 0, 5 kHz, 8-bit resolution
ledcSetup(1, 5000, 8); // Channel 1, 5 kHz, 8-bit resolution
ledcSetup(2, 5000, 8); // Channel 2, 5 kHz, 8-bit resolution
ledcAttachPin(RED_PIN, 0);
ledcAttachPin(GREEN_PIN, 1);
ledcAttachPin(BLUE_PIN, 2);
}
void loop() {
Blynk.run();
// Read distance from ultrasonic sensor
double distance = readDistance();
// Update RGB LED based on distance
if (distance < 100) {
setRGBColor(255, 0, 0); // Red if too near
} else {
setRGBColor(0, 255, 0); // Green if safe distance
}
// Update LCD display
lcd.clear();
lcd.setCursor(0,0);
lcd.print(" The Vehicle is");
lcd.setCursor(0, 1);
if (distance < 100) {
lcd.print(" Too Near ");
} else {
lcd.print("Fair");
}
// Update OLED display
oled.clearDisplay();
oled.setTextSize(2); // Adjust text size if needed
oled.setTextColor(SSD1306_WHITE);
oled.setCursor(0, 0);
oled.print("Distance:");
oled.setCursor(0, 24);
oled.print(distance);
oled.display();
// Send data to Blynk
Blynk.virtualWrite(V2, distance); // Measured distance
delay(1000); // Adjust the delay as needed
}
double readDistance() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
long duration = pulseIn(ECHO_PIN, HIGH);
double distance = duration * 0.034 / 2;
return distance;
}
void setRGBColor(int red, int green, int blue) {
ledcWrite(0, red);
ledcWrite(1, green);
ledcWrite(2, blue);
}
BLYNK_WRITE(V1) {
// Here, you can add functionality to set the setpoint if needed
}