#include <SoftwareSerial.h>
const int trigPin = 5;
const int echoPin = 6;
const int buzzerPin = 3;
const int ledPin = 4;
const int dangerThreshold = 50; // المسافة الحرجة (سم)
long duration;
int distance;
bool alertActive = false;
unsigned long lastLedToggle = 0;
bool ledState = false;
unsigned long lastBuzzerToggle = 0;
bool buzzerState = false;
SoftwareSerial bluetooth(10, 11); // RX, TX
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(buzzerPin, OUTPUT);
pinMode(ledPin, OUTPUT);
bluetooth.begin(9600);
Serial.begin(9600);
bluetooth.println(“🔒 System ready – Rooftop child safety active”);
Serial.println(“System initialized – monitoring area”);
}
void loop() {
// قياس المسافة
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2;
Serial.print(“Measured distance: “);
Serial.print(distance);
Serial.println(” cm”);
unsigned long currentTime = millis();
if (distance > 0 && distance < dangerThreshold) {
if (!alertActive) {
bluetooth.println(“🚨 ALERT: Movement detected near the rooftop entrance!”);
Serial.println(“⚠️ Child detected near entrance! Triggering alarm…”);
alertActive = true;
}
// وميض الليد كل 0.5 ثانية
if (currentTime – lastLedToggle >= 500) {
ledState = !ledState;
digitalWrite(ledPin, ledState);
Serial.print(“LED “);
Serial.println(ledState ? “ON” : “OFF”);
lastLedToggle = currentTime;
}
// وميض البازر كل ثانية
if (currentTime – lastBuzzerToggle >= 1000) {
buzzerState = !buzzerState;
digitalWrite(buzzerPin, buzzerState);
Serial.print(“Buzzer “);
Serial.println(buzzerState ? “ON” : “OFF”);
lastBuzzerToggle = currentTime;
}
} else {
if (alertActive) {
bluetooth.println(“✅ Safe: No presence near rooftop entrance”);
Serial.println(“Area is now safe. Stopping alerts.”);
alertActive = false;
}
// إيقاف الإنذارات
digitalWrite(ledPin, LOW);
digitalWrite(buzzerPin, LOW);
ledState = false;
buzzerState = false;
}
delay(100);
}