#include <Arduino.h>
#include <AccelStepper.h>
#define LED_PIN 2 // LED
#define PIR_PIN 4 // sensor PIR
#define BUTTON_PIN 23 // botão
#define MOTOR_X_STEP_PIN 5
#define MOTOR_X_DIR_PIN 18
#define MOTOR_Y_STEP_PIN 19
#define MOTOR_Y_DIR_PIN 21
volatile bool motionDetected = false;
volatile bool resetRequested = false;
unsigned long ledOnTime = 0;
bool ledState = LOW;
bool ledBlinking = false;
unsigned long ledBlinkDuration = 20000;
unsigned long ledBlinkInterval = 2000;
AccelStepper motorX(AccelStepper::DRIVER, MOTOR_X_STEP_PIN, MOTOR_X_DIR_PIN);
AccelStepper motorY(AccelStepper::DRIVER, MOTOR_Y_STEP_PIN, MOTOR_Y_DIR_PIN);
void IRAM_ATTR handlePIR() {
motionDetected = true;
}
void IRAM_ATTR handleButton() {
resetRequested = true;
}
void setup() {
pinMode(LED_PIN, OUTPUT);
pinMode(PIR_PIN, INPUT);
pinMode(BUTTON_PIN, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(PIR_PIN), handlePIR, RISING);
attachInterrupt(digitalPinToInterrupt(BUTTON_PIN), handleButton, FALLING);
// Configura os motores de passo
motorX.setMaxSpeed(1000);
motorX.setAcceleration(500);
motorY.setMaxSpeed(1000);
motorY.setAcceleration(500);
}
void loop() {
if (resetRequested) {
digitalWrite(LED_PIN, LOW);
motorX.stop();
motorY.stop();
motorX.setCurrentPosition(0);
motorY.setCurrentPosition(0);
resetRequested = false;
ledBlinking = false;
return;
}
if (motionDetected) {
motionDetected = false;
ledOnTime = millis();
ledBlinking = true;
unsigned long motorDelayStart = millis();
while (millis() - motorDelayStart < 20000) {
if (ledBlinking) {
unsigned long currentMillis = millis();
if (currentMillis - ledOnTime >= ledBlinkInterval) {
ledState = !ledState;
digitalWrite(LED_PIN, ledState);
ledOnTime = currentMillis;
}
}
}
digitalWrite(LED_PIN, LOW);
motorX.moveTo(200);
motorY.moveTo(200);
while (motorX.isRunning() || motorY.isRunning()) {
motorX.run();
motorY.run();
}
ledBlinking = false;
}
motorX.run();
motorY.run();
}