// Blynk credentials
#define BLYNK_TEMPLATE_ID "TMPL6JZsMW6uC"
#define BLYNK_TEMPLATE_NAME "ULTRASONIC"
#define BLYNK_AUTH_TOKEN "wxzkFvv_k-XGjysB86OU-qHgERf_AFW2"
// Include necessary libraries
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Stepper.h>
#include <BlynkSimpleEsp32.h>
#include <WiFi.h>
// Motor setup
#define STEPS_PER_REV 200 // Number of steps per revolution for the motor
Stepper stepper(STEPS_PER_REV, 16, 17, 5, 18); // Define motor pins
// Sensor and component pins
#define TRIG_PIN 12
#define ECHO_PIN 13
#define GREEN_LED_PIN 14
#define RED_LED_PIN 27
#define BUZZER_PIN 27
// LCD setup (pastikan I2C berada pada pin yang benar untuk ESP32)
LiquidCrystal_I2C lcd(0x27, 16, 2); // I2C address 0x27 for a 16 chars and 2 line display
// Variables
long duration;
int distance;
bool isGateOpen = false; // Track gate status
// Function to get distance from ultrasonic sensor
int getDistance() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
duration = pulseIn(ECHO_PIN, HIGH);
return duration * 0.034 / 2;
}
void setup() {
// Initialize Serial Monitor
Serial.begin(115200);
// Initialize Blynk
Blynk.begin(BLYNK_AUTH_TOKEN, "Wokwi-GUEST", "");
// Set up I2C on ESP32 (SDA = 21, SCL = 22)
Wire.begin(21, 22);
// Initialize LCD
lcd.begin(16, 2);
lcd.backlight();
// Pin modes
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(GREEN_LED_PIN, OUTPUT);
pinMode(RED_LED_PIN, OUTPUT);
pinMode(BUZZER_PIN, OUTPUT);
// Set motor speed
stepper.setSpeed(100);
}
void loop() {
// Measure distance
distance = getDistance();
// Send distance data to Blynk
Blynk.virtualWrite(V1, distance);
// If object is detected within 50 cm and the gate is closed
if (distance < 50 && !isGateOpen) {
openGate();
}
// If no object is detected and the gate is open
else if (distance >= 50 && isGateOpen) {
closeGate();
}
// Run Blynk
Blynk.run();
}
// Function to open the gate (move motor 30 steps forward)
void openGate() {
stepper.step(40); // Move motor forward 30 steps
delay(100); // Delay to allow motor to finish steps
// Display "pintu terbuka" on LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("PINTU TERBUKA");
// Turn on green LED, turn off red LED and buzzer
digitalWrite(GREEN_LED_PIN, HIGH);
digitalWrite(RED_LED_PIN, LOW);
digitalWrite(BUZZER_PIN, LOW);
// Update gate status to open
isGateOpen = true;
return;
}
// Function to close the gate (move motor back to 0)
void closeGate() {
stepper.step(-40); // Move motor back 30 steps
delay(100); // Delay to allow motor to finish steps
// Display "pintu tertutup" on LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("PINTU TERTUTUP");
// Turn on red LED and buzzer, turn off green LED
digitalWrite(RED_LED_PIN, HIGH);
digitalWrite(GREEN_LED_PIN, LOW);
digitalWrite(BUZZER_PIN, HIGH);
// Update gate status to closed
isGateOpen = false;
return;
}