`#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
const char* ssid = “May in Mau”;
const char* password = “minhkhue123”;
ESP8266WebServer server(80);
const int cwPin = 5; // CW pulse pin – chính là chân D1
const int ccwPin = 4; // CCW pulse pin – chính là chân D2
int speedCW = 500; // Speed for CW pulses (in microseconds)
int speedCCW = 500; // Speed for CCW pulses (in microseconds)
int steps = 500; // Number of steps
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println(“Connecting to WiFi…”);
}
Serial.println(“Connected to WiFi”);
server.on(“/”, handleRoot);
server.on(“/set”, handleSet);
server.on(“/cw”, handleCW);
server.on(“/ccw”, handleCCW);
server.begin();
Serial.println(“HTTP server started”);
pinMode(cwPin, OUTPUT);
pinMode(ccwPin, OUTPUT);
}
void handleSet() {
if (server.hasArg(“speedCW”)) {
int freqCW = server.arg(“speedCW”).toInt();
if (freqCW > 0) {
speedCW = 1000000 / freqCW;
}
}
if (server.hasArg(“speedCCW”)) {
int freqCCW = server.arg(“speedCCW”).toInt();
if (freqCCW > 0) {
speedCCW = 1000000 / freqCCW;
}
}
if (server.hasArg(“steps”)) {
steps = server.arg(“steps”).toInt();
}
if (server.hasArg(“revolutions”)) {
int revolutions = server.arg(“revolutions”).toInt();
steps = revolutions * 500; // Cập nhật số bước dựa trên số vòng quay
}
server.sendHeader(“Location”, “/”);
server.send(303);
}
void handleRoot() {
String html = "<html><head><meta charset=\“UTF-8\”></head><body><h1>ESP8266 Motor Control</h1>";
html += “<form action=\”/set\" method=\“GET\”>";
html += "Speed CW (Hz): <input type=\“number\” name=\“speedCW\” value=\"“ + String(1000000 / speedCW) + ”\“><br>”;
html += "Speed CCW (Hz): <input type=\“number\” name=\“speedCCW\” value=\"“ + String(1000000 / speedCCW) + ”\“><br>”;
html += "Steps: <input type=\“number\” name=\“steps\” value=\"“ + String(steps) + ”\“><br>”;
html += "Revolutions: <input type=\“number\” name=\“revolutions\” value=\“1\”><br>"; // Thêm trường nhập liệu cho số vòng quay
//html += "<input type=\“submit\” value=\“Set\”>";
html += "<input type=\“submit\” value=\“Set\” style=\“font-size: 20px; padding: 10px 20px;\”>";
html += “</form>”;
html += “<a href=\”/cw\“><button>Clockwise</button></a>”;
html += “<a href=\”/ccw\“><button>Counter-Clockwise</button></a>”;
html += “</body></html>”;
server.send(200, “text/html”, html);
}
void handleCW() {
for (int i = 0; i < steps; i++) {
digitalWrite(cwPin, HIGH);
delayMicroseconds(speedCW);
digitalWrite(cwPin, LOW);
delayMicroseconds(speedCW);
//ESP.wdtFeed(); // Đặt lại WDT thủ công -> không được
}
server.sendHeader(“Location”, “/”);
server.send(303);
}
void handleCCW() {
for (int i = 0; i < steps; i++) {
digitalWrite(ccwPin, HIGH);
delayMicroseconds(speedCCW);
digitalWrite(ccwPin, LOW);
delayMicroseconds(speedCCW);
//ESP.wdtFeed(); // Đặt lại WDT thủ công -> không được
}
server.sendHeader(“Location”, “/”);
server.send(303);
}
void loop() {
server.handleClient();
}
`