Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /********* Pleasedontcode.com **********
- Pleasedontcode thanks you for automatic code generation! Enjoy your code!
- - Terms and Conditions:
- You have a non-exclusive, revocable, worldwide, royalty-free license
- for personal and commercial use. Attribution is optional; modifications
- are allowed, but you're responsible for code maintenance. We're not
- liable for any loss or damage. For full terms,
- please visit pleasedontcode.com/termsandconditions.
- - Project:
- - Source Code NOT compiled for: ESP32 DevKit V1
- - Source Code created on: 2025-12-12 17:24:32
- ********* Pleasedontcode.com **********/
- /****** SYSTEM REQUIREMENTS *****/
- /****** SYSTEM REQUIREMENT 1 *****/
- /* Configure WiFi and timezone settings with web page */
- /* available via both AP and STA */
- /****** END SYSTEM REQUIREMENTS *****/
- /****** DEFINITION OF LIBRARIES *****/
- #include <Wire.h>
- #include <WiFi.h>
- #include <WebServer.h>
- #include <Preferences.h>
- #include <time.h>
- #include <Adafruit_SSD1306.h> //https://github.com/stblassitude/Adafruit_SSD1306_Wemos_OLED.git
- #include <U8g2_for_Adafruit_GFX.h> //https://github.com/olikraus/U8g2_for_Adafruit_GFX
- #include "config_web.h"
- /****** FUNCTION PROTOTYPES *****/
- void setup(void);
- void loop(void);
- void initWiFi(void);
- void startAPMode(void);
- void startSTAMode(void);
- void initWebServer(void);
- void updateDisplay(void);
- void loadSettings(void);
- void saveSettings(void);
- void configureTimezone(void);
- /***** DEFINITION OF DIGITAL INPUT PINS *****/
- const uint8_t test_PushButton_PIN_D4 = 4;
- /***** DEFINITION OF DIGITAL OUTPUT PINS *****/
- const uint8_t relay_RelayModule_Signal_PIN_D13 = 13;
- /***** DEFINITION OF I2C PINS *****/
- const uint8_t myDisplay_SSD1306OledDisplay_I2C_PIN_SDA_D21 = 21;
- const uint8_t myDisplay_SSD1306OledDisplay_I2C_PIN_SCL_D22 = 22;
- const uint8_t myDisplay_SSD1306OledDisplay_I2C_SLAVE_ADDRESS = 60;
- /****** DEFINITION OF LIBRARIES CLASS INSTANCES*****/
- // Display object with I2C address
- #define OLED_RESET -1
- Adafruit_SSD1306 display(128, 64, &Wire, OLED_RESET);
- U8G2_FOR_ADAFRUIT_GFX u8g2_for_adafruit_gfx;
- // Web server on port 80
- WebServer server(80);
- // Preferences for persistent storage
- Preferences preferences;
- /****** GLOBAL VARIABLES FOR WIFI AND TIMEZONE *****/
- // WiFi configuration variables
- String wifi_ssid = "";
- String wifi_password = "";
- String ap_ssid = "ESP32-ConfigAP";
- String ap_password = "12345678";
- String timezone_str = "UTC0";
- int gmtOffset_sec = 0;
- int daylightOffset_sec = 0;
- // WiFi mode tracking
- bool sta_mode_active = false;
- bool ap_mode_active = false;
- // Time tracking for display updates
- unsigned long lastDisplayUpdate = 0;
- const unsigned long displayUpdateInterval = 1000; // Update display every 1 second
- void setup(void)
- {
- // Initialize serial communication
- Serial.begin(115200);
- Serial.println("\n\n=== ESP32 WiFi & Timezone Configuration System ===");
- // Initialize GPIO pins
- pinMode(test_PushButton_PIN_D4, INPUT_PULLUP);
- pinMode(relay_RelayModule_Signal_PIN_D13, OUTPUT);
- digitalWrite(relay_RelayModule_Signal_PIN_D13, LOW);
- // Initialize I2C for display
- Wire.begin(myDisplay_SSD1306OledDisplay_I2C_PIN_SDA_D21, myDisplay_SSD1306OledDisplay_I2C_PIN_SCL_D22);
- // Initialize OLED display
- if(!display.begin(SSD1306_SWITCHCAPVCC, myDisplay_SSD1306OledDisplay_I2C_SLAVE_ADDRESS)) {
- Serial.println(F("SSD1306 allocation failed"));
- // Continue anyway, some displays may work without proper init
- }
- // Initialize U8g2 for Adafruit GFX
- u8g2_for_adafruit_gfx.begin(display);
- // Clear display and show startup message
- display.clearDisplay();
- u8g2_for_adafruit_gfx.setFont(u8g2_font_6x10_tf);
- u8g2_for_adafruit_gfx.setFontMode(1);
- u8g2_for_adafruit_gfx.setForegroundColor(WHITE);
- u8g2_for_adafruit_gfx.setCursor(0, 10);
- u8g2_for_adafruit_gfx.print("Starting...");
- display.display();
- // Load settings from persistent storage
- loadSettings();
- // Initialize WiFi (will start AP mode if no credentials, or try STA mode)
- initWiFi();
- // Initialize web server with configuration pages
- initWebServer();
- // Configure timezone
- configureTimezone();
- Serial.println("Setup complete!");
- // Update display with current status
- updateDisplay();
- }
- void loop(void)
- {
- // Handle web server requests
- server.handleClient();
- // Check if button is pressed (optional - could be used to toggle relay or reset settings)
- if (digitalRead(test_PushButton_PIN_D4) == LOW) {
- // Button pressed
- digitalWrite(relay_RelayModule_Signal_PIN_D13, HIGH);
- } else {
- digitalWrite(relay_RelayModule_Signal_PIN_D13, LOW);
- }
- // Update display periodically
- if (millis() - lastDisplayUpdate >= displayUpdateInterval) {
- lastDisplayUpdate = millis();
- updateDisplay();
- }
- }
- /****** WIFI INITIALIZATION *****/
- void initWiFi(void)
- {
- Serial.println("\n--- Initializing WiFi ---");
- // Check if we have saved WiFi credentials
- if (wifi_ssid.length() > 0) {
- // Try to connect to saved WiFi network (STA mode)
- Serial.println("Attempting to connect to saved WiFi network...");
- startSTAMode();
- // Wait up to 15 seconds for connection
- int timeout = 15;
- while (WiFi.status() != WL_CONNECTED && timeout > 0) {
- delay(1000);
- Serial.print(".");
- timeout--;
- }
- Serial.println();
- if (WiFi.status() == WL_CONNECTED) {
- sta_mode_active = true;
- Serial.println("Connected to WiFi!");
- Serial.print("IP Address: ");
- Serial.println(WiFi.localIP());
- // Also start AP mode for configuration access
- WiFi.mode(WIFI_AP_STA);
- WiFi.softAP(ap_ssid.c_str(), ap_password.c_str());
- ap_mode_active = true;
- Serial.print("AP Mode also active. AP IP: ");
- Serial.println(WiFi.softAPIP());
- } else {
- // Connection failed, start AP mode only
- Serial.println("Failed to connect. Starting AP mode only.");
- sta_mode_active = false;
- startAPMode();
- }
- } else {
- // No saved credentials, start AP mode only
- Serial.println("No saved WiFi credentials. Starting AP mode.");
- startAPMode();
- }
- }
- /****** START ACCESS POINT MODE *****/
- void startAPMode(void)
- {
- WiFi.mode(WIFI_AP);
- WiFi.softAP(ap_ssid.c_str(), ap_password.c_str());
- ap_mode_active = true;
- sta_mode_active = false;
- IPAddress IP = WiFi.softAPIP();
- Serial.print("AP Mode started. IP address: ");
- Serial.println(IP);
- Serial.print("SSID: ");
- Serial.println(ap_ssid);
- Serial.print("Password: ");
- Serial.println(ap_password);
- }
- /****** START STATION MODE *****/
- void startSTAMode(void)
- {
- WiFi.mode(WIFI_STA);
- WiFi.begin(wifi_ssid.c_str(), wifi_password.c_str());
- Serial.print("Connecting to: ");
- Serial.println(wifi_ssid);
- }
- /****** INITIALIZE WEB SERVER *****/
- void initWebServer(void)
- {
- Serial.println("\n--- Initializing Web Server ---");
- // Root page - configuration form
- server.on("/", HTTP_GET, []() {
- server.send(200, "text/html", getConfigPage());
- });
- // Handle WiFi configuration submission
- server.on("/config", HTTP_POST, []() {
- if (server.hasArg("ssid") && server.hasArg("password")) {
- wifi_ssid = server.arg("ssid");
- wifi_password = server.arg("password");
- if (server.hasArg("timezone")) {
- timezone_str = server.arg("timezone");
- parseTimezone(timezone_str);
- }
- // Save settings to persistent storage
- saveSettings();
- // Send success response
- String response = getSuccessPage();
- server.send(200, "text/html", response);
- // Restart WiFi with new settings after a short delay
- delay(2000);
- initWiFi();
- configureTimezone();
- } else {
- server.send(400, "text/html", "<html><body><h1>Error: Missing parameters</h1></body></html>");
- }
- });
- // Status page - show current settings
- server.on("/status", HTTP_GET, []() {
- server.send(200, "text/html", getStatusPage());
- });
- // Reset settings
- server.on("/reset", HTTP_POST, []() {
- wifi_ssid = "";
- wifi_password = "";
- timezone_str = "UTC0";
- gmtOffset_sec = 0;
- daylightOffset_sec = 0;
- saveSettings();
- 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>");
- delay(2000);
- ESP.restart();
- });
- // Start the server
- server.begin();
- Serial.println("Web server started");
- Serial.println("Access configuration page at:");
- if (ap_mode_active) {
- Serial.print(" AP Mode: http://");
- Serial.println(WiFi.softAPIP());
- }
- if (sta_mode_active) {
- Serial.print(" STA Mode: http://");
- Serial.println(WiFi.localIP());
- }
- }
- /****** UPDATE OLED DISPLAY *****/
- void updateDisplay(void)
- {
- display.clearDisplay();
- // Set font and text properties
- u8g2_for_adafruit_gfx.setFont(u8g2_font_6x10_tf);
- u8g2_for_adafruit_gfx.setFontMode(1);
- u8g2_for_adafruit_gfx.setForegroundColor(WHITE);
- int line = 10;
- // Display WiFi status
- u8g2_for_adafruit_gfx.setCursor(0, line);
- u8g2_for_adafruit_gfx.print("WiFi Status:");
- line += 12;
- if (sta_mode_active && WiFi.status() == WL_CONNECTED) {
- u8g2_for_adafruit_gfx.setCursor(0, line);
- u8g2_for_adafruit_gfx.print("STA: Connected");
- line += 10;
- u8g2_for_adafruit_gfx.setCursor(0, line);
- String ip = WiFi.localIP().toString();
- u8g2_for_adafruit_gfx.print(ip.c_str());
- line += 12;
- }
- if (ap_mode_active) {
- u8g2_for_adafruit_gfx.setCursor(0, line);
- u8g2_for_adafruit_gfx.print("AP: Active");
- line += 10;
- u8g2_for_adafruit_gfx.setCursor(0, line);
- String apip = WiFi.softAPIP().toString();
- u8g2_for_adafruit_gfx.print(apip.c_str());
- line += 12;
- }
- if (!sta_mode_active && !ap_mode_active) {
- u8g2_for_adafruit_gfx.setCursor(0, line);
- u8g2_for_adafruit_gfx.print("Disconnected");
- line += 12;
- }
- // Display current time
- struct tm timeinfo;
- if(getLocalTime(&timeinfo)) {
- char timeStr[32];
- strftime(timeStr, sizeof(timeStr), "%H:%M:%S", &timeinfo);
- u8g2_for_adafruit_gfx.setCursor(0, line);
- u8g2_for_adafruit_gfx.print("Time: ");
- u8g2_for_adafruit_gfx.print(timeStr);
- }
- display.display();
- }
- /****** LOAD SETTINGS FROM PERSISTENT STORAGE *****/
- void loadSettings(void)
- {
- Serial.println("\n--- Loading Settings ---");
- preferences.begin("wifi-config", false);
- wifi_ssid = preferences.getString("ssid", "");
- wifi_password = preferences.getString("password", "");
- timezone_str = preferences.getString("timezone", "UTC0");
- gmtOffset_sec = preferences.getInt("gmt_offset", 0);
- daylightOffset_sec = preferences.getInt("dst_offset", 0);
- preferences.end();
- Serial.print("Loaded SSID: ");
- Serial.println(wifi_ssid.length() > 0 ? wifi_ssid : "(none)");
- Serial.print("Loaded Timezone: ");
- Serial.println(timezone_str);
- }
- /****** SAVE SETTINGS TO PERSISTENT STORAGE *****/
- void saveSettings(void)
- {
- Serial.println("\n--- Saving Settings ---");
- preferences.begin("wifi-config", false);
- preferences.putString("ssid", wifi_ssid);
- preferences.putString("password", wifi_password);
- preferences.putString("timezone", timezone_str);
- preferences.putInt("gmt_offset", gmtOffset_sec);
- preferences.putInt("dst_offset", daylightOffset_sec);
- preferences.end();
- Serial.println("Settings saved successfully");
- }
- /****** CONFIGURE TIMEZONE *****/
- void configureTimezone(void)
- {
- Serial.println("\n--- Configuring Timezone ---");
- Serial.print("Timezone: ");
- Serial.println(timezone_str);
- Serial.print("GMT Offset (sec): ");
- Serial.println(gmtOffset_sec);
- Serial.print("DST Offset (sec): ");
- Serial.println(daylightOffset_sec);
- // Configure time with NTP
- configTime(gmtOffset_sec, daylightOffset_sec, "pool.ntp.org", "time.nist.gov");
- // Wait a bit for time to sync
- Serial.println("Waiting for NTP time sync...");
- struct tm timeinfo;
- int retry = 0;
- while(!getLocalTime(&timeinfo) && retry < 10) {
- delay(500);
- Serial.print(".");
- retry++;
- }
- Serial.println();
- if (retry < 10) {
- Serial.println("Time synchronized successfully");
- } else {
- Serial.println("Failed to synchronize time");
- }
- }
- /* END CODE */
Advertisement
Add Comment
Please, Sign In to add comment