-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathautomatic_gate.ino
More file actions
88 lines (75 loc) · 2.19 KB
/
automatic_gate.ino
File metadata and controls
88 lines (75 loc) · 2.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
//Author: Mugisha Samuella
#include <Servo.h>
// Pin definitions
const int triggerPin = 2;
const int echoPin = 3;
const int redLedAnodePin = 4;
const int redLedCathodePin = 8;
const int blueLedPin = 5;
const int blueLedCathodePin = 7;
const int servoPin = 6;
const int buzzerPin = 12;
// Constants
const float thresholdDistance = 50.0; // cm
const int closedAngle = 0;
const int openAngle = 90;
const unsigned long closeDelay = 5000; // 5 seconds
// Global state
Servo myServo;
bool isOpen = false;
unsigned long lastDetectionTime = 0;
void setup() {
// Sensor pins
pinMode(triggerPin, OUTPUT);
pinMode(echoPin, INPUT);
// LEDs
pinMode(redLedAnodePin, OUTPUT);
pinMode(redLedCathodePin, OUTPUT);
digitalWrite(redLedCathodePin, LOW); // Act as GND
pinMode(blueLedPin, OUTPUT);
pinMode(blueLedCathodePin, OUTPUT);
digitalWrite(blueLedCathodePin, LOW); // Act as GND
// Buzzer
pinMode(buzzerPin, OUTPUT);
// Servo
myServo.attach(servoPin);
myServo.write(closedAngle); // Start closed
// Initial LED & buzzer state
digitalWrite(redLedAnodePin, HIGH); // Red ON
digitalWrite(blueLedPin, LOW); // Blue OFF
digitalWrite(buzzerPin, LOW); // Buzzer OFF
}
float getDistance() {
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
long duration = pulseIn(echoPin, HIGH);
return duration / 58.0; // Convert to cm
}
void loop() {
float distance = getDistance();
bool objectDetected = (distance < thresholdDistance);
if (objectDetected) {
if (!isOpen) {
// Open gate
myServo.write(openAngle);
isOpen = true;
digitalWrite(redLedAnodePin, LOW); // Red OFF
digitalWrite(blueLedPin, HIGH); // Blue ON
}
digitalWrite(buzzerPin, HIGH); // Buzzer ON
lastDetectionTime = millis();
} else {
if (isOpen && (millis() - lastDetectionTime > closeDelay)) {
// Close gate
myServo.write(closedAngle);
isOpen = false;
digitalWrite(redLedAnodePin, HIGH); // Red ON
digitalWrite(blueLedPin, LOW); // Blue OFF
digitalWrite(buzzerPin, LOW); // Buzzer OFF
}
}
delay(100);
}