可通过 HTTP JSON API/Web 浏览器控制的 ESP32 舵机
此 PlatformIO 草图允许你将 ESP32 用作舵机控制器(舵机在引脚 D25 上),它连接到 Wifi 并可使用简单的 HTTP API 控制。Web 服务器使用 ESPAsyncWebserver 实现。如果你不熟悉该库,另请参见PlatformIO 的 ESP32 最小 JSON Web 服务器示例 (ESPAsyncWebserver)。此示例不是完成的应用程序,而是构建你自己的应用程序的最小起点。
main.cpp
main.cpp
#include <Arduino.h>
#include <Arduino.h>
#include <WiFi.h>
#include <ESP32Servo.h>
#include <ESPAsyncWebServer.h>
#include <ArduinoJson.h>
AsyncWebServer server(80);
/**
* 等待 WiFi 连接,如果未连接则重启
*/
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) { // 如果 5 秒后未连接则重置板
if(printOnSerial) {
Serial.println("Resetting due to Wifi not connecting...");
}
ESP.restart();
}
}
if(printOnSerial) {
// 打印 wifi IP 地址
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();
// 将舵机连接到引脚 25
servo.attach(25, 1000, 2000);
// 配置 HTTP 路由
server.on("/api/set-servo", HTTP_GET, [](AsyncWebServerRequest *request) {
float value = request->arg("value").toFloat();
servo.write(value);
// 发送 {status: "ok"}
AsyncResponseStream *response = request->beginResponseStream("application/json");
DynamicJsonDocument json(1024);
json["status"] = "ok";
serializeJson(json, *response);
request->send(response);
});
// 启动 Web 服务器
server.begin();
}
void loop() {
}platformio.ini
platformio.ini
[env:nodemcu-32s]
platform = espressif32
board = nodemcu-32s
framework = arduino
monitor_speed = 115200
lib_deps =
ESP Async Webserver@1.2.3
ArduinoJSON@6.17.2
ESP32Servo如何使用
在以下行中插入你的 Wifi 凭据
main.cpp
WiFi.begin("MyWifiSSID", "MyWifiPassword");并上传固件。现在打开 http://[ESP32 的 IP 地址]/api/set-servo?value=0.0。注意在当前版本的固件中,你不能使用 value=10,而必须使用 value=10.0。
Check out similar posts by category:
ESP8266/ESP32, PlatformIO
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow