ESP8266WIFI AP模式驱动SG90舵机,以及处理SG90旋转只能旋转90度或者只能旋转设定角度一半的问题。
安装arduino流程参考文档:
控制舵机参考文档:
舵机只能旋转一半角度问题处理方案:
完整代码:
#include <Servo.h>
#include <Arduino.h>
#include "ESP8266WiFi.h"
#include "ESP8266WebServer.h"
Servo myservo;
ESP8266WebServer server(80);
void handleRoot() {
String html = "<!DOCTYPE html>\n"
"<html lang=\"en\">\n"
"<head>\n"
"<meta charset=\"UTF-8\">\n"
"<style>\n"
"body {\n"
" display: flex;\n"
" flex-direction: column;\n"
" justify-content: center;\n"
" align-items: center;\n"
" height: 100vh;\n"
" margin: 0;\n"
" font-family: Arial, sans-serif;\n"
"}\n"
"\n"
".button-container {\n"
" text-align: center;\n"
" width: 100%;\n"
" max-width: 300px;\n" /* 可选:限制按钮容器的最大宽度 */
"}\n"
"\n"
".button {\n"
" display: block;\n" /* 将按钮设置为块级元素,以便它们竖向排列 */
" padding: 10px 20px;\n"
" font-size: 16px;\n"
" font-weight: bold;\n"
" text-align: center;\n"
" text-decoration: none;\n"
" color: #fff;\n"
" background-color: #007BFF;\n"
" border: none;\n"
" border-radius: 5px;\n"
" cursor: pointer;\n"
" margin: 10px 0; \n"
"}\n"
"\n"
".button:hover {\n"
" background-color: #0056b3;\n"
"}\n"
"\n"
".button:active {\n"
" background-color: #004085;\n"
"}\n"
"</style>\n"
"</head>\n"
"<body>\n"
"<div class=\"button-container\">\n"
"<h2>WIFI控制开关</h2>\n"
"<a href=\"/on\" class=\"button\">旋转到180度</a>\n"
"<a href=\"/off\" class=\"button\">旋转到0度</a>\n"
"<a href=\"/fw\" class=\"button\">旋转到90度</a>\n"
"<a href=\"/xh\" class=\"button\">0-90-180</a>\n"
"</div>\n"
"</body>\n"
"</html>\n";
server.send(200, "text/html", html);
}
void handleOn() {
myservo.write(180); // 旋转到180度
server.sendHeader("Location", "/");
server.send(303);
}
void handleOff() {
myservo.write(0); // 旋转到0度
server.sendHeader("Location", "/");
server.send(303);
}
void handleFw() {
myservo.write(90); // 旋转到90度
server.sendHeader("Location", "/");
server.send(303);
}
void handleXh() {
myservo.write(0);
delay(3000);
myservo.write(90);
delay(3000);
myservo.write(180);
server.sendHeader("Location", "/");
server.send(303);
}
void setup() {
Serial.begin(115200); //设置波特率
myservo.attach(D4,500,2500);
//myservo.attach(D4); //定义引脚
myservo.write(90); // 初始位置
WiFi.mode(WIFI_AP); //设置WiFi模式
WiFi.softAP("sgwifi", "12345678"); //设置名称,密码
server.begin(); //开启服务
server.on("/", handleRoot);
server.on("/on", handleOn);
server.on("/off", handleOff);
server.on("/fw", handleFw);
server.on("/xh", handleXh);
}
void loop() {
server.handleClient();
}
最后附上几个安装包:
提取码:C21A
简要安装流程:
1、安装arduino-ide_2.3.3_Windows_64bit.exe,一路默认即可。
2、修改arduino的语言等红框信息http://arduino.esp8266.com/stable/package_esp8266com_index.json
3、安装CH341SER.EXE(这个是CH340驱动,你如果不是CH340不用安装,找自己的对应驱动即可)。
4、安装8266_package_3.1.1_arduinome.exe离线开发包
5、选择红框这个:
6、选择端口:
然后这里就显示:
7、写完代码,上传,等编译和上传就可以了。