# main.ino

- Project: [esp32-MG995-example](https://flashesp.com/explore/EaxoiTG2yqqrenC0Zjko3.md) by Mikrobot.pl
- Board: ESP32 Dev Module
- Language: Arduino (C++)
- Web page: https://flashesp.com/explore/EaxoiTG2yqqrenC0Zjko3/files/W0NurHs9N0rNStDKS3Tdh

```cpp
#include <WiFi.h>
#include <WebServer.h>
#include <DNSServer.h>
#include <ESP32Servo.h>

// =======================
// SERVO CONFIGURATION
// =======================
#define SERVO_PIN 13

// Measured calibration: 500 us = 0 deg, 2500 us = 180 deg
// Resolution: 2000 us / 180 deg = 11.11 us per degree
#define SERVO_MIN_US 500
#define SERVO_MAX_US 2500
#define ANGLE_MAX    180

// Safety margin away from the end stops [us].
// 0 = full range. If the servo buzzes or heats up at the extremes, set 25 or 50.
#define EDGE_MARGIN_US 0

Servo myServo;

int  servoAngle   = 90;
int  currentUs    = 1500;
bool servoHolding = true;   // true = holding position, false = released (no pulse)

// Non-blocking sweep test
bool          sweepActive = false;
int           sweepDir    = 1;
unsigned long lastSweepMs = 0;
const unsigned long SWEEP_STEP_MS = 12; // ~2.2 s for a full 0-180 travel

// =======================
// WIFI ACCESS POINT CONFIG
// =======================
const char* ap_ssid = "ESP32-SERVO"; // 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);

// =======================
// SERVO CONTROL
// =======================
int angleToUs(int deg) {
  deg = constrain(deg, 0, ANGLE_MAX);
  long us = (long)SERVO_MIN_US +
            (long)deg * (SERVO_MAX_US - SERVO_MIN_US) / ANGLE_MAX;
  return constrain((int)us,
                   SERVO_MIN_US + EDGE_MARGIN_US,
                   SERVO_MAX_US - EDGE_MARGIN_US);
}

void applyAngle() {
  currentUs = angleToUs(servoAngle);
  if (!servoHolding) return;

  if (!myServo.attached()) {
    myServo.attach(SERVO_PIN, SERVO_MIN_US, SERVO_MAX_US);
  }
  myServo.writeMicroseconds(currentUs);
}

void moveTo(int deg) {
  servoAngle = constrain(deg, 0, ANGLE_MAX);
  if (!servoHolding) servoHolding = true; // any move wakes the servo up
  applyAngle();
}

void setHolding(bool hold) {
  servoHolding = hold;

  if (hold) {
    applyAngle();
  } else {
    sweepActive = false;
    if (myServo.attached()) myServo.detach(); // no pulse -> shaft goes limp, no heating
  }
}

void updateSweep() {
  if (!sweepActive || !servoHolding) return;

  unsigned long now = millis();
  if (now - lastSweepMs < SWEEP_STEP_MS) return;
  lastSweepMs = now;

  servoAngle += sweepDir;
  if (servoAngle >= ANGLE_MAX) { servoAngle = ANGLE_MAX; sweepDir = -1; }
  if (servoAngle <= 0)         { servoAngle = 0;         sweepDir =  1; }

  applyAngle();
}

// =======================
// HTML PAGE
// =======================
String htmlPage() {
  String html = "<!DOCTYPE html><html><head>"
                "<meta charset='UTF-8'>"
                "<meta name='viewport' content='width=device-width, initial-scale=1.0'>"
                "<title>ESP32 Servo Control</title>"
                "<style>"
                "body{font-family:sans-serif;margin:18px;max-width:540px;}"
                "button{padding:10px 16px;margin:4px;font-size:16px;}"
                ".status{padding:12px;background:#eee;margin-bottom:12px;}"
                "input[type=range]{width:100%;height:38px;}"
                ".big{font-size:30px;font-weight:bold;}"
                ".sub{color:#666;font-size:14px;}"
                "</style></head><body>";

  html += "<h2>ESP32 &ndash; MG995 Servo Control</h2>";

  html += "<div class='status'>"
          "Position: <span class='big' id='val'>" + String(servoAngle) + "</span>&deg;<br>"
          "<span class='sub'>pulse: <b id='us'>" + String(currentUs) + "</b> &micro;s"
          " &nbsp;|&nbsp; state: <b id='mode'>" +
          String(servoHolding ? (sweepActive ? "SWEEPING" : "HOLDING") : "RELEASED") +
          "</b></span></div>";

  html += "<input type='range' id='sl' min='0' max='180' step='1' value='" +
          String(servoAngle) + "'>";

  html += "<p>";
  html += "<button onclick=\"go(0)\">0&deg;</button>";
  html += "<button onclick=\"go(45)\">45&deg;</button>";
  html += "<button onclick=\"go(90)\">90&deg;</button>";
  html += "<button onclick=\"go(135)\">135&deg;</button>";
  html += "<button onclick=\"go(180)\">180&deg;</button>";
  html += "</p>";

  html += "<p>";
  html += "<button onclick=\"nudge(-5)\">&laquo; -5&deg;</button>";
  html += "<button onclick=\"nudge(-1)\">&lsaquo; -1&deg;</button>";
  html += "<button onclick=\"nudge(1)\">+1&deg; &rsaquo;</button>";
  html += "<button onclick=\"nudge(5)\">+5&deg; &raquo;</button>";
  html += "</p>";

  html += "<hr><p>";
  html += "<button onclick=\"cmd('/sweep?state=on')\">Sweep START</button>";
  html += "<button onclick=\"cmd('/sweep?state=off')\">Sweep STOP</button>";
  html += "</p><p>";
  html += "<button onclick=\"cmd('/hold?state=on')\">Hold</button>";
  html += "<button onclick=\"cmd('/hold?state=off')\">Release</button>";
  html += "</p>";

  // Fallback for browsers with JavaScript disabled
  html += "<hr><form action='/set' method='GET'>";
  html += "<input type='number' name='angle' min='0' max='180' value='" +
          String(servoAngle) + "'> ";
  html += "<button type='submit'>Set (no-JS)</button></form>";

  html += "<hr><p>Connect to WiFi network <b>ESP32-SERVO</b> (open network, no password).</p>";
  html += "<p>This page should open automatically as a captive portal.</p>";

  html += "<script>"
          "var sl=document.getElementById('sl');"
          "var busy=0;"
          "sl.oninput=function(){busy=1;document.getElementById('val').innerHTML=sl.value;};"
          "sl.onchange=function(){cmd('/set?angle='+sl.value);busy=0;};"
          "function go(a){busy=0;sl.value=a;cmd('/set?angle='+a);}"
          "function nudge(d){busy=0;cmd('/nudge?d='+d);}"
          "function cmd(u){fetch(u+(u.indexOf('?')<0?'?':'&')+'ajax=1')"
          ".then(function(r){return r.json();}).then(upd).catch(function(){});}"
          "function upd(d){"
          "if(!busy){sl.value=d.angle;document.getElementById('val').innerHTML=d.angle;}"
          "document.getElementById('us').innerHTML=d.us;"
          "document.getElementById('mode').innerHTML="
          "d.hold?(d.sweep?'SWEEPING':'HOLDING'):'RELEASED';}"
          "setInterval(function(){cmd('/status');},350);"
          "</script>";

  html += "</body></html>";
  return html;
}

String jsonStatus() {
  String j = "{\"angle\":" + String(servoAngle);
  j += ",\"us\":" + String(currentUs);
  j += ",\"sweep\":"; j += sweepActive  ? "true" : "false";
  j += ",\"hold\":";  j += servoHolding ? "true" : "false";
  j += "}";
  return j;
}

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

// Reply with JSON for fetch() calls, full HTML for plain form submits
void reply() {
  if (server.hasArg("ajax")) {
    server.send(200, "application/json", jsonStatus());
  } else {
    server.send(200, "text/html", htmlPage());
  }
}

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

void handleStatus() {
  server.send(200, "application/json", jsonStatus());
}

void handleSetAngle() {
  if (server.hasArg("angle")) {
    sweepActive = false;
    moveTo(server.arg("angle").toInt());

    Serial.print("Servo -> ");
    Serial.print(servoAngle);
    Serial.print(" deg (");
    Serial.print(currentUs);
    Serial.println(" us)");
  }
  reply();
}

void handleNudge() {
  if (server.hasArg("d")) {
    sweepActive = false;
    moveTo(servoAngle + server.arg("d").toInt());

    Serial.print("Servo -> ");
    Serial.print(servoAngle);
    Serial.println(" deg");
  }
  reply();
}

void handleSetSweep() {
  if (server.hasArg("state")) {
    if (server.arg("state") == "on") {
      setHolding(true);
      sweepActive = true;
      lastSweepMs = millis();
    } else {
      sweepActive = false;
    }
  }
  reply();
}

void handleSetHold() {
  if (server.hasArg("state")) {
    setHolding(server.arg("state") == "on");
  }
  reply();
}

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 servo
  ESP32PWM::allocateTimer(0);
  ESP32PWM::allocateTimer(1);
  myServo.setPeriodHertz(50);                            // 50 Hz standard RC frame
  myServo.attach(SERVO_PIN, SERVO_MIN_US, SERVO_MAX_US);
  servoAngle   = 90;
  servoHolding = true;
  applyAngle();

  // 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);
  Serial.print("Servo range: ");
  Serial.print(SERVO_MIN_US);
  Serial.print(" - ");
  Serial.print(SERVO_MAX_US);
  Serial.println(" us over 0-180 deg");

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

  // Setup web server routes
  server.on("/", handleRoot);
  server.on("/set", handleSetAngle);
  server.on("/nudge", handleNudge);
  server.on("/sweep", handleSetSweep);
  server.on("/hold", handleSetHold);
  server.on("/status", handleStatus);

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

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

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

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