ESP32 Servo controllable via HTTP JSON API / web browser

This sketch for PlatformIO  allows you to use the ESP32 as a Servo controller (servo on pin D25) that connects to Wifi and can be controller using a simple HTTP API. The webserver is implemented using ESPAsyncWebserver. Also see ESP32 minimal JSON webserver example for PlatformIO (ESPAsyncWebserver) in case you are not familiar with that library. This example is not a finished application but a minimal starting point to build your own application.

main.cpp

#include <Arduino.h>
#include <Arduino.h>
#include <WiFi.h>
#include <ESP32Servo.h>

#include <ESPAsyncWebServer.h>
#include <ArduinoJson.h>

AsyncWebServer server(80);

/**
 * Wait for WiFi connection, and, if not connected, reboot
 */
void waitForWiFiConnectOrReboot(bool printOnSerial=true) {
  uint32_t notConnectedCounter = 0;
  while (WiFi.status() != WL_CONNECTED) {
      delay(100);
      if(printOnSerial) {
        Serial.println("Wifi connecting...");
      }
      notConnectedCounter++;
      if(notConnectedCounter > 50) { // Reset board if not connected after 5s
          if(printOnSerial) {
            Serial.println("Resetting due to Wifi not connecting...");
          }
          ESP.restart();
      }
  }
  if(printOnSerial) {
    // Print wifi IP addess
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
  }
}

Servo servo;

void setup() {
  ESP32PWM::allocateTimer(0);
  ESP32PWM::allocateTimer(1);
  ESP32PWM::allocateTimer(2);
  ESP32PWM::allocateTimer(3);

  Serial.begin(115200);

  WiFi.config(INADDR_NONE, INADDR_NONE, INADDR_NONE);
  WiFi.setHostname("ESP-Servo");

  WiFi.begin("MyWifiSSID", "MyWifiPassword");
  waitForWiFiConnectOrReboot();

  // Attach servo to pin 25
  servo.attach(25, 1000, 2000);
  
  // Configure HTTP routes
  server.on("/api/set-servo", HTTP_GET, [](AsyncWebServerRequest *request) {
      float value = request->arg("value").toFloat();
      servo.write(value);
      // Send {status: "ok"}
      AsyncResponseStream *response = request->beginResponseStream("application/json");
      DynamicJsonDocument json(1024);
      json["status"] = "ok";
      serializeJson(json, *response);
      request->send(response);
  });
  
  // Start webserver
  server.begin();
}

void loop() {
}

platformio.ini

[env:nodemcu-32s]
platform = espressif32
board = nodemcu-32s
framework = arduino
monitor_speed = 115200
lib_deps =
    ESP Async [email protected]
    [email protected]
    ESP32Servo

How to use

Insert your Wifi credentials in the line

WiFi.begin("MyWifiSSID", "MyWifiPassword");

and upload the firmware. Now open http://[ip address of the ESP32]/api/set-servo?value=0.0. Note that in the current version of the firmware, you can not use value=10 but you must use value=10.0.