#include <Stepper.h>
//Passos necessários para fazer uma volta completa
const int stepsPerRevolution = 2038;
//Pin do sensor
const int sensorPin = 5;
//Constante do estado da caixa: 1 - Limpo, 0- Sujo
int clean = 1;
//Configuração do stepper
Stepper myStepper(stepsPerRevolution, 12, 14, 27, 26);
//Configuração do non-blocking delay
unsigned long previousMillis = 0;
const unsigned long delayDuration = 5000;
bool isDelaying = false;
//Configuração por estados
enum State {
IDLE,
ROTATE_RIGHT,
DELAY_BETWEEN_ROTATIONS,
ROTATE_LEFT,
DELAY_AFTER_ROTATIONS,
START_CLEANING
};
State currentState = IDLE;
void setup() {
Serial.begin(9600);
pinMode(sensorPin, INPUT);
}
void startNonBlockingDelay() {
previousMillis = millis();
isDelaying = true;
}
void checkNonBlockingDelay() {
if (isDelaying && (millis() - previousMillis >= delayDuration)) {
isDelaying = false;
}
}
void loop() {
checkNonBlockingDelay();
//Possivel problema: animal entrar durante a rotação da caixa (improvável)
/*
Possivel configuração:
Delay por tempo personalizado
*/
switch (currentState) {
case IDLE:
if (digitalRead(sensorPin) == HIGH) {
Serial.println("Animal Detected");
clean = 0; //Dá set como sujo
}
else if (clean == 0)
{
Serial.println("Animal Left");
startNonBlockingDelay(); // Começa o delay de 10 segundos
currentState = START_CLEANING;
}
break;
case START_CLEANING:
if (!isDelaying){
currentState = ROTATE_RIGHT;
}
break;
case ROTATE_RIGHT:
Serial.println("Rotating Right");
myStepper.setSpeed(16);
myStepper.step(stepsPerRevolution);
startNonBlockingDelay(); // Começa o delay de 10 segundos
currentState = DELAY_BETWEEN_ROTATIONS;
break;
case DELAY_BETWEEN_ROTATIONS:
if (!isDelaying) {
currentState = ROTATE_LEFT;
}
break;
case ROTATE_LEFT:
Serial.println("Rotating Left");
myStepper.setSpeed(16);
myStepper.step(-stepsPerRevolution);
startNonBlockingDelay(); // Começa o delay de 10 segundos
currentState = IDLE;
clean = 1; // Dá set como limpo
break;
case DELAY_AFTER_ROTATIONS:
if (!isDelaying) {
currentState = ROTATE_LEFT;
}
break;
}
}