Advertisement
CHU2

vss

Feb 11th, 2025 (edited)
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Arduino 7.62 KB | Source Code | 0 0
  1. #define BLYNK_TEMPLATE_ID "TMPL6tSitw7kx"
  2. #define BLYNK_TEMPLATE_NAME "Tanawa Template"
  3. #define BLYNK_AUTH_TOKEN "3f9t3xoMaZgWy2MLqTUG0ulcXDcvXjyh"
  4.  
  5. #define BLYNK_PRINT Serial
  6. #include <BlynkSimpleEsp32.h>
  7. #include <HTTPClient.h>
  8. #include <Arduino.h>
  9. #include <WiFi.h>
  10. #include "time.h"
  11. #include <ESP32Servo.h>
  12. #include <WebServer.h>
  13.  
  14. WebServer server(80);  // Create an HTTP server on port 80
  15.  
  16. char auth[] = BLYNK_AUTH_TOKEN;
  17. BlynkTimer timer;
  18.  
  19. // Wi-Fi credentials
  20. const char* ssid = "";  // Wifi and Password are hidden for data privacy purposes
  21. const char* password = "";
  22. const char* ntpServer = "time.google.com";  // Using Google NTP server
  23.  
  24. const long gmtOffset_sec = 3600 * 8;  // Philippines Time (UTC +8)
  25. const int daylightOffset_sec = 0;    // No DST in the Philippines
  26.  
  27. // Pin definitions
  28. const int trigPin = 5;
  29. const int echoPin = 18;
  30. const int ledPin = 19;
  31. const int buzzerPin = 21;
  32. const int servoPin = 23;
  33.  
  34. // Constants for sound speed and distance conversion
  35. #define SOUND_SPEED 0.034
  36. #define CM_TO_INCH 0.393701
  37.  
  38. long duration;
  39. float distanceCm;
  40. float distanceInch;
  41. String receivedText;
  42.  
  43. // Global variables for task synchronization
  44. QueueHandle_t alarmQueue;
  45.  
  46. Servo servo1;
  47.  
  48. String time_info;
  49. int alarm_info;
  50. bool is_servo_fixed_control;
  51.  
  52. // Global flag to ensure only one capture request is sent per detection event.
  53. volatile bool captureTriggered = false;
  54.  
  55. #define SWITCH_VPIN V2  // Use V2 for the switch in the Blynk app
  56. #define CAPTURE_VPIN V3  
  57.  
  58. // Blynk function to handle the switch state
  59. BLYNK_WRITE(SWITCH_VPIN) {
  60.   int switchState = param.asInt();
  61.   if (switchState == 1) {
  62.     is_servo_fixed_control = true;
  63.     servo1.write(0);
  64.     Serial.println("Servo moved to 0°");
  65.   } else {
  66.     is_servo_fixed_control = false;
  67.     servo1.write(90);
  68.     Serial.println("Servo moved to 90°");
  69.   }
  70. }
  71.  
  72. BLYNK_WRITE(CAPTURE_VPIN) {
  73.   int captureState = param.asInt();
  74.   if (captureState == 1) {
  75.     bool alarmSignal = true;
  76.     xQueueSend(alarmQueue, &alarmSignal, portMAX_DELAY);
  77.   }
  78. }
  79.  
  80. void controlServoTask(void *pvParameters) {
  81.   while (true) {
  82.     if (receivedText == "LMM 8923") {  // Check if the plate number matches
  83.       Serial.println("✅ Authorized Vehicle Detected! Opening Gate...");
  84.       servo1.write(0);  // Open the gate
  85.       vTaskDelay(pdMS_TO_TICKS(5000));  // Keep gate open for 5 seconds
  86.       Serial.println("❌ Closing Gate...");
  87.       servo1.write(90);  // Close the gate
  88.       receivedText = "";  // Reset the received text to avoid re-triggering
  89.     }
  90.     vTaskDelay(pdMS_TO_TICKS(500));  // Check every 500ms
  91.   }
  92. }
  93.  
  94.  
  95. void sendCaptureRequest() {
  96.   HTTPClient http;
  97.   Serial.println("Sending capture request to Flask server...");
  98.  
  99.   http.begin("http://192.168.254.112/capture");
  100.   http.addHeader("Content-Type", "application/json");
  101.   int httpResponseCode = http.GET();
  102.  
  103.   if (httpResponseCode > 0) {
  104.     Serial.print("Capture Request Sent Successfully, Response code: ");
  105.     Serial.println(httpResponseCode);
  106.   } else {
  107.     Serial.print("Capture Request Failed: ");
  108.     Serial.println(http.errorToString(httpResponseCode).c_str());
  109.   }
  110.  
  111.   http.end();
  112. }
  113.  
  114. void sendSensor() {
  115.   struct tm timeinfo;
  116.   if (!getLocalTime(&timeinfo)) {
  117.     Serial.println("Failed to obtain time");
  118.     return;
  119.   }
  120.   char formattedTime[20];
  121.   strftime(formattedTime, sizeof(formattedTime), "%Y%m%d_%H%M%S", &timeinfo);
  122.   time_info = String(formattedTime);
  123.   xQueueReceive(alarmQueue, &alarm_info, portMAX_DELAY);
  124.   Blynk.virtualWrite(V0, time_info);
  125.   Blynk.virtualWrite(V1, receivedText);
  126. }
  127.  
  128. void sendplateNumber() {
  129.   Blynk.virtualWrite(V1, receivedText);
  130. }
  131.  
  132. void printLocalTime() {
  133.   struct tm timeinfo;
  134.   if (!getLocalTime(&timeinfo)) {
  135.     Serial.println("Failed to obtain time");
  136.     return;
  137.   }
  138.   char formattedTime[20];
  139.   strftime(formattedTime, sizeof(formattedTime), "%Y%m%d_%H%M%S", &timeinfo);
  140.   Serial.print(formattedTime);
  141. }
  142.  
  143. // Task to measure distance using the ultrasonic sensor
  144. void measureDistanceTask(void *pvParameters) {
  145.   unsigned long objectDetectedTime = 0;
  146.   while (true) {
  147.     digitalWrite(trigPin, LOW);
  148.     delayMicroseconds(2);
  149.     digitalWrite(trigPin, HIGH);
  150.     delayMicroseconds(10);
  151.     digitalWrite(trigPin, LOW);
  152.  
  153.     duration = pulseIn(echoPin, HIGH);
  154.     if (duration > 0 && duration < 30000) {
  155.       distanceCm = duration * SOUND_SPEED / 2;
  156.       distanceInch = distanceCm * CM_TO_INCH;
  157.  
  158.       if (distanceInch < 6) {
  159.         if (objectDetectedTime == 0) {
  160.           objectDetectedTime = millis();
  161.         } else if (millis() - objectDetectedTime >= 3000) {
  162.           bool alarmSignal = true;
  163.           xQueueSend(alarmQueue, &alarmSignal, portMAX_DELAY);
  164.         }
  165.       } else {
  166.         objectDetectedTime = 0;
  167.         bool alarmSignal = false;
  168.         xQueueSend(alarmQueue, &alarmSignal, portMAX_DELAY);
  169.       }
  170.     }
  171.     vTaskDelay(pdMS_TO_TICKS(100));
  172.   }
  173. }
  174.  
  175. void alarmTask(void *pvParameters) {
  176.   bool lastAlarm = false;
  177.  
  178.   while (true) {
  179.     bool alarm = false;
  180.     if (xQueueReceive(alarmQueue, &alarm, portMAX_DELAY)) {
  181.       if (alarm && !lastAlarm) {
  182.         lastAlarm = true;
  183.         Serial.print("Date/Time: ");
  184.         printLocalTime();
  185.         Serial.println(" - VEHICLE DETECTED!");
  186.  
  187.         receivedText = "";
  188.         Serial.println("🔄 Reset receivedText for new detection.");
  189.  
  190.         for (int i = 0; i < 3; i++) {
  191.           digitalWrite(ledPin, HIGH);
  192.           digitalWrite(buzzerPin, HIGH);
  193.           vTaskDelay(pdMS_TO_TICKS(100));
  194.           digitalWrite(ledPin, LOW);
  195.           digitalWrite(buzzerPin, LOW);
  196.           vTaskDelay(pdMS_TO_TICKS(100));
  197.         }
  198.  
  199.         if (!captureTriggered) {
  200.           sendCaptureRequest();
  201.           captureTriggered = true;
  202.         }
  203.       } else if (!alarm && lastAlarm) {
  204.         lastAlarm = false;
  205.         captureTriggered = false;
  206.       }
  207.     }
  208.     vTaskDelay(pdMS_TO_TICKS(100));
  209.   }
  210. }
  211.  
  212. void setup() {
  213.   Serial.begin(115200);
  214.  
  215.   pinMode(trigPin, OUTPUT);
  216.   pinMode(echoPin, INPUT);
  217.   pinMode(ledPin, OUTPUT);
  218.   pinMode(buzzerPin, OUTPUT);
  219.  
  220.   servo1.attach(servoPin);
  221.  
  222.   Serial.print("Connecting to ");
  223.   Serial.println(ssid);
  224.   WiFi.begin(ssid, password);
  225.   while (WiFi.status() != WL_CONNECTED) {
  226.     delay(500);
  227.     Serial.print(".");
  228.   }
  229.   Serial.println("\nWiFi connected.");
  230.  
  231.   configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
  232.   struct tm timeinfo;
  233.   int attempts = 0;
  234.   while (!getLocalTime(&timeinfo) && attempts < 5) {
  235.     Serial.println("Failed to obtain time, retrying...");
  236.     delay(2000);
  237.     attempts++;
  238.   }
  239.  
  240.   if (attempts == 5) {
  241.     Serial.println("Failed to obtain time.");
  242.   } else {
  243.     Serial.println("Time synchronized!");
  244.     printLocalTime();
  245.     Serial.println();
  246.   }
  247.  
  248.   alarmQueue = xQueueCreate(5, sizeof(bool));
  249.  
  250.   Blynk.begin(auth, ssid, password);
  251.   timer.setInterval(10000L, sendSensor);
  252.  
  253.   server.on("/receive_text", HTTP_GET, []() {
  254.     if (server.hasArg("text")) {
  255.       receivedText = server.arg("text");
  256.       Serial.print("📌 Extracted Text Received: ");
  257.       Serial.println(receivedText);
  258.       sendSensor();
  259.     }
  260.     server.send(200, "text/plain", "Text received");
  261.   });
  262.  
  263.   server.begin();
  264.   Serial.println("🔹 HTTP Server Started on ESP32");
  265.  
  266.   xTaskCreate(measureDistanceTask, "Measure Distance", 4096, NULL, 2, NULL);
  267.   xTaskCreate(alarmTask, "Alarm", 4096, NULL, 1, NULL);
  268.   xTaskCreate(controlServoTask, "Control Servo", 4096, NULL, 1, NULL);
  269. }
  270.  
  271. void loop() {
  272.   Blynk.run();
  273.   timer.run();
  274.   server.handleClient();
  275.  
  276.   if (alarm_info == 1) {
  277.     Blynk.logEvent("vehicle_detected", "Vehicle Detected! It wants to enter.");
  278.   }
  279. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement