# main.ino

- Project: [esp-32-with-micro-servo-example](https://flashesp.com/explore/km4MK7p7fT3w4GMZnl8Y5.md) by Mikrobot.pl
- Board: ESP32 Dev Module
- Language: Arduino (C++)
- Web page: https://flashesp.com/explore/km4MK7p7fT3w4GMZnl8Y5/files/EcpqNwk3JJSGDmmwtEADk

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

// =======================
// SERVO CONFIGURATION
// =======================
#define SERVO_PIN 13           // GPIO pin connected to the servo signal wire (orange/yellow)
#define SERVO_MIN_US 500       // Minimum pulse width in microseconds (adjust if servo doesn't reach 0 deg)
#define SERVO_MAX_US 2400      // Maximum pulse width in microseconds (adjust if servo doesn't reach 180 deg)

#define ANGLE_MIN 0
#define ANGLE_MAX 180
#define ANGLE_CENTER 90
#define ANGLE_STEP 15           // Degrees moved per "Left" / "Right" button press

Servo myServo;
int currentAngle = ANGLE_CENTER;

// =======================
// 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
// =======================
void setServoAngle(int angle) {
  angle = constrain(angle, ANGLE_MIN, ANGLE_MAX);
  currentAngle = angle;
  myServo.write(currentAngle);
}

// =======================
// HTML PAGE
// =======================
String htmlPage(int angle) {
  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:20px;text-align:center;}"
                "button{padding:14px 26px;margin:6px;font-size:18px;}"
                ".status{padding:10px;background:#eee;display:inline-block;margin-bottom:15px;}"
                "input[type=range]{width:80%;}"
                "</style>"
                "</head><body>";

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

  html += "<p class='status'>Current angle: <b>" + String(angle) + "&deg;</b></p><br>";

  // Left / Center / Right buttons
  html += "<form action='/set' method='GET' style='display:inline-block;'>";
  html += "<input type='hidden' name='dir' value='left'>";
  html += "<button type='submit'>&#8592; Left</button>";
  html += "</form>";

  html += "<form action='/set' method='GET' style='display:inline-block;'>";
  html += "<input type='hidden' name='dir' value='center'>";
  html += "<button type='submit'>Center</button>";
  html += "</form>";

  html += "<form action='/set' method='GET' style='display:inline-block;'>";
  html += "<input type='hidden' name='dir' value='right'>";
  html += "<button type='submit'>Right &#8594;</button>";
  html += "</form>";

  // Precise angle slider - moves the servo live while dragging, no submit button needed
  html += "<br><br><p>Or drag to set a precise angle:</p>";
  html += "<input type='range' id='angleSlider' min='" + String(ANGLE_MIN) + "' max='" + String(ANGLE_MAX)
          + "' value='" + String(angle) + "' oninput='moveServo(this.value)'>";
  html += "<div><output id='angleValue'>" + String(angle) + "</output>&deg;</div>";

  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>";

  // Sends the slider value to the ESP32 immediately on every drag event (no page reload)
  html += "<script>"
          "let lastSent=-1;"
          "function moveServo(val){"
          "document.getElementById('angleValue').innerText=val;"
          "if(val==lastSent)return;"
          "lastSent=val;"
          "fetch('/setAngle?angle='+val);"
          "}"
          "</script>";

  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(currentAngle));
}

void handleSetServo() {
  if (server.hasArg("angle")) {
    // Precise angle requested via the slider
    int angle = server.arg("angle").toInt();
    setServoAngle(angle);
  } else if (server.hasArg("dir")) {
    String dir = server.arg("dir");

    if (dir == "left") {
      setServoAngle(currentAngle - ANGLE_STEP);
    } else if (dir == "right") {
      setServoAngle(currentAngle + ANGLE_STEP);
    } else if (dir == "center") {
      setServoAngle(ANGLE_CENTER);
    }
  }

  server.send(200, "text/html", htmlPage(currentAngle));
}

void handleSetAngleLive() {
  // Used by the slider's JS fetch() call - keep this fast and lightweight,
  // since it may fire many times per second while dragging.
  if (server.hasArg("angle")) {
    int angle = server.arg("angle").toInt();
    setServoAngle(angle);
  }
  server.send(200, "text/plain", String(currentAngle));
}

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
  // Allow allocation of all timers (needed by the ESP32Servo library on some boards)
  ESP32PWM::allocateTimer(0);
  ESP32PWM::allocateTimer(1);
  ESP32PWM::allocateTimer(2);
  ESP32PWM::allocateTimer(3);

  myServo.setPeriodHertz(50);                 // Standard 50Hz servo signal
  myServo.attach(SERVO_PIN, SERVO_MIN_US, SERVO_MAX_US);
  setServoAngle(ANGLE_CENTER);                // Start centered

  // 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", handleSetServo);
  server.on("/setAngle", handleSetAngleLive);

  // 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();
}
```
