Advertisement
pleasedontcode

"ESP32 Automation" rev_01

Jul 16th, 2024
787
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /********* Pleasedontcode.com **********
  2.  
  3.     Pleasedontcode thanks you for automatic code generation! Enjoy your code!
  4.  
  5.     - Terms and Conditions:
  6.     You have a non-exclusive, revocable, worldwide, royalty-free license
  7.     for personal and commercial use. Attribution is optional; modifications
  8.     are allowed, but you're responsible for code maintenance. We're not
  9.     liable for any loss or damage. For full terms,
  10.     please visit pleasedontcode.com/termsandconditions.
  11.  
  12.     - Project: "ESP32 Automation"
  13.     - Source Code NOT compiled for: ESP32 DevKit V1
  14.     - Source Code created on: 2024-07-17 00:16:29
  15.  
  16. ********* Pleasedontcode.com **********/
  17.  
  18. /****** SYSTEM REQUIREMENTS *****/
  19. /****** SYSTEM REQUIREMENT 1 *****/
  20.     /* create a web server for setting sid and password */
  21.     /* and showing time on rtc  once esp32 has wifi */
  22.     /* connection update rtc from nst.  tun on relay1 */
  23.     /* every second and relay2 every 30 seconds using */
  24.     /* time from rtc */
  25. /****** END SYSTEM REQUIREMENTS *****/
  26.  
  27. /****** DEFINITION OF LIBRARIES *****/
  28. #include <Wire.h>
  29. #include <DS3231.h>  //https://github.com/NorthernWidget/DS3231
  30. #include <WiFiManager.h>  //https://github.com/tzapu/WiFiManager.git
  31. #include <FS.h>
  32. #include <ArduinoJson.h>
  33. #include <WiFi.h>
  34. #include <WebServer.h>
  35. #include <NTPClient.h>
  36. #include <WiFiUdp.h>
  37.  
  38. #ifdef ESP32
  39.   #include <SPIFFS.h>
  40. #endif
  41.  
  42. /****** FUNCTION PROTOTYPES *****/
  43. void setup(void);
  44. void loop(void);
  45. void updateOutputs(void);
  46. void saveConfigCallback(void);
  47. void isr_TickTock(void);
  48. void handleRoot(void);
  49. void handleNotFound(void);
  50. void updateRTCFromNTP(void);
  51.  
  52. /***** DEFINITION OF DIGITAL OUTPUT PINS *****/
  53. const uint8_t relay1_RelayModule_Signal_PIN_D4 = 4;
  54. const uint8_t relay2_RelayModule_Signal_PIN_D13 = 13;
  55.  
  56. /***** DEFINITION OF I2C PINS *****/
  57. const uint8_t rtc_DS3231_I2C_PIN_SDA_D21 = 21;
  58. const uint8_t rtc_DS3231_I2C_PIN_SCL_D22 = 22;
  59. const uint8_t rtc_DS3231_I2C_SLAVE_ADDRESS = 104;
  60.  
  61. /***** DEFINITION OF OUTPUT RAW VARIABLES *****/
  62. /***** used to store raw data *****/
  63. bool relay1_RelayModule_Signal_PIN_D4_rawData = 0;
  64. bool relay2_RelayModule_Signal_PIN_D13_rawData = 0;
  65.  
  66. /***** DEFINITION OF OUTPUT PHYSICAL VARIABLES *****/
  67. /***** used to store data after characteristic curve transformation *****/
  68. float relay1_RelayModule_Signal_PIN_D4_phyData = 0.0;
  69. float relay2_RelayModule_Signal_PIN_D13_phyData = 0.0;
  70.  
  71. /****** DEFINITION OF LIBRARIES CLASS INSTANCES*****/
  72. DS3231 myRTC;  // Initialize DS3231 object
  73. WiFiManager wifiManager;  // Initialize WiFiManager object
  74. WebServer server(80);  // Initialize WebServer on port 80
  75. WiFiUDP ntpUDP;  // Initialize WiFiUDP object
  76. NTPClient timeClient(ntpUDP, "pool.ntp.org", 0, 60000);  // Initialize NTPClient to get time from NTP server
  77.  
  78. /****** WiFiManager Custom Parameters *****/
  79. char mqtt_server[40];
  80. char mqtt_port[6] = "8080";
  81. char api_token[34] = "YOUR_API_TOKEN";
  82. bool shouldSaveConfig = false;
  83.  
  84. /****** WiFiManager Custom Parameters Instances *****/
  85. WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, 40);
  86. WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 6);
  87. WiFiManagerParameter custom_api_token("apikey", "API token", api_token, 32);
  88.  
  89. void saveConfigCallback() {
  90.   Serial.println("Should save config");
  91.   shouldSaveConfig = true;
  92. }
  93.  
  94. void setup(void) {
  95.   // Initialize I2C communication
  96.   Wire.begin(rtc_DS3231_I2C_PIN_SDA_D21, rtc_DS3231_I2C_PIN_SCL_D22);
  97.  
  98.   // Initialize Serial communication for debugging
  99.   Serial.begin(9600);
  100.   while (!Serial);
  101.  
  102.   // Print initialization message
  103.   Serial.println("Starting Serial");
  104.  
  105.   // Initialize relay pins as outputs
  106.   pinMode(relay1_RelayModule_Signal_PIN_D4, OUTPUT);
  107.   pinMode(relay2_RelayModule_Signal_PIN_D13, OUTPUT);
  108.  
  109.   // Set Alarm 1 to fire every second
  110.   myRTC.turnOffAlarm(1);
  111.   myRTC.setA1Time(0, 0, 0, 0, 0b00001111, false, false, false);
  112.   myRTC.turnOnAlarm(1);
  113.   myRTC.checkIfAlarm(1);
  114.  
  115.   // Prevent Alarm 2 from interfering
  116.   myRTC.setA2Time(0, 0, 0xFF, 0b01100000, false, false, false);
  117.   myRTC.turnOffAlarm(2);
  118.   myRTC.checkIfAlarm(2);
  119.  
  120.   // Attach clock interrupt
  121.   pinMode(2, INPUT_PULLUP);  // Assuming interrupt pin is GPIO 2
  122.   attachInterrupt(digitalPinToInterrupt(2), isr_TickTock, FALLING);
  123.  
  124.   // Use built-in LED to blink
  125.   pinMode(LED_BUILTIN, OUTPUT);
  126.  
  127.   // Initialize SPIFFS
  128.   if (SPIFFS.begin()) {
  129.     if (SPIFFS.exists("/config.json")) {
  130.       File configFile = SPIFFS.open("/config.json", "r");
  131.       if (configFile) {
  132.         size_t size = configFile.size();
  133.         std::unique_ptr<char[]> buf(new char[size]);
  134.         configFile.readBytes(buf.get(), size);
  135.         DynamicJsonDocument json(1024);
  136.         if (!deserializeJson(json, buf.get())) {
  137.           strcpy(mqtt_server, json["mqtt_server"]);
  138.           strcpy(mqtt_port, json["mqtt_port"]);
  139.           strcpy(api_token, json["api_token"]);
  140.         }
  141.         configFile.close();
  142.       }
  143.     }
  144.   }
  145.  
  146.   // Set WiFiManager custom parameters
  147.   wifiManager.setSaveConfigCallback(saveConfigCallback);
  148.   wifiManager.addParameter(&custom_mqtt_server);
  149.   wifiManager.addParameter(&custom_mqtt_port);
  150.   wifiManager.addParameter(&custom_api_token);
  151.  
  152.   // Attempt to connect to WiFi
  153.   if (!wifiManager.autoConnect("AutoConnectAP", "password")) {
  154.     Serial.println("Failed to connect and hit timeout");
  155.     ESP.restart();
  156.   }
  157.  
  158.   Serial.println("Connected to WiFi");
  159.  
  160.   // Save custom parameters
  161.   strcpy(mqtt_server, custom_mqtt_server.getValue());
  162.   strcpy(mqtt_port, custom_mqtt_port.getValue());
  163.   strcpy(api_token, custom_api_token.getValue());
  164.  
  165.   if (shouldSaveConfig) {
  166.     DynamicJsonDocument json(1024);
  167.     json["mqtt_server"] = mqtt_server;
  168.     json["mqtt_port"] = mqtt_port;
  169.     json["api_token"] = api_token;
  170.  
  171.     File configFile = SPIFFS.open("/config.json", "w");
  172.     if (configFile) {
  173.       serializeJson(json, configFile);
  174.       configFile.close();
  175.     }
  176.   }
  177.  
  178.   Serial.println("Local IP: " + WiFi.localIP().toString());
  179.  
  180.   // Initialize web server routes
  181.   server.on("/", handleRoot);
  182.   server.onNotFound(handleNotFound);
  183.   server.begin();
  184.  
  185.   // Initialize NTP client
  186.   timeClient.begin();
  187. }
  188.  
  189. void loop(void) {
  190.   // Handle web server
  191.   server.handleClient();
  192.  
  193.   // Update NTP client
  194.   timeClient.update();
  195.  
  196.   // Update RTC from NTP if not already updated
  197.   static bool rtcUpdated = false;
  198.   if (!rtcUpdated && WiFi.status() == WL_CONNECTED) {
  199.     updateRTCFromNTP();
  200.     rtcUpdated = true;
  201.   }
  202.  
  203.   updateOutputs();  // Refresh output data
  204.  
  205.   static byte state = false;
  206.   static volatile byte tick = 1;
  207.  
  208.   // If alarm went off, toggle LED
  209.   if (tick) {
  210.     tick = 0;
  211.     state = !state;
  212.     digitalWrite(LED_BUILTIN, state);
  213.  
  214.     // Optional serial output
  215.     Serial.print("Turning LED ");
  216.     Serial.println(state ? "ON" : "OFF");
  217.  
  218.     // Clear Alarm 1 flag
  219.     myRTC.checkIfAlarm(1);
  220.   }
  221.  
  222.   // Loop delay to emulate other running code
  223.   delay(10);
  224. }
  225.  
  226. void updateOutputs() {
  227.   // Get current time from RTC
  228.   DateTime now = myRTC.getDateTime();
  229.  
  230.   // Turn on relay1 every second
  231.   relay1_RelayModule_Signal_PIN_D4_rawData = (now.second % 2 == 0);
  232.  
  233.   // Turn on relay2 every 30 seconds
  234.   relay2_RelayModule_Signal_PIN_D13_rawData = (now.second % 30 == 0);
  235.  
  236.   // Update relay states
  237.   digitalWrite(relay1_RelayModule_Signal_PIN_D4, relay1_RelayModule_Signal_PIN_D4_rawData);
  238.   digitalWrite(relay2_RelayModule_Signal_PIN_D13, relay2_RelayModule_Signal_PIN_D13_rawData);
  239. }
  240.  
  241. void isr_TickTock() {
  242.   // Interrupt signals to loop
  243.   static volatile byte tick = 1;
  244. }
  245.  
  246. void handleRoot() {
  247.   String html = "<html><body><h1>ESP32 Web Server</h1>";
  248.   html += "<p>Current Time: " + myRTC.getDateTime().toString() + "</p>";
  249.   html += "<form action='/update' method='POST'>";
  250.   html += "SSID: <input type='text' name='ssid'><br>";
  251.   html += "Password: <input type='password' name='password'><br>";
  252.   html += "<input type='submit' value='Update WiFi'>";
  253.   html += "</form></body></html>";
  254.   server.send(200, "text/html", html);
  255. }
  256.  
  257. void handleNotFound() {
  258.   server.send(404, "text/plain", "404: Not found");
  259. }
  260.  
  261. void updateRTCFromNTP() {
  262.   // Get time from NTP
  263.   time_t epochTime = timeClient.getEpochTime();
  264.   struct tm *ptm = gmtime(&epochTime);
  265.  
  266.   // Update RTC with NTP time
  267.   myRTC.setDateTime(ptm->tm_year + 1900, ptm->tm_mon + 1, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
  268.  
  269.   Serial.println("RTC updated from NTP");
  270. }
  271.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement