Phase 2: Electronics Interaction
FINAL DAPHNE CODE WORKING:
#include <ESP32Servo.h>
const int servoPin = 2; // GPIO 4 (ensure this matches your hardware)
const int trigPin = 4; // GPIO 3 (ensure this matches your hardware)
const int echoPin = 3; // GPIO 2 (ensure this matches your hardware)
float duration; // variable to store pulse duration
float distanceCM; // variable to store distance in CM
float distanceIN; // variable to store distance in IN
Servo myServo;
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
myServo.attach(servoPin);
}
void loop() {
// start with a clean signal
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// send trigger signal
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// return pulse duration in microseconds
duration = pulseIn(echoPin, HIGH);
// convert m/s to cm/microseconds (343 m/s = 0.034 cm/microsecond)
distanceCM = (duration * 0.034) / 2;
// convert to inches (1 inch = 2.54 cm)
distanceIN = distanceCM / 2.54;
// If the distance is greater than 70 cm, ignore it and don't print to Serial Monitor
if (distanceCM > 200) {
return; // Skip this loop iteration and don't process the servo or print to Serial Monitor
}
// print distance to Serial Monitor only if it's <= 70 cm
Serial.print("Distance: ");
Serial.print(distanceCM);
Serial.print(" cm | ");
Serial.print(distanceIN);
Serial.println(" in");
// Map the delay time based on the distance (closer = shorter delay)
int delayTime = map(distanceCM, 2, 60, 10, 100); // Slower overall delay range
delay(100); // fixed short delay before reading again
// If object is less than or equal to 60 cm, move servo with dynamic delay
if (distanceCM <= 60) {
// Sweep servo from 0 to 180 degrees with dynamic delay based on distance
for (int pos = 0; pos <= 180; pos += 5) {
myServo.write(pos); // move the servo to the position
delay(map(distanceCM, 2, 60, 10, 100)); // dynamic delay for smooth movement
}
// Sweep servo back from 180 to 0 degrees with dynamic delay based on distance
for (int pos = 180; pos >= 0; pos -= 5) {
myServo.write(pos); // move the servo to the position
delay(map(distanceCM, 2, 60, 10, 100)); // dynamic delay for smooth movement
}
}
// If object is farther than 60 cm, move the servo back and forth very slowly
else {
// Gradual movement for objects greater than 70 cm
// Move servo gradually from 0 to 180 degrees with small increments
for (int pos = 0; pos <= 180; pos += 5) { // Small increments for smooth gradual movement
myServo.write(pos); // move the servo to the position
delay(100); // Longer delay for slow movement
}
// Move servo gradually back from 180 to 0 degrees with small increments
for (int pos = 180; pos >= 0; pos -= 5) { // Small increments for smooth gradual movement
myServo.write(pos); // move the servo to the position
delay(100); // Longer delay for slow movement
}
}
}