/*
* This ESP32 code is created by esp32io.com
*
* This ESP32 code is released in the public domain
*
* For more detail (instruction and wiring diagram), visit https://esp32io.com/tutorials/esp32-motion-sensor-servo-motor
*/
#include <ESP32Servo.h>
#define MOTION_SENSOR_PIN 21 // ESP32 pin GPIO21 connected to motion sensor's pin
#define SERVO_PIN 26 // ESP32 pin GPIO26 connected to servo motor's pin
Servo servo; // create servo object to control a servo
// variables will change:
int angle = 0; // the current angle of servo motor
int lastMotionState; // the previous state of motion sensor
int currentMotionState; // the current state of motion sensor
void setup() {
Serial.begin(9600); // initialize serial
pinMode(MOTION_SENSOR_PIN, INPUT); // set ESP32 pin to input mode
servo.attach(SERVO_PIN); // attaches the servo on pin 9 to the servo object
servo.write(angle);
currentMotionState = digitalRead(MOTION_SENSOR_PIN);
}
void loop() {
lastMotionState = currentMotionState; // save the last state
currentMotionState = digitalRead(MOTION_SENSOR_PIN); // read new state
if (currentMotionState == LOW && lastMotionState == HIGH) { // pin state change: LOW -> HIGH
Serial.println("Motion detected!, rotating servo motor to 90°");
servo.write(90);
} else if (currentMotionState == HIGH && lastMotionState == LOW) { // pin state change: HIGH -> LOW
Serial.println("Motion stopped!, rotating servo motor to 0°");
servo.write(0);
}
}