#include <Stepper.h>
#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
// Define your stepper motor and limit switch pins
#define motorStepPin 26
#define motorDirPin 27
#define limitSwitch1 34
#define limitSwitch2 35
// Define your stepper motor object
Stepper myStepper(200, motorStepPin, motorDirPin);
// Define variables for tracking the motor position and the suction state
int motorPosition = 0;
bool suctionState = false;
// Create an instance of the web server
AsyncWebServer server(80);
// Handle the "start" request from the Home Assistant dashboard
void handleStartRequest(AsyncWebServerRequest *request) {
// Move the motor to the limit switch 2
while (digitalRead(limitSwitch2) == LOW) {
myStepper.step(1);
motorPosition++;
}
// Turn on the suction and wait for 2 minutes
digitalWrite(suctionPin, HIGH);
delay(120000);
// Turn off the suction and move the motor to limit switch 1
digitalWrite(suctionPin, LOW);
while (digitalRead(limitSwitch1) == LOW) {
myStepper.step(-1);
motorPosition--;
}
// Turn on the suction and wait for 2 minutes
digitalWrite(suctionPin, HIGH);
delay(120000);
// Turn off the suction and move the motor back to the home position
digitalWrite(suctionPin, LOW);
while (motorPosition > 0) {
myStepper.step(-1);
motorPosition--;
}
// Send a response to the Home Assistant dashboard
request->send(200, "text/plain", "Cycle complete.");
}
void setup() {
// Initialize the serial port and the limit switch pins
Serial.begin(9600);
pinMode(limitSwitch1, INPUT_PULLUP);
pinMode(limitSwitch2, INPUT_PULLUP);
// Initialize the stepper motor and set the speed to 100 RPM
myStepper.setSpeed(100);
// Initialize the suction pin and turn it off
pinMode(suctionPin, OUTPUT);
digitalWrite(suctionPin, LOW);
// Connect to your Wi-Fi network
WiFi.begin("Micromotion Wi-Fi", "Zahid@0908");
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi.");
// Register the "start" request handler with the web server
server.on("/start", HTTP_GET, handleStartRequest);
// Start the web server
server.begin();
}
void loop() {
// Nothing to do here
}