#include <WiFi.h>
#include <AccelStepper.h>

// WiFi credentials
const char* ssid = "EECS_Labs";
const char* password = "";

// Create a stepper object
AccelStepper stepper(AccelStepper::FULL4WIRE, 12, 14, 27, 26);

// Setup a web server
WiFiServer server(80);

void setup() {
  // Initialize Serial Monitor
  Serial.begin(115200);

  // Initialize Stepper Motor
  stepper.setMaxSpeed(1000);  // Adjust max speed
  stepper.setSpeed(200);      // Adjust initial speed

  // Connect to WiFi
  Serial.println("Connecting to WiFi...");
  WiFi.begin(ssid, password, 6);

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting...");
  }
  Serial.println("Connected!");

  // Start the server
  server.begin();

  // Print the IP address
  Serial.println(WiFi.localIP());
}

void loop() {
  // Check if a client has connected
  WiFiClient client = server.available();
  if (!client) {
    return;
  }

  // Wait for data from the client
  Serial.println("New Client.");
  while (!client.available()) {
    delay(1);
  }

  // Read the request
  String request = client.readStringUntil('\r');
  Serial.println(request);
  client.flush();

  // Control motor based on request
  if (request.indexOf("/forward") != -1) {
    stepper.move(200);  // Move forward by 200 steps
  }
  if (request.indexOf("/backward") != -1) {
    stepper.move(-200);  // Move backward by 200 steps
  }

  // Perform the step
  stepper.run();

  // Send a response to the client
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println("");
  client.println("<!DOCTYPE HTML>");
  client.println("<html>");
  client.println("<h1>Stepper Motor Control</h1>");
  client.println("<p><a href=\"/forward\">Move Forward</a></p>");
  client.println("<p><a href=\"/backward\">Move Backward</a></p>");
  client.println("</html>");

  delay(1);
  Serial.println("Client disconnected.");
}
A4988