main.ino

Arduino (C++) · 213 lines

/*
  ESP32-C3 Super Mini (0.42" OLED) - Captive Portal Text Display
  ---------------------------------------------------------------
  Creates an open WiFi Access Point + captive portal.
  When a device connects, a page opens where you type text.
  After submitting, the text is shown on the on-board 0.42" OLED.

  Board:   ESP32-C3 Super Mini with built-in 0.42" OLED (SSD1306, 72x40 visible)
  IDE:     Arduino IDE (ESP32 core by Espressif)
  Library: U8g2 by olikraus  (Tools -> Manage Libraries -> "U8g2")

  Select board:  "ESP32C3 Dev Module"  (or "ESP32-C3 Super Mini" if available)
*/

#include <WiFi.h>
#include <WebServer.h>
#include <DNSServer.h>
#include <U8g2lib.h>
#include <Wire.h>

// =======================
// OLED CONFIGURATION
// =======================
// The 0.42" OLED on the ESP32-C3 Super Mini is a 72x40 panel driven by an
// SSD1306 controller over I2C. On this board the default I2C pins are:
#define OLED_SDA 5
#define OLED_SCL 6

// U8g2 constructor for the exact 72x40 SSD1306 panel (hardware I2C).
U8G2_SSD1306_72X40_ER_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE);

// =======================
// TEXT TO DISPLAY
// =======================
// Default text shown on boot (\n separates lines).
String displayText = "mikrobot_pl\nflashesp.com";

// =======================
// WIFI ACCESS POINT CONFIG
// =======================
const char* ap_ssid = "ESP32-C3-OLED"; // open AP (no password)

IPAddress apIP(192, 168, 4, 1);
IPAddress netMsk(255, 255, 255, 0);

// =======================
// DNS / CAPTIVE PORTAL
// =======================
const byte DNS_PORT = 53;

DNSServer dnsServer;
WebServer server(80);

// =======================
// OLED RENDER
// =======================
void updateDisplay() {
  u8g2.clearBuffer();
  u8g2.setFont(u8g2_font_6x10_tf); // ~6px wide, 10px tall -> good for 72x40

  const int lineHeight = 11;         // vertical spacing between lines
  int y = 10;                        // baseline of the first line

  // Walk through displayText line by line (split on '\n').
  int start = 0;
  while (start <= displayText.length()) {
    int nl = displayText.indexOf('\n', start);
    String line;
    if (nl == -1) {
      line = displayText.substring(start);
      start = displayText.length() + 1; // done
    } else {
      line = displayText.substring(start, nl);
      start = nl + 1;
    }

    if (y > 40) break;               // don't draw past the visible area
    u8g2.drawStr(0, y, line.c_str());
    y += lineHeight;
  }

  u8g2.sendBuffer();
}

// =======================
// HTML PAGE
// =======================
String htmlPage() {
  // Show the current text in the textarea (convert \n so it survives in HTML).
  String current = displayText;

  String html = "<!DOCTYPE html><html><head>"
                "<meta charset='UTF-8'>"
                "<meta name='viewport' content='width=device-width, initial-scale=1.0'>"
                "<title>ESP32-C3 OLED</title>"
                "<style>"
                "body{font-family:sans-serif;margin:20px;max-width:480px;}"
                "h2{margin-top:0;}"
                "textarea{width:100%;box-sizing:border-box;font-size:16px;padding:8px;}"
                "button{padding:10px 20px;margin-top:10px;font-size:16px;}"
                ".status{padding:10px;background:#eee;white-space:pre-wrap;}"
                "small{color:#666;}"
                "</style>"
                "</head><body>";

  html += "<h2>OLED Text Display</h2>";

  html += "<p>Currently on screen:</p>";
  html += "<div class='status'>";
  html += current;
  html += "</div><br>";

  html += "<form action='/set' method='POST'>";
  html += "<label>New text (each line = one row on the OLED):</label><br>";
  html += "<textarea name='text' rows='4'>";
  html += current;
  html += "</textarea><br>";
  html += "<button type='submit'>Show on OLED</button>";
  html += "</form>";

  html += "<hr><small>Connect to WiFi <b>";
  html += ap_ssid;
  html += "</b> (open network). This page opens automatically as a captive portal.</small>";
  html += "</body></html>";

  return html;
}

// =======================
// CAPTIVE PORTAL REDIRECT
// =======================
void redirectToRoot() {
  String url = "http://" + apIP.toString() + "/";
  server.sendHeader("Location", url, true);
  server.send(302, "text/plain", "");
}

// =======================
// HTTP HANDLERS
// =======================
void handleRoot() {
  server.send(200, "text/html", htmlPage());
}

void handleSetText() {
  if (server.hasArg("text")) {
    displayText = server.arg("text");
    displayText.replace("\r\n", "\n"); // normalize line endings
    displayText.replace("\r", "\n");
    updateDisplay();
  }
  server.send(200, "text/html", htmlPage());
}

void handleNotFound() {
  // Redirect any unknown path to the main page (captive portal behavior)
  redirectToRoot();
}

// Captive portal triggers used by Android, iOS, Windows
void handleGenerate204() { handleRoot(); } // /generate_204 (Android)
void handleHotspotDetect() { handleRoot(); } // /hotspot-detect.html (iOS/macOS)
void handleNCsi() { handleRoot(); }          // /ncsi.txt (Windows)

// =======================
// SETUP
// =======================
void setup() {
  Serial.begin(115200);
  delay(100);

  // Initialize OLED
  Wire.begin(OLED_SDA, OLED_SCL);
  u8g2.begin();
  u8g2.setContrast(255);
  updateDisplay(); // show default text

  // Start WiFi in AP mode (open network)
  WiFi.mode(WIFI_AP);
  WiFi.softAPConfig(apIP, apIP, netMsk);
  WiFi.softAP(ap_ssid);

  Serial.println();
  Serial.print("AP started. SSID: ");
  Serial.println(ap_ssid);
  Serial.print("AP IP address: ");
  Serial.println(apIP);

  // Start DNS server -> redirect all domains to our AP
  dnsServer.start(DNS_PORT, "*", apIP);

  // Setup web server routes
  server.on("/", handleRoot);
  server.on("/set", HTTP_POST, handleSetText);

  // Captive portal paths
  server.on("/generate_204", handleGenerate204);
  server.on("/hotspot-detect.html", handleHotspotDetect);
  server.on("/ncsi.txt", handleNCsi);

  server.onNotFound(handleNotFound);
  server.begin();

  Serial.println("Web server + DNS captive portal started.");
}

// =======================
// LOOP
// =======================
void loop() {
  dnsServer.processNextRequest();
  server.handleClient();
}