// Include necessary libraries
#include <WiFi.h>
#include <ESPAsyncWebServer.h>
// Define motor pins
#define MOTOR1_PIN 12
#define MOTOR2_PIN 2
// Define WiFi credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// Create AsyncWebServer object
AsyncWebServer server(80);
// Function to handle motor control requests
void handleMotorControl(AsyncWebServerRequest *request) {
// Get motor direction and speed from request parameters
String direction = request->getParam("direction")->value();
int speed = request->getParam("speed")->value().toInt();
// Convert speed to PWM value (0-255)
int pwm = map(speed, 0, 100, 0, 255);
// Control motor based on direction
if (direction == "forward") {
// Set motor pins to HIGH and PWM value
digitalWrite(MOTOR1_PIN, HIGH);
analogWrite(MOTOR2_PIN, pwm);
} else if (direction == "backward") {
// Set motor pins to LOW and PWM value
digitalWrite(MOTOR1_PIN, LOW);
analogWrite(MOTOR2_PIN, pwm);
} else if (direction == "left") {
// Set motor pins to LOW and PWM value
digitalWrite(MOTOR1_PIN, LOW);
analogWrite(MOTOR2_PIN, pwm);
} else if (direction == "right") {
// Set motor pins to HIGH and PWM value
digitalWrite(MOTOR1_PIN, HIGH);
analogWrite(MOTOR2_PIN, pwm);
} else if (direction == "stop") {
// Set motor pins to LOW and PWM value
digitalWrite(MOTOR1_PIN, LOW);
analogWrite(MOTOR2_PIN, 0);
}
// Send response to client
request->send(200, "text/plain", "Motor control successful");
}
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Set motor pins as outputs
pinMode(MOTOR1_PIN, OUTPUT);
pinMode(MOTOR2_PIN, OUTPUT);
// Connect to WiFi network
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi..");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("Connected to WiFi");
// Print IP address
Serial.println(WiFi.localIP());
// Route for motor control
server.on("/motor", HTTP_GET, handleMotorControl);
// Start server
server.begin();
}
void loop() {
// Nothing to do in loop
}