pleasedontcode

Charli_Speaker rev_97

Dec 12th, 2025
28
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Arduino 11.57 KB | None | 0 0
  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:
  13.     - Source Code NOT compiled for: ESP32 DevKit V1
  14.     - Source Code created on: 2025-12-12 17:24:32
  15.  
  16. ********* Pleasedontcode.com **********/
  17.  
  18. /****** SYSTEM REQUIREMENTS *****/
  19. /****** SYSTEM REQUIREMENT 1 *****/
  20.     /* Configure WiFi and timezone settings with web page */
  21.     /* available via both AP and STA */
  22. /****** END SYSTEM REQUIREMENTS *****/
  23.  
  24.  
  25. /****** DEFINITION OF LIBRARIES *****/
  26. #include <Wire.h>
  27. #include <WiFi.h>
  28. #include <WebServer.h>
  29. #include <Preferences.h>
  30. #include <time.h>
  31. #include <Adafruit_SSD1306.h>   //https://github.com/stblassitude/Adafruit_SSD1306_Wemos_OLED.git
  32. #include <U8g2_for_Adafruit_GFX.h>  //https://github.com/olikraus/U8g2_for_Adafruit_GFX
  33. #include "config_web.h"
  34.  
  35. /****** FUNCTION PROTOTYPES *****/
  36. void setup(void);
  37. void loop(void);
  38. void initWiFi(void);
  39. void startAPMode(void);
  40. void startSTAMode(void);
  41. void initWebServer(void);
  42. void updateDisplay(void);
  43. void loadSettings(void);
  44. void saveSettings(void);
  45. void configureTimezone(void);
  46.  
  47. /***** DEFINITION OF DIGITAL INPUT PINS *****/
  48. const uint8_t test_PushButton_PIN_D4        = 4;
  49.  
  50. /***** DEFINITION OF DIGITAL OUTPUT PINS *****/
  51. const uint8_t relay_RelayModule_Signal_PIN_D13      = 13;
  52.  
  53. /***** DEFINITION OF I2C PINS *****/
  54. const uint8_t myDisplay_SSD1306OledDisplay_I2C_PIN_SDA_D21      = 21;
  55. const uint8_t myDisplay_SSD1306OledDisplay_I2C_PIN_SCL_D22      = 22;
  56. const uint8_t myDisplay_SSD1306OledDisplay_I2C_SLAVE_ADDRESS        = 60;
  57.  
  58. /****** DEFINITION OF LIBRARIES CLASS INSTANCES*****/
  59. // Display object with I2C address
  60. #define OLED_RESET -1
  61. Adafruit_SSD1306 display(128, 64, &Wire, OLED_RESET);
  62. U8G2_FOR_ADAFRUIT_GFX u8g2_for_adafruit_gfx;
  63.  
  64. // Web server on port 80
  65. WebServer server(80);
  66.  
  67. // Preferences for persistent storage
  68. Preferences preferences;
  69.  
  70. /****** GLOBAL VARIABLES FOR WIFI AND TIMEZONE *****/
  71. // WiFi configuration variables
  72. String wifi_ssid = "";
  73. String wifi_password = "";
  74. String ap_ssid = "ESP32-ConfigAP";
  75. String ap_password = "12345678";
  76. String timezone_str = "UTC0";
  77. int gmtOffset_sec = 0;
  78. int daylightOffset_sec = 0;
  79.  
  80. // WiFi mode tracking
  81. bool sta_mode_active = false;
  82. bool ap_mode_active = false;
  83.  
  84. // Time tracking for display updates
  85. unsigned long lastDisplayUpdate = 0;
  86. const unsigned long displayUpdateInterval = 1000; // Update display every 1 second
  87.  
  88. void setup(void)
  89. {
  90.     // Initialize serial communication
  91.     Serial.begin(115200);
  92.     Serial.println("\n\n=== ESP32 WiFi & Timezone Configuration System ===");
  93.  
  94.     // Initialize GPIO pins
  95.     pinMode(test_PushButton_PIN_D4, INPUT_PULLUP);
  96.     pinMode(relay_RelayModule_Signal_PIN_D13,    OUTPUT);
  97.     digitalWrite(relay_RelayModule_Signal_PIN_D13, LOW);
  98.  
  99.     // Initialize I2C for display
  100.     Wire.begin(myDisplay_SSD1306OledDisplay_I2C_PIN_SDA_D21, myDisplay_SSD1306OledDisplay_I2C_PIN_SCL_D22);
  101.    
  102.     // Initialize OLED display
  103.     if(!display.begin(SSD1306_SWITCHCAPVCC, myDisplay_SSD1306OledDisplay_I2C_SLAVE_ADDRESS)) {
  104.         Serial.println(F("SSD1306 allocation failed"));
  105.         // Continue anyway, some displays may work without proper init
  106.     }
  107.    
  108.     // Initialize U8g2 for Adafruit GFX
  109.     u8g2_for_adafruit_gfx.begin(display);
  110.    
  111.     // Clear display and show startup message
  112.     display.clearDisplay();
  113.     u8g2_for_adafruit_gfx.setFont(u8g2_font_6x10_tf);
  114.     u8g2_for_adafruit_gfx.setFontMode(1);
  115.     u8g2_for_adafruit_gfx.setForegroundColor(WHITE);
  116.     u8g2_for_adafruit_gfx.setCursor(0, 10);
  117.     u8g2_for_adafruit_gfx.print("Starting...");
  118.     display.display();
  119.    
  120.     // Load settings from persistent storage
  121.     loadSettings();
  122.    
  123.     // Initialize WiFi (will start AP mode if no credentials, or try STA mode)
  124.     initWiFi();
  125.    
  126.     // Initialize web server with configuration pages
  127.     initWebServer();
  128.    
  129.     // Configure timezone
  130.     configureTimezone();
  131.    
  132.     Serial.println("Setup complete!");
  133.    
  134.     // Update display with current status
  135.     updateDisplay();
  136. }
  137.  
  138. void loop(void)
  139. {
  140.     // Handle web server requests
  141.     server.handleClient();
  142.    
  143.     // Check if button is pressed (optional - could be used to toggle relay or reset settings)
  144.     if (digitalRead(test_PushButton_PIN_D4) == LOW) {
  145.         // Button pressed
  146.         digitalWrite(relay_RelayModule_Signal_PIN_D13, HIGH);
  147.     } else {
  148.         digitalWrite(relay_RelayModule_Signal_PIN_D13, LOW);
  149.     }
  150.    
  151.     // Update display periodically
  152.     if (millis() - lastDisplayUpdate >= displayUpdateInterval) {
  153.         lastDisplayUpdate = millis();
  154.         updateDisplay();
  155.     }
  156. }
  157.  
  158. /****** WIFI INITIALIZATION *****/
  159. void initWiFi(void)
  160. {
  161.     Serial.println("\n--- Initializing WiFi ---");
  162.    
  163.     // Check if we have saved WiFi credentials
  164.     if (wifi_ssid.length() > 0) {
  165.         // Try to connect to saved WiFi network (STA mode)
  166.         Serial.println("Attempting to connect to saved WiFi network...");
  167.         startSTAMode();
  168.        
  169.         // Wait up to 15 seconds for connection
  170.         int timeout = 15;
  171.         while (WiFi.status() != WL_CONNECTED && timeout > 0) {
  172.             delay(1000);
  173.             Serial.print(".");
  174.             timeout--;
  175.         }
  176.         Serial.println();
  177.        
  178.         if (WiFi.status() == WL_CONNECTED) {
  179.             sta_mode_active = true;
  180.             Serial.println("Connected to WiFi!");
  181.             Serial.print("IP Address: ");
  182.             Serial.println(WiFi.localIP());
  183.            
  184.             // Also start AP mode for configuration access
  185.             WiFi.mode(WIFI_AP_STA);
  186.             WiFi.softAP(ap_ssid.c_str(), ap_password.c_str());
  187.             ap_mode_active = true;
  188.             Serial.print("AP Mode also active. AP IP: ");
  189.             Serial.println(WiFi.softAPIP());
  190.         } else {
  191.             // Connection failed, start AP mode only
  192.             Serial.println("Failed to connect. Starting AP mode only.");
  193.             sta_mode_active = false;
  194.             startAPMode();
  195.         }
  196.     } else {
  197.         // No saved credentials, start AP mode only
  198.         Serial.println("No saved WiFi credentials. Starting AP mode.");
  199.         startAPMode();
  200.     }
  201. }
  202.  
  203. /****** START ACCESS POINT MODE *****/
  204. void startAPMode(void)
  205. {
  206.     WiFi.mode(WIFI_AP);
  207.     WiFi.softAP(ap_ssid.c_str(), ap_password.c_str());
  208.     ap_mode_active = true;
  209.     sta_mode_active = false;
  210.    
  211.     IPAddress IP = WiFi.softAPIP();
  212.     Serial.print("AP Mode started. IP address: ");
  213.     Serial.println(IP);
  214.     Serial.print("SSID: ");
  215.     Serial.println(ap_ssid);
  216.     Serial.print("Password: ");
  217.     Serial.println(ap_password);
  218. }
  219.  
  220. /****** START STATION MODE *****/
  221. void startSTAMode(void)
  222. {
  223.     WiFi.mode(WIFI_STA);
  224.     WiFi.begin(wifi_ssid.c_str(), wifi_password.c_str());
  225.     Serial.print("Connecting to: ");
  226.     Serial.println(wifi_ssid);
  227. }
  228.  
  229. /****** INITIALIZE WEB SERVER *****/
  230. void initWebServer(void)
  231. {
  232.     Serial.println("\n--- Initializing Web Server ---");
  233.    
  234.     // Root page - configuration form
  235.     server.on("/", HTTP_GET, []() {
  236.         server.send(200, "text/html", getConfigPage());
  237.     });
  238.    
  239.     // Handle WiFi configuration submission
  240.     server.on("/config", HTTP_POST, []() {
  241.         if (server.hasArg("ssid") && server.hasArg("password")) {
  242.             wifi_ssid = server.arg("ssid");
  243.             wifi_password = server.arg("password");
  244.            
  245.             if (server.hasArg("timezone")) {
  246.                 timezone_str = server.arg("timezone");
  247.                 parseTimezone(timezone_str);
  248.             }
  249.            
  250.             // Save settings to persistent storage
  251.             saveSettings();
  252.            
  253.             // Send success response
  254.             String response = getSuccessPage();
  255.             server.send(200, "text/html", response);
  256.            
  257.             // Restart WiFi with new settings after a short delay
  258.             delay(2000);
  259.             initWiFi();
  260.             configureTimezone();
  261.         } else {
  262.             server.send(400, "text/html", "<html><body><h1>Error: Missing parameters</h1></body></html>");
  263.         }
  264.     });
  265.    
  266.     // Status page - show current settings
  267.     server.on("/status", HTTP_GET, []() {
  268.         server.send(200, "text/html", getStatusPage());
  269.     });
  270.    
  271.     // Reset settings
  272.     server.on("/reset", HTTP_POST, []() {
  273.         wifi_ssid = "";
  274.         wifi_password = "";
  275.         timezone_str = "UTC0";
  276.         gmtOffset_sec = 0;
  277.         daylightOffset_sec = 0;
  278.         saveSettings();
  279.        
  280.         server.send(200, "text/html", "<html><body><h1>Settings Reset</h1><p>Device will restart in AP mode.</p><a href='/'>Back to Config</a></body></html>");
  281.        
  282.         delay(2000);
  283.         ESP.restart();
  284.     });
  285.    
  286.     // Start the server
  287.     server.begin();
  288.     Serial.println("Web server started");
  289.     Serial.println("Access configuration page at:");
  290.     if (ap_mode_active) {
  291.         Serial.print("  AP Mode: http://");
  292.         Serial.println(WiFi.softAPIP());
  293.     }
  294.     if (sta_mode_active) {
  295.         Serial.print("  STA Mode: http://");
  296.         Serial.println(WiFi.localIP());
  297.     }
  298. }
  299.  
  300. /****** UPDATE OLED DISPLAY *****/
  301. void updateDisplay(void)
  302. {
  303.     display.clearDisplay();
  304.    
  305.     // Set font and text properties
  306.     u8g2_for_adafruit_gfx.setFont(u8g2_font_6x10_tf);
  307.     u8g2_for_adafruit_gfx.setFontMode(1);
  308.     u8g2_for_adafruit_gfx.setForegroundColor(WHITE);
  309.    
  310.     int line = 10;
  311.    
  312.     // Display WiFi status
  313.     u8g2_for_adafruit_gfx.setCursor(0, line);
  314.     u8g2_for_adafruit_gfx.print("WiFi Status:");
  315.     line += 12;
  316.    
  317.     if (sta_mode_active && WiFi.status() == WL_CONNECTED) {
  318.         u8g2_for_adafruit_gfx.setCursor(0, line);
  319.         u8g2_for_adafruit_gfx.print("STA: Connected");
  320.         line += 10;
  321.        
  322.         u8g2_for_adafruit_gfx.setCursor(0, line);
  323.         String ip = WiFi.localIP().toString();
  324.         u8g2_for_adafruit_gfx.print(ip.c_str());
  325.         line += 12;
  326.     }
  327.    
  328.     if (ap_mode_active) {
  329.         u8g2_for_adafruit_gfx.setCursor(0, line);
  330.         u8g2_for_adafruit_gfx.print("AP: Active");
  331.         line += 10;
  332.        
  333.         u8g2_for_adafruit_gfx.setCursor(0, line);
  334.         String apip = WiFi.softAPIP().toString();
  335.         u8g2_for_adafruit_gfx.print(apip.c_str());
  336.         line += 12;
  337.     }
  338.    
  339.     if (!sta_mode_active && !ap_mode_active) {
  340.         u8g2_for_adafruit_gfx.setCursor(0, line);
  341.         u8g2_for_adafruit_gfx.print("Disconnected");
  342.         line += 12;
  343.     }
  344.    
  345.     // Display current time
  346.     struct tm timeinfo;
  347.     if(getLocalTime(&timeinfo)) {
  348.         char timeStr[32];
  349.         strftime(timeStr, sizeof(timeStr), "%H:%M:%S", &timeinfo);
  350.         u8g2_for_adafruit_gfx.setCursor(0, line);
  351.         u8g2_for_adafruit_gfx.print("Time: ");
  352.         u8g2_for_adafruit_gfx.print(timeStr);
  353.     }
  354.    
  355.     display.display();
  356. }
  357.  
  358. /****** LOAD SETTINGS FROM PERSISTENT STORAGE *****/
  359. void loadSettings(void)
  360. {
  361.     Serial.println("\n--- Loading Settings ---");
  362.    
  363.     preferences.begin("wifi-config", false);
  364.    
  365.     wifi_ssid = preferences.getString("ssid", "");
  366.     wifi_password = preferences.getString("password", "");
  367.     timezone_str = preferences.getString("timezone", "UTC0");
  368.     gmtOffset_sec = preferences.getInt("gmt_offset", 0);
  369.     daylightOffset_sec = preferences.getInt("dst_offset", 0);
  370.    
  371.     preferences.end();
  372.    
  373.     Serial.print("Loaded SSID: ");
  374.     Serial.println(wifi_ssid.length() > 0 ? wifi_ssid : "(none)");
  375.     Serial.print("Loaded Timezone: ");
  376.     Serial.println(timezone_str);
  377. }
  378.  
  379. /****** SAVE SETTINGS TO PERSISTENT STORAGE *****/
  380. void saveSettings(void)
  381. {
  382.     Serial.println("\n--- Saving Settings ---");
  383.    
  384.     preferences.begin("wifi-config", false);
  385.    
  386.     preferences.putString("ssid", wifi_ssid);
  387.     preferences.putString("password", wifi_password);
  388.     preferences.putString("timezone", timezone_str);
  389.     preferences.putInt("gmt_offset", gmtOffset_sec);
  390.     preferences.putInt("dst_offset", daylightOffset_sec);
  391.    
  392.     preferences.end();
  393.    
  394.     Serial.println("Settings saved successfully");
  395. }
  396.  
  397. /****** CONFIGURE TIMEZONE *****/
  398. void configureTimezone(void)
  399. {
  400.     Serial.println("\n--- Configuring Timezone ---");
  401.     Serial.print("Timezone: ");
  402.     Serial.println(timezone_str);
  403.     Serial.print("GMT Offset (sec): ");
  404.     Serial.println(gmtOffset_sec);
  405.     Serial.print("DST Offset (sec): ");
  406.     Serial.println(daylightOffset_sec);
  407.    
  408.     // Configure time with NTP
  409.     configTime(gmtOffset_sec, daylightOffset_sec, "pool.ntp.org", "time.nist.gov");
  410.    
  411.     // Wait a bit for time to sync
  412.     Serial.println("Waiting for NTP time sync...");
  413.     struct tm timeinfo;
  414.     int retry = 0;
  415.     while(!getLocalTime(&timeinfo) && retry < 10) {
  416.         delay(500);
  417.         Serial.print(".");
  418.         retry++;
  419.     }
  420.     Serial.println();
  421.    
  422.     if (retry < 10) {
  423.         Serial.println("Time synchronized successfully");
  424.     } else {
  425.         Serial.println("Failed to synchronize time");
  426.     }
  427. }
  428.  
  429. /* END CODE */
  430.  
Advertisement
Add Comment
Please, Sign In to add comment