unsigned long relayStartTime = 0;
bool relayActive = false;
#define RelayPin 7
void setup() {
pinMode(RelayPin, OUTPUT);
}
void loop() {
// Turn on the relay if the distance is less than 50 and it's not already active
if (distance < 50 && !relayActive) {
digitalWrite(RelayPin, HIGH);
relayStartTime = millis(); // Record the time when the relay is turned on
relayActive = true;
}
// Turn off the relay after 45 seconds
if (relayActive && millis() - relayStartTime >= 45000) {
digitalWrite(RelayPin, LOW);
relayActive = false;
}
// The servo motor will rotate from 135 degree to 45 degree
for (int x=135; x >= 45; x-=2){
baseServo.write(x);
delay(50);
}
for (int x = 45; x <= 135; x+= 2){
baseServo.write(x);
delay(50);
}
}