Advertisement
Guest User

ESP32C3 Motion Sensing Lightswitch

a guest
Nov 6th, 2024
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 9.58 KB | None | 0 0
  1. #include <Arduino.h>
  2. #include <BlynkSimpleEsp32.h>
  3. #include <WiFi.h>
  4. #include <AsyncTCP.h>
  5. #include <ESPAsyncWebServer.h>
  6. #include <AsyncElegantOTA.h>
  7. #include "time.h"
  8. #include "Adafruit_VL53L1X.h"
  9.  
  10. //################################
  11. //||                            ||
  12. //||      Default settings      ||
  13. //||                            ||
  14. //################################
  15.  
  16. #define SWITCH_PIN 0
  17. #define REED_PIN 1
  18. #define RELAY_PIN 2
  19. int timeout = 120;
  20. int threshold = 900;
  21.  
  22. //################################
  23. //||                            ||
  24. //||        Declarations        ||
  25. //||                            ||
  26. //################################
  27.  
  28.  
  29. bool lightOn = false;
  30. bool readyToRead = true;
  31. bool doorLeftOpen = false;
  32. int16_t distance;
  33.  
  34. Adafruit_VL53L1X vl53 = Adafruit_VL53L1X();
  35.  
  36. const char* ssid = "xxxxxxx";
  37. const char* password = "xxxxxxxxx";
  38.  
  39. const char* ntpServer = "pool.ntp.org";
  40. const long gmtOffset_sec = -18000;  //Replace with your GMT offset (secs)
  41. const int daylightOffset_sec = 0;   //Replace with your daylight offset (secs)
  42. int hours, mins, secs;
  43. unsigned long triggerTime, debounceTime, switchTime, reconnectTime;
  44.  
  45. char auth[] = "xxxxxxxxxxxxxx";
  46.  
  47. AsyncWebServer server(80);
  48.  
  49. WidgetTerminal terminal(V10);
  50.  
  51. #define every(interval) \
  52.     static uint32_t __every__##interval = millis(); \
  53.     if (millis() - __every__##interval >= interval && (__every__##interval = millis()))
  54.  
  55. void printLocalTime() {
  56.   time_t rawtime;
  57.   struct tm* timeinfo;
  58.   time(&rawtime);
  59.   timeinfo = localtime(&rawtime);
  60.   terminal.print(" ");  
  61.   terminal.print(asctime(timeinfo));
  62.  
  63. }
  64.  
  65. //################################
  66. //||                            ||
  67. //||       Blynk controls       ||
  68. //||                            ||
  69. //################################
  70.  
  71.  
  72. BLYNK_WRITE(V10) {
  73.   if (String("help") == param.asStr()) {
  74.     terminal.println("==List of available commands:==");
  75.     terminal.println("wifi");
  76.     terminal.println("reset");
  77.     terminal.println("==End of list.==");
  78.   }
  79.   if (String("wifi") == param.asStr()) {
  80.     terminal.print("Connected to: ");
  81.     terminal.println(ssid);
  82.     terminal.print("IP address:");
  83.     terminal.println(WiFi.localIP());
  84.     terminal.print("Signal strength: ");
  85.     terminal.println(WiFi.RSSI());
  86.     printLocalTime();
  87.   }
  88.   if (String("reset") == param.asStr()) {
  89.     terminal.println("Restarting...");
  90.     terminal.flush();
  91.     ESP.restart();
  92.   }
  93.     terminal.flush();
  94. }
  95.  
  96. BLYNK_WRITE(V11)
  97. {
  98.    timeout = param.asInt(); // assigning incoming value from pin V1 to a variable
  99. }
  100.  
  101. BLYNK_WRITE(V12)
  102. {
  103.    threshold = param.asInt(); // assigning incoming value from pin V1 to a variable
  104. }
  105.  
  106. BLYNK_WRITE(V14)
  107. {
  108.   if ((param.asInt() == 1) && (lightOn == false) && (readyToRead) && (millis() - debounceTime > 100)) {
  109.       lightOn = true;
  110.       digitalWrite(RELAY_PIN, HIGH);
  111.      
  112.       terminal.print("App turned light ON");
  113.        printLocalTime();
  114.       terminal.flush();
  115.       debounceTime = millis();
  116.       triggerTime = millis();
  117.       readyToRead = false;
  118.   }
  119.  
  120.   if ((param.asInt() == 0) && (lightOn == true) && (readyToRead) && (millis() - debounceTime > 100)) {
  121.       lightOn = false;
  122.       debounceTime = millis();
  123.       digitalWrite(RELAY_PIN, LOW);
  124.      
  125.       terminal.print("App turned light OFF");
  126.       printLocalTime();
  127.       terminal.flush();
  128.       readyToRead = false;
  129.   }
  130. }
  131.  
  132. BLYNK_CONNECTED() {
  133.   Blynk.syncVirtual(V11);
  134.   Blynk.syncVirtual(V12);
  135. }
  136.  
  137. //################################
  138. //||                            ||
  139. //||         MAIN SETUP         ||
  140. //||   (run this on startup)    ||
  141. //||                            ||
  142. //################################
  143.  
  144.  
  145. void setup(void) {
  146.   pinMode(SWITCH_PIN, INPUT_PULLUP);
  147.   pinMode(REED_PIN, INPUT_PULLUP);
  148.   pinMode(RELAY_PIN, OUTPUT);
  149.   digitalWrite(RELAY_PIN, LOW);
  150.   pinMode(8, OUTPUT);
  151.   Serial.begin(9600);
  152.   delay(1000);
  153.   WiFi.mode(WIFI_STA);
  154.   WiFi.begin(ssid, password);
  155.   WiFi.setTxPower(WIFI_POWER_8_5dBm);
  156.   Serial.println("");
  157.  
  158.   // Wait for connection
  159.   while (WiFi.status() != WL_CONNECTED) {
  160.     delay(250);
  161.     digitalWrite(8, HIGH);
  162.     delay(250);
  163.     digitalWrite(8, LOW);
  164.     Serial.print(".");
  165.   }
  166.   Serial.println("");
  167.   Serial.print("Connected to ");
  168.   Serial.println(ssid);
  169.   Serial.print("IP address: ");
  170.   Serial.println(WiFi.localIP());
  171.  
  172.   server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
  173.     request->send(200, "text/plain", "Hi! I am ESP32.");
  174.   });
  175.  
  176.   AsyncElegantOTA.begin(&server);    // Start ElegantOTA
  177.   server.begin();
  178.   Serial.println("HTTP server started");
  179.   delay(250);
  180.   configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
  181.   Blynk.config(auth, IPAddress(192, 168, 50, 197), 8080);
  182.   Blynk.connect();
  183.   delay(250);
  184.   struct tm timeinfo;
  185.   getLocalTime(&timeinfo);
  186.   hours = timeinfo.tm_hour;
  187.   mins = timeinfo.tm_min;
  188.   secs = timeinfo.tm_sec;
  189.   terminal.println("***SERVER STARTED***");
  190.   terminal.print("Connected to ");
  191.   terminal.println(ssid);
  192.   terminal.print("IP address: ");
  193.   terminal.println(WiFi.localIP());
  194.   printLocalTime();
  195.  
  196.   Wire.begin();
  197.   if (! vl53.begin(0x29, &Wire)) {
  198.     //terminal.print(F("Error on init of VL sensor: "));
  199.     //terminal.println(vl53.vl_status);
  200.     while (1)       delay(10);
  201.   }
  202.   terminal.println(F("VL53L1X sensor OK!"));
  203.  
  204.   terminal.print(F("Sensor ID: 0x"));
  205.   terminal.println(vl53.sensorID(), HEX);
  206.  
  207.   if (! vl53.startRanging()) {
  208.     terminal.print(F("Couldn't start ranging: "));
  209.     terminal.println(vl53.vl_status);
  210.     while (1)       delay(10);
  211.   }
  212.   terminal.println(F("Ranging started"));
  213.  
  214.   // Valid timing budgets: 15, 20, 33, 50, 100, 200 and 500ms!
  215.   vl53.setTimingBudget(50);
  216.   terminal.print(F("Timing budget (ms): "));
  217.  terminal.println(vl53.getTimingBudget());
  218.  
  219.   terminal.flush();
  220. }
  221.  
  222. //################################
  223. //||                            ||
  224. //||         MAIN LOOP          ||
  225. //||     (run this forever)     ||
  226. //||                            ||
  227. //################################
  228.  
  229.  
  230. void loop() {
  231.  
  232.   if (vl53.dataReady()) { //IF laser sensor is ready to give new reading
  233.     distance = vl53.distance(); //update the reading
  234.     vl53.clearInterrupt();
  235.     if (( (distance < threshold)) && (lightOn == false) && (millis() - switchTime > (timeout*1000))) { //if the distance is a real number, less than  the threshold, lights are off, and the switch wasn't recently pressed
  236.       lightOn = true;
  237.       digitalWrite(RELAY_PIN, HIGH); //turn the lights ON
  238.       Blynk.virtualWrite(V14, HIGH);      //send the same to Blynk
  239.       terminal.print("Triggered by motion"); //write it on the terminal
  240.       printLocalTime();
  241.       terminal.flush();
  242.       triggerTime = millis(); //update the time at which this all happened
  243.     }
  244.   }
  245.  
  246.  
  247.   if ((digitalRead(SWITCH_PIN)) && (lightOn == true) && (readyToRead) && (millis() - debounceTime > 100)) { //if the switch was pressed, the lights are ON, the switch isn't being held, and the switch hasn't bounced
  248.       lightOn = false;
  249.       debounceTime = millis();
  250.       switchTime = debounceTime;
  251.       digitalWrite(RELAY_PIN, LOW);  //turn the lights OFF
  252.       Blynk.virtualWrite(V14, LOW);
  253.       terminal.print("Switch turned light OFF");
  254.       printLocalTime();
  255.       terminal.flush();
  256.       readyToRead = false; //the switch is being held
  257.   }
  258.  
  259.   if ((digitalRead(SWITCH_PIN)) && (lightOn == false) && (readyToRead) && (millis() - debounceTime > 100)) { //if the switch was pressed, the lights are OFF, and the switch hasn't bounced
  260.       lightOn = true;
  261.       digitalWrite(RELAY_PIN, HIGH);  //turn the lights ON
  262.       Blynk.virtualWrite(V14, HIGH);      
  263.       terminal.print("Switch turned light ON");
  264.        printLocalTime();
  265.       terminal.flush();
  266.       debounceTime = millis();
  267.       triggerTime = millis();
  268.       readyToRead = false; //the switch is being held
  269.   }
  270.  
  271.   if (!digitalRead(SWITCH_PIN) && (!readyToRead)) {  //if the switch has been let go after holding it down
  272.     readyToRead = true;  //we area ready to read anotehr switch press
  273.   }
  274.  
  275.  
  276.  
  277.   if ((digitalRead(REED_PIN)) && (lightOn == false) && (readyToRead) && (!doorLeftOpen) && (millis() - debounceTime > 100)) { //if the door is opened, the lights are off, the switch isn't being held, the door hasn't been left open, and the reed switch hasn't bounced
  278.       lightOn = true;
  279.       digitalWrite(RELAY_PIN, HIGH); //turn the lights ON
  280.       Blynk.virtualWrite(V14, HIGH);      
  281.       terminal.print("Door opened.");
  282.       printLocalTime();
  283.       terminal.flush();
  284.       debounceTime = millis();
  285.       triggerTime = millis();
  286.       readyToRead = false;
  287.   }
  288.  
  289.  
  290.   if ((millis() - triggerTime > (timeout * 1000)) && (lightOn) && (!digitalRead(REED_PIN)) && (distance > threshold)) { //if the lights have been on longer than the timeout and nobody is standing in front of the laser sensor
  291.       lightOn = false;
  292.      
  293.       terminal.print("Light timed out");
  294.       printLocalTime();
  295.       terminal.flush();
  296.       digitalWrite(RELAY_PIN, LOW); //turn the lights OFF
  297.       Blynk.virtualWrite(V14, LOW);
  298.  
  299.   }
  300.  
  301.  
  302.  
  303.  
  304.       if (WiFi.status() == WL_CONNECTED) {Blynk.run();}  //don't do Blynk unless wifi
  305.       else { //if no wifi, try to reconnect
  306.         if (millis() - reconnectTime > 30000) {
  307.               Serial.print(millis());
  308.               WiFi.disconnect();
  309.               WiFi.reconnect();
  310.               reconnectTime = millis();
  311.         }
  312.  
  313.       }
  314.  
  315.       every(60000){ //update Blynk every minute
  316.       Blynk.virtualWrite(V1, distance);
  317.       Blynk.virtualWrite(V2, WiFi.RSSI());
  318.       Blynk.virtualWrite(V3, temperatureRead());
  319.       }
  320.  
  321.  
  322. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement