pleasedontcode

# ESP32 Dashboard rev_02

Mar 14th, 2026
24
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Arduino 11.35 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: # ESP32 Dashboard
  13.     - Version: 002
  14.     - Source Code NOT compiled for: ESP32 DevKit V1
  15.     - Source Code created on: 2026-03-14 23:03:27
  16.  
  17. ********* Pleasedontcode.com **********/
  18.  
  19. /****** SYSTEM REQUIREMENTS *****/
  20. /****** SYSTEM REQUIREMENT 1 *****/
  21.     /* Initialize SSD1306 OLED display and display "Hello */
  22.     /* World" text on screen with clear and refresh */
  23.     /* updates */
  24. /****** SYSTEM REQUIREMENT 2 *****/
  25.     /* [POTA] Include POTA.h and secrets.h. Init POTA in */
  26.     /* setup() with WiFi creds from secrets.h. Call */
  27.     /* pota.loop() in loop(). */
  28. /****** SYSTEM REQUIREMENT 3 *****/
  29.     /* [POTA] MANDATORY OTA: call */
  30.     /* pota.checkAndPerformOTA() in setup() after */
  31.     /* begin(). Register pota.onOTAAvailable(cb) where cb */
  32.     /* sets a bool flag. In loop() when flag is true call */
  33.     /* pota.restart(). Without OTA the device cannot */
  34.     /* update remotely. */
  35. /****** END SYSTEM REQUIREMENTS *****/
  36.  
  37.  
  38. /* START CODE */
  39.  
  40. /****** DEFINITION OF LIBRARIES *****/
  41. #include <Wire.h>
  42. #include <Adafruit_SSD1306.h>   //https://github.com/adafruit/Adafruit_SSD1306
  43. #include <Adafruit_GFX.h>   //https://github.com/adafruit/Adafruit-GFX-Library
  44. #include "secrets.h"
  45. #include "POTA.h"
  46.  
  47. /****** FUNCTION PROTOTYPES *****/
  48. void setup(void);
  49. void loop(void);
  50. void setupDashboard(void);
  51. void setupDashboardCallbacks(void);
  52. void onOTAAvailable(const char* version);
  53.  
  54. /***** DEFINITION OF I2C PINS *****/
  55. const uint8_t myOLED_SSD1306OledDisplay_I2C_PIN_SDA_D21 = 21;
  56. const uint8_t myOLED_SSD1306OledDisplay_I2C_PIN_SCL_D22 = 22;
  57. const uint8_t myOLED_SSD1306OledDisplay_I2C_SLAVE_ADDRESS = 0x3C; // Standard I2C address for SSD1306
  58.  
  59. /***** OLED DISPLAY PARAMETERS *****/
  60. const uint8_t OLED_SCREEN_WIDTH = 128; // SSD1306 OLED width in pixels
  61. const uint8_t OLED_SCREEN_HEIGHT = 64; // SSD1306 OLED height in pixels
  62. const int8_t OLED_RESET_PIN = -1; // Reset pin (-1 = no reset pin)
  63.  
  64. /****** DEFINITION OF LIBRARIES CLASS INSTANCES *****/
  65. // Create SSD1306 display object with I2C address 0x3C
  66. Adafruit_SSD1306 display(OLED_SCREEN_WIDTH, OLED_SCREEN_HEIGHT, &Wire, OLED_RESET_PIN);
  67.  
  68. // Create POTA instance for OTA and Dashboard functionality
  69. POTA pota;
  70.  
  71. // Dashboard widget IDs
  72. uint8_t dashboardHeader;
  73. uint8_t statusIndicator;
  74. uint8_t systemTemperature;
  75. uint8_t systemUptime;
  76. uint8_t systemMemory;
  77. uint8_t ledToggle;
  78. uint8_t deviceInfo;
  79.  
  80. // Device state variables
  81. bool otaAvailable = false;
  82. unsigned long startTime = 0;
  83. uint32_t lastUpdateTime = 0;
  84.  
  85. /**
  86.  * @brief Initialize dashboard with widgets
  87.  * Configures all POTA dashboard widgets for monitoring and control
  88.  */
  89. void setupDashboard(void) {
  90.     Serial.println("🎨 Configuring POTA dashboard widgets...");
  91.    
  92.     // Header separator with title and description
  93.     dashboardHeader = pota.dashboard.addWidget(SEPARATOR_CARD, "📊 ESP32 Device Dashboard", 0, "Real-time monitoring and control interface for ESP32 DevKit V1 with OLED display integration");
  94.    
  95.     // Status indicator - shows current device status
  96.     statusIndicator = pota.dashboard.addWidget(FEEDBACK_CARD, "System Status");
  97.     pota.dashboard.setValue(statusIndicator, STATUS_SUCCESS);
  98.    
  99.     // Temperature slider - displays system temperature (read-only simulation)
  100.     // Step 0.1 provides float values with 1 decimal precision
  101.     systemTemperature = pota.dashboard.addWidget(SLIDER_CARD, "System Temperature (°C)", 0, "CPU Temperature", 0.1, 20, 85);
  102.     pota.dashboard.setValue(systemTemperature, 45.5);
  103.    
  104.     // Uptime display - shows device runtime in seconds (read-only)
  105.     // Step 1 provides integer values
  106.     systemUptime = pota.dashboard.addWidget(SLIDER_CARD, "Uptime (seconds)", 0, "Time since device started", 1, 0, 2147483647);
  107.     pota.dashboard.setValue(systemUptime, 0);
  108.    
  109.     // Memory usage - displays free heap memory
  110.     // Step 100 provides values in 100-byte increments
  111.     systemMemory = pota.dashboard.addWidget(SLIDER_CARD, "Free Memory (bytes)", 0, "Available heap memory", 100, 0, 4000000);
  112.     pota.dashboard.setValue(systemMemory, 0);
  113.    
  114.     // LED toggle control - bidirectional widget for controlling LED
  115.     ledToggle = pota.dashboard.addWidget(TOGGLE_BUTTON_CARD, "Onboard LED Control");
  116.     pota.dashboard.setValue(ledToggle, false);
  117.    
  118.     // Device info display - shows firmware and hardware details
  119.     deviceInfo = pota.dashboard.addWidget(FEEDBACK_CARD, "Device Information");
  120.     pota.dashboard.setValue(deviceInfo, STATUS_INFO);
  121.    
  122.     Serial.println("✅ Dashboard widgets configured successfully!");
  123. }
  124.  
  125. /**
  126.  * @brief Register callbacks for dashboard widget interactions
  127.  * Sets up event handlers for user interactions with dashboard widgets
  128.  */
  129. void setupDashboardCallbacks(void) {
  130.     Serial.println("📡 Registering dashboard callbacks...");
  131.    
  132.     // LED toggle callback - handle on/off control from dashboard
  133.     pota.dashboard.onUpdate(ledToggle, [](WidgetData data) {
  134.         bool ledState = data.getBool();
  135.        
  136.         Serial.print("💡 LED control from dashboard: ");
  137.         Serial.println(ledState ? "ON" : "OFF");
  138.        
  139.         // Control the onboard LED
  140.         digitalWrite(LED_BUILTIN, ledState ? HIGH : LOW);
  141.        
  142.         // Update status feedback
  143.         pota.dashboard.setValue(statusIndicator, ledState ? STATUS_SUCCESS : STATUS_NONE);
  144.        
  145.         // Update OLED display
  146.         displayLEDStatus(ledState);
  147.     });
  148.    
  149.     Serial.println("✅ Callbacks registered successfully!");
  150. }
  151.  
  152. /**
  153.  * @brief Callback invoked when OTA update is available
  154.  * Registers availability of new firmware version
  155.  *
  156.  * @param version Pointer to version string of available update
  157.  */
  158. void onOTAAvailable(const char* version) {
  159.     Serial.print("🔄 OTA Update available: ");
  160.     Serial.println(version);
  161.    
  162.     otaAvailable = true;
  163.    
  164.     // Update dashboard status
  165.     pota.dashboard.setValue(statusIndicator, STATUS_WARNING);
  166.    
  167.     // Update OLED display
  168.     displayOTAAvailable(version);
  169. }
  170.  
  171. /**
  172.  * @brief Display LED status on OLED screen
  173.  * Updates OLED display with current LED state
  174.  *
  175.  * @param isOn Current LED state (true = ON, false = OFF)
  176.  */
  177. void displayLEDStatus(bool isOn) {
  178.     display.clearDisplay();
  179.     display.setTextSize(2);
  180.     display.setTextColor(SSD1306_WHITE);
  181.     display.setCursor(0, 0);
  182.     display.println(F("Hello"));
  183.     display.println(F("World"));
  184.    
  185.     display.setTextSize(1);
  186.     display.setCursor(0, 40);
  187.     display.print(F("LED: "));
  188.     display.println(isOn ? F("ON") : F("OFF"));
  189.    
  190.     display.display();
  191. }
  192.  
  193. /**
  194.  * @brief Display OTA availability notification on OLED
  195.  * Shows version information of available update
  196.  *
  197.  * @param version Pointer to version string of available update
  198.  */
  199. void displayOTAAvailable(const char* version) {
  200.     display.clearDisplay();
  201.     display.setTextSize(1);
  202.     display.setTextColor(SSD1306_WHITE);
  203.     display.setCursor(0, 0);
  204.     display.println(F("OTA Available!"));
  205.     display.print(F("Version: "));
  206.     display.println(version);
  207.     display.println(F("Restarting..."));
  208.    
  209.     display.display();
  210. }
  211.  
  212. /**
  213.  * @brief Update system metrics on dashboard
  214.  * Periodically updates temperature, uptime, and memory values
  215.  */
  216. void updateSystemMetrics(void) {
  217.     // Only update every 5 seconds to avoid excessive updates
  218.     if (millis() - lastUpdateTime < 5000) {
  219.         return;
  220.     }
  221.     lastUpdateTime = millis();
  222.    
  223.     // Calculate uptime in seconds
  224.     unsigned long uptimeSeconds = (millis() - startTime) / 1000;
  225.     pota.dashboard.setValue(systemUptime, (int)uptimeSeconds);
  226.    
  227.     // Get free heap memory
  228.     uint32_t freeHeap = 0;
  229.     #ifdef ESP32
  230.         freeHeap = ESP.getFreeHeap();
  231.     #elif defined(ESP8266)
  232.         freeHeap = ESP.getFreeHeap();
  233.     #endif
  234.     pota.dashboard.setValue(systemMemory, (int)freeHeap);
  235.    
  236.     // Simulate temperature reading (in real application, use ADC)
  237.     // Temperature varies slightly around 45°C
  238.     float tempBase = 45.5;
  239.     float tempVariation = 2.0 * sin(uptimeSeconds / 10.0);
  240.     float temperature = tempBase + tempVariation;
  241.     pota.dashboard.setValue(systemTemperature, temperature);
  242. }
  243.  
  244. void setup(void)
  245. {
  246.     // Initialize serial communication
  247.     Serial.begin(115200);
  248.     delay(2000);
  249.    
  250.     Serial.println("\n╔════════════════════════════════════════╗");
  251.     Serial.println("║     OLED + POTA Dashboard Example      ║");
  252.     Serial.println("╚════════════════════════════════════════╝\n");
  253.    
  254.     // Initialize the I2C communication with custom pins for ESP32
  255.     Wire.begin(myOLED_SSD1306OledDisplay_I2C_PIN_SDA_D21, myOLED_SSD1306OledDisplay_I2C_PIN_SCL_D22);
  256.  
  257.     // Initialize the SSD1306 display with I2C address 0x3C
  258.     if (!display.begin(SSD1306_SWITCHCAPVCC, myOLED_SSD1306OledDisplay_I2C_SLAVE_ADDRESS))
  259.     {
  260.         Serial.println("❌ SSD1306 initialization failed!");
  261.         // Failed to initialize display - loop indefinitely
  262.         while (1)
  263.         {
  264.             delay(100);
  265.         }
  266.     }
  267.  
  268.     // Clear the display buffer
  269.     display.clearDisplay();
  270.  
  271.     // Set text size and color for "Hello World" text
  272.     display.setTextSize(2); // Set text size to 2 (double size)
  273.     display.setTextColor(SSD1306_WHITE); // Set text color to white
  274.  
  275.     // Set cursor position (x=0, y=0 at top-left corner)
  276.     display.setCursor(0, 0);
  277.  
  278.     // Print "Hello World" text to the display buffer
  279.     display.println(F("Hello"));
  280.     display.println(F("World"));
  281.  
  282.     // Refresh the display to show the text on the screen
  283.     display.display();
  284.    
  285.     Serial.println("✅ OLED Display initialized");
  286.  
  287.     // Configure onboard LED
  288.     pinMode(LED_BUILTIN, OUTPUT);
  289.     digitalWrite(LED_BUILTIN, LOW);
  290.    
  291.     // Initialize POTA with credentials from secrets.h
  292.     Serial.println("\n🔧 Initializing POTA...");
  293.     POTAError err = pota.begin(
  294.         DEVICE_TYPE,
  295.         FIRMWARE_VERSION,
  296.         AUTH_TOKEN,
  297.         SERVER_SECRET,
  298.         WIFI_SSID,
  299.         WIFI_PASSWORD
  300.     );
  301.    
  302.     if (err != POTAError::SUCCESS) {
  303.         Serial.print("❌ POTA initialization failed: ");
  304.         Serial.println(POTA::errorToString(err));
  305.         return;
  306.     }
  307.    
  308.     Serial.println("✅ POTA initialized successfully");
  309.    
  310.     // Check for OTA updates immediately after initialization
  311.     Serial.println("\n🔍 Checking for OTA updates...");
  312.     err = pota.checkAndPerformOTA();
  313.    
  314.     if (err == POTAError::NO_UPDATE_AVAILABLE) {
  315.         Serial.println("✅ Device is up to date");
  316.     } else if (err != POTAError::SUCCESS) {
  317.         Serial.print("⚠️  OTA check result: ");
  318.         Serial.println(POTA::errorToString(err));
  319.     }
  320.    
  321.     // Register OTA availability callback
  322.     // This will be called if an update becomes available during runtime
  323.     pota.onOTAAvailable(onOTAAvailable);
  324.    
  325.     // Register dashboard configuration callback
  326.     pota.dashboard.setWidgetConfigCallback(setupDashboard);
  327.    
  328.     // Register callback for widget interactions
  329.     pota.dashboard.setWidgetConfigCallback([](void) {
  330.         setupDashboard();
  331.         setupDashboardCallbacks();
  332.     });
  333.    
  334.     // Initialize startup time for uptime calculation
  335.     startTime = millis();
  336.     lastUpdateTime = millis();
  337.    
  338.     Serial.println("✅ Setup complete");
  339.     Serial.println("📱 Dashboard is ready! Connect to the POTA service.\n");
  340. }
  341.  
  342. void loop(void)
  343. {
  344.     // Call POTA loop to handle WebSocket connections, OTA checks, and dashboard updates
  345.     pota.loop();
  346.    
  347.     // Update system metrics for dashboard display
  348.     updateSystemMetrics();
  349.    
  350.     // If OTA is available and callback was triggered, restart the device
  351.     if (otaAvailable) {
  352.         Serial.println("🔄 Restarting device for OTA update...");
  353.         pota.restart();
  354.         // restart() will not return - device will restart
  355.     }
  356.    
  357.     // Small delay to prevent overwhelming the CPU
  358.     delay(100);
  359. }
  360.  
  361. /* END CODE */
  362.  
Advertisement
Add Comment
Please, Sign In to add comment