#include <Arduino.h>
#include <Wire.h>
#include <AccelStepper.h>
#define ECHO_PIN 34
#define TRIG_PIN 32
int LED_BUILTIN = 23;
const int ldrPin = A0;
const int pirPin = 14;
const int motorStep = 2;
const int motorDir = 15;
AccelStepper stepper(AccelStepper::FULL4WIRE, motorStep, 13, 12, 14);
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println("Hello, ESP32!");
pinMode(LED_BUILTIN, OUTPUT);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(ldrPin, INPUT);
pinMode(pirPin, INPUT);
pinMode(motorStep, OUTPUT);
pinMode(motorDir, OUTPUT);
stepper.setMaxSpeed(2000);
stepper.setAcceleration(1000);
}
float readDistanceCM() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
int duration = pulseIn(ECHO_PIN, HIGH);
return duration * 0.034 / 2;
}
void loop() {
// put your main code here, to run repeatedly:
float distance = readDistanceCM();
bool isNearby = distance > 10;
digitalWrite(LED_BUILTIN, isNearby);
Serial.print("Measured distance: ");
Serial.println(readDistanceCM());
delay(100); // this speeds up the simulation
// Read values from LDR and PIR
int ldrValue = analogRead(ldrPin);
int pirValue = digitalRead(pirPin);
// Print sensor values to the serial monitor
Serial.print("LDR Value: ");
Serial.println(ldrValue);
Serial.print("PIR Value: ");
Serial.println(pirValue);
// Control the stepper motor based on sensor readings
if (ldrValue < 500 && pirValue == HIGH) {
// If it's dark and motion is detected, rotate the stepper motor
stepper.moveTo(1000);
stepper.run();
} else {
// If conditions are not met, stop the stepper motor
stepper.stop();
stepper.setCurrentPosition(0);
}
// Wait for a short time before taking the next readings
delay(1000);
}