#include <SoftwareSerial.h>
const int trigPin = 5;
const int echoPin = 6;
const int buzzerPin = 3;
const int ledPin = 4;
const int detectionThreshold = 50; // المسافة القصوى (سم)
const unsigned long inactivityLimit = 10 * 1000UL; //
const unsigned long messageInterval = 1000;
long duration;
int distance;
unsigned long lastDetectionTime = 0;
unsigned long lastMessageTime = 0;
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 – Stay hydrated”);
Serial.println(“System initialized”);
lastDetectionTime = millis();
lastMessageTime = millis();
}
void loop() {
// قياس المسافة
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2;
unsigned long currentTime = millis();
// عند الاقتراب من الحساس
if (distance < detectionThreshold) {
lastDetectionTime = currentTime;
alertActive = false;
digitalWrite(buzzerPin, LOW);
digitalWrite(ledPin, LOW);
buzzerState = false;
ledState = false;
Serial.println(“Object detected: Resetting alert”);
Serial.println(“LED OFF”);
Serial.println(“Buzzer OFF”);
}
unsigned long timeInactive = currentTime – lastDetectionTime;
// بعد 10 دقائق بدون اقتراب
if (timeInactive >= inactivityLimit) {
if (!alertActive) {
bluetooth.println(“⚠️ Reminder: Please visit the faucet.”);
bluetooth.println(“🛑 Risk of heat stress. Stay hydrated.”);
Serial.println(“Sending hydration reminder…”);
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 (currentTime – lastMessageTime >= messageInterval) {
unsigned long remaining = (inactivityLimit – timeInactive) / 1000;
int mins = remaining / 60;
int secs = remaining % 60;
bluetooth.print(“⏳ “);
bluetooth.print(mins);
bluetooth.print(“m “);
bluetooth.print(secs);
bluetooth.println(“s left before reminder”);
Serial.print(“Remaining time: “);
Serial.print(mins);
Serial.print(“m “);
Serial.print(secs);
Serial.println(“s”);
lastMessageTime = currentTime;
}
// تأكد من إطفاء التنبيهات
if (ledState || buzzerState) {
digitalWrite(ledPin, LOW);
digitalWrite(buzzerPin, LOW);
ledState = false;
buzzerState = false;
Serial.println(“Deactivating LED and Buzzer”);
}
}
delay(100);
}