Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define BLYNK_TEMPLATE_ID "TMPL60PHVGDEq"
- #define BLYNK_TEMPLATE_NAME "TANAWA"
- #define BLYNK_AUTH_TOKEN "PtI4d8oCiM5gFwMRiOW69Hs6Nzof8caC"
- #define BLYNK_PRINT Serial
- #include <BlynkSimpleEsp32.h>
- #include <HTTPClient.h>
- #include <Arduino.h>
- #include <WiFi.h>
- #include "time.h"
- #include <ESP32Servo.h>
- #include <WebServer.h>
- WebServer server(80); // Create an HTTP server on port 80
- char auth[] = BLYNK_AUTH_TOKEN;
- BlynkTimer timer;
- // Wi-Fi credentials
- const char* ssid = "AOBY_2.4";
- const char* password = ""; // password hidden for data privacy purposes
- const char* ntpServer = "time.google.com"; // Using Google NTP server
- const long gmtOffset_sec = 3600 * 8; // Philippines Time (UTC +8)
- const int daylightOffset_sec = 0; // No DST in the Philippines
- // Pin definitions
- const int trigPin = 5;
- const int echoPin = 18;
- const int ledPin = 19;
- const int buzzerPin = 21;
- const int servoPin = 23;
- // Constants for sound speed and distance conversion
- #define SOUND_SPEED 0.034
- #define CM_TO_INCH 0.393701
- long duration;
- float distanceCm;
- float distanceInch;
- String receivedText;
- // Global variables for task synchronization
- QueueHandle_t alarmQueue;
- Servo servo1;
- String time_info;
- int alarm_info;
- bool is_servo_fixed_control;
- // Global flag to ensure only one capture request is sent per detection event.
- volatile bool captureTriggered = false;
- #define SWITCH_VPIN V2 // Use V2 for the switch in the Blynk app
- #define CAPTURE_VPIN V3
- // Blynk function to handle the switch state
- BLYNK_WRITE(SWITCH_VPIN) {
- int switchState = param.asInt();
- if (switchState == 1) {
- is_servo_fixed_control = true;
- servo1.write(0); // Move to 90° when switch is ON
- Serial.println("Servo moved to 0°");
- } else {
- is_servo_fixed_control = false;
- servo1.write(90); // Move to 0° when switch is OFF
- Serial.println("Servo moved to 90°");
- }
- }
- BLYNK_WRITE(CAPTURE_VPIN) {
- int captureState = param.asInt();
- if (captureState == 1) {
- bool alarmSignal = true;
- xQueueSend(alarmQueue, &alarmSignal, portMAX_DELAY);
- }
- }
- void sendCaptureRequest() {
- HTTPClient http;
- Serial.println("Sending capture request to Flask server...");
- http.begin("http://192.168.254.112/capture"); // ESP32 CAM code capture // CHANGE IP
- http.addHeader("Content-Type", "application/json"); // Set JSON header
- int httpResponseCode = http.GET(); // Send empty JSON body for POST request
- if (httpResponseCode > 0) {
- Serial.print("Capture Request Sent Successfully, Response code: ");
- Serial.println(httpResponseCode);
- } else {
- Serial.print("Capture Request Failed: ");
- Serial.println(http.errorToString(httpResponseCode).c_str());
- }
- http.end();
- }
- void sendSensor() {
- struct tm timeinfo;
- if (!getLocalTime(&timeinfo)) {
- Serial.println("Failed to obtain time");
- return;
- }
- char formattedTime[20];
- strftime(formattedTime, sizeof(formattedTime), "%Y%m%d_%H%M%S", &timeinfo);
- time_info = String(formattedTime);
- xQueueReceive(alarmQueue, &alarm_info, portMAX_DELAY);
- Blynk.virtualWrite(V0, time_info);
- Blynk.virtualWrite(V1, receivedText);
- // Blynk.virtualWrite(V1, alarm_info);
- }
- void sendplateNumber() {
- Blynk.virtualWrite(V1, receivedText);
- }
- void printLocalTime() {
- struct tm timeinfo;
- if (!getLocalTime(&timeinfo)) {
- Serial.println("Failed to obtain time");
- return;
- }
- char formattedTime[20];
- strftime(formattedTime, sizeof(formattedTime), "%Y%m%d_%H%M%S", &timeinfo);
- Serial.print(formattedTime);
- }
- // Task to control the servo motor
- void controlServoTask(void *pvParameters) {
- while (true) {
- bool alarm = false;
- if (xQueueReceive(alarmQueue, &alarm, portMAX_DELAY)) {
- if (!is_servo_fixed_control) {
- vTaskDelay(pdMS_TO_TICKS(2000));
- if (alarm && receivedText == "LMM 8923") {
- servo1.write(0);
- } else {
- servo1.write(90);
- }
- }
- }
- vTaskDelay(pdMS_TO_TICKS(100));
- }
- }
- // Task to measure distance using the ultrasonic sensor
- void measureDistanceTask(void *pvParameters) {
- unsigned long objectDetectedTime = 0;
- while (true) {
- // Trigger the ultrasonic pulse
- digitalWrite(trigPin, LOW);
- delayMicroseconds(2);
- digitalWrite(trigPin, HIGH);
- delayMicroseconds(10);
- digitalWrite(trigPin, LOW);
- // Measure pulse duration on echo pin
- duration = pulseIn(echoPin, HIGH);
- if (duration > 0 && duration < 30000) {
- distanceCm = duration * SOUND_SPEED / 2;
- distanceInch = distanceCm * CM_TO_INCH;
- // If an object is detected within 6 inches:
- if (distanceInch < 6) {
- if (objectDetectedTime == 0) {
- objectDetectedTime = millis();
- } else if (millis() - objectDetectedTime >= 3000) {
- bool alarmSignal = true;
- xQueueSend(alarmQueue, &alarmSignal, portMAX_DELAY);
- }
- } else {
- objectDetectedTime = 0;
- bool alarmSignal = false;
- xQueueSend(alarmQueue, &alarmSignal, portMAX_DELAY);
- }
- }
- vTaskDelay(pdMS_TO_TICKS(100));
- }
- }
- void alarmTask(void *pvParameters) {
- bool lastAlarm = false; // Keep track of the previous alarm state
- while (true) {
- bool alarm = false;
- // Wait to receive the latest alarm state from the queue.
- if (xQueueReceive(alarmQueue, &alarm, portMAX_DELAY)) {
- // Only trigger when alarm goes from false to true.
- if (alarm && !lastAlarm) {
- lastAlarm = true; // Update state
- Serial.print("Date/Time: ");
- printLocalTime();
- Serial.println(" - VEHICLE DETECTED!");
- // Reset receivedText when a new vehicle is detected
- receivedText = "";
- Serial.println("🔄 Reset receivedText for new detection.");
- // Trigger alarm pattern (LED & buzzer)
- for (int i = 0; i < 3; i++) {
- digitalWrite(ledPin, HIGH);
- digitalWrite(buzzerPin, HIGH);
- vTaskDelay(pdMS_TO_TICKS(100));
- digitalWrite(ledPin, LOW);
- digitalWrite(buzzerPin, LOW);
- vTaskDelay(pdMS_TO_TICKS(100));
- }
- // Send the capture request only once per detection event.
- if (!captureTriggered) {
- sendCaptureRequest();
- captureTriggered = true;
- }
- }
- // When the alarm goes from true to false, reset the flag.
- else if (!alarm && lastAlarm) {
- lastAlarm = false;
- captureTriggered = false;
- }
- }
- vTaskDelay(pdMS_TO_TICKS(100));
- }
- }
- // Function to handle received text from Flask
- void handleTextReception() {
- if (server.hasArg("text")) {
- receivedText = server.arg("text");
- Serial.print("📌 Extracted Text Received: ");
- Serial.println(receivedText);
- sendSensor();
- }
- server.send(200, "text/plain", "Text received");
- }
- void setup() {
- Serial.begin(115200);
- // Initialize pins for sensor, LED, buzzer.
- pinMode(trigPin, OUTPUT);
- pinMode(echoPin, INPUT);
- pinMode(ledPin, OUTPUT);
- pinMode(buzzerPin, OUTPUT);
- // Attach servo.
- servo1.attach(servoPin);
- // Connect to Wi-Fi.
- Serial.print("Connecting to ");
- Serial.println(ssid);
- WiFi.begin(ssid, password);
- while (WiFi.status() != WL_CONNECTED) {
- delay(500);
- Serial.print(".");
- }
- Serial.println("\nWiFi connected.");
- Serial.print("WiFi Signal Strength: ");
- Serial.println(WiFi.RSSI());
- // Initialize time synchronization.
- configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
- struct tm timeinfo;
- int attempts = 0;
- while (!getLocalTime(&timeinfo) && attempts < 5) {
- Serial.println("Failed to obtain time, retrying...");
- delay(2000);
- attempts++;
- }
- if (attempts == 5) {
- Serial.println("Failed to obtain time after multiple attempts.");
- } else {
- Serial.println("Time successfully synchronized!");
- printLocalTime();
- Serial.println();
- }
- // Create a queue to synchronize alarm signals.
- alarmQueue = xQueueCreate(5, sizeof(bool));
- // Start Blynk.
- Blynk.begin(auth, ssid, password);
- timer.setInterval(10000L, sendplateNumber);
- server.on("/receive_text", HTTP_GET, handleTextReception);
- server.begin();
- Serial.println("🔹 HTTP Server Started on ESP32");
- // Create FreeRTOS tasks.
- xTaskCreate(measureDistanceTask, "Measure Distance", 4096, NULL, 2, NULL);
- xTaskCreate(alarmTask, "Alarm", 4096, NULL, 1, NULL);
- xTaskCreate(controlServoTask, "Servo", 4096, NULL, 1, NULL);
- }
- void loop() {
- // Let Blynk and its timer run.
- Blynk.run();
- timer.run();
- server.handleClient();
- if (alarm_info == 1) {
- Blynk.logEvent("vehicle_detected", "Vehicle Detected! It wants to enter.");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement