#include <NewPing.h>
#define TRIGGER_PIN 2
#define ECHO_PIN 3
#define MAX_DISTANCE 200
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
int relay1Pin = 8;
int relay2Pin = 9;
int limitSwitch1Pin = 4;
int limitSwitch2Pin = 5;
int manualOpenButtonPin = 6; // Connect manual open button to this pin
int manualCloseButtonPin = 7; // Connect manual close button to this pin
void setup() {
pinMode(relay1Pin, OUTPUT);
pinMode(relay2Pin, OUTPUT);
pinMode(limitSwitch1Pin, INPUT_PULLUP);
pinMode(limitSwitch2Pin, INPUT_PULLUP);
pinMode(manualOpenButtonPin, INPUT_PULLUP);
pinMode(manualCloseButtonPin, INPUT_PULLUP);
}
void loop() {
bool gateClosed = (digitalRead(limitSwitch1Pin) == HIGH) && (digitalRead(limitSwitch2Pin) == HIGH);
// Check if manual open button is pressed
if (digitalRead(manualOpenButtonPin) == LOW) {
openGate();
while (digitalRead(manualOpenButtonPin) == LOW) {} // Wait for button release
}
// Check if manual close button is pressed
if (digitalRead(manualCloseButtonPin) == LOW) {
closeGate();
while (digitalRead(manualCloseButtonPin) == LOW) {} // Wait for button release
}
// Automatic mode
unsigned int distance = sonar.ping_cm();
if (distance < 10 && gateClosed) {
openGate();
}
}
void openGate() {
digitalWrite(relay1Pin, HIGH);
digitalWrite(relay2Pin, LOW);
delay(3000);
digitalWrite(relay1Pin, LOW);
digitalWrite(relay2Pin, LOW);
}
void closeGate() {
digitalWrite(relay1Pin, LOW);
digitalWrite(relay2Pin, HIGH);
delay(3000);
digitalWrite(relay1Pin, LOW);
digitalWrite(relay2Pin, LOW);
}