Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
2.8 kB
1
Indexable
Never
// Menentukan nomor pin
const int TRIGPIN = D3;
const int ECHOPIN = D4;
const int GREEN_LED_PIN = D6;
const int RED_LED_PIN = D5;
const int YELLOW_LED_PIN = D7;
const int BUZZER_PIN = D8;

// Menentukan jarak
const int DISTANCE_THRESHOLD_1 = 5;   // 5 cm jarak botol

// Menentukan waktu pengingat
const long BUZZER_DELAY = 30000;   // pengingat tiap 30 detik 
const int BLINK_INTERVAL = 500;    // cepat kedip led kuning

unsigned long detectionTime = 0;
bool objectDetected = false;
bool buzzerActive = false;
bool ledState = false;
unsigned long previousMillis = 0;

void setup() {
Serial.begin(9600);
pinMode(TRIGPIN, OUTPUT);
pinMode(ECHOPIN, INPUT);
pinMode(GREEN_LED_PIN, OUTPUT);
pinMode(RED_LED_PIN, OUTPUT);
pinMode(YELLOW_LED_PIN, OUTPUT);
pinMode(BUZZER_PIN, OUTPUT);

digitalWrite(GREEN_LED_PIN, LOW);
digitalWrite(RED_LED_PIN, LOW);
digitalWrite(YELLOW_LED_PIN, LOW);
digitalWrite(BUZZER_PIN, LOW);

void loop() {
digitalWrite(TRIGPIN, LOW);  
delayMicroseconds(2); 
digitalWrite(TRIGPIN, HIGH);
delayMicroseconds(10); 
digitalWrite(TRIGPIN, LOW);

long timer = pulseIn(ECHOPIN, HIGH);
long jarak = timer / 58;
Serial.print("Jarak: ");
Serial.print(jarak);
Serial.println(" cm");

unsigned long currentMillis = millis();

if (jarak > 0 && jarak < DISTANCE_THRESHOLD_1) {
// Kondisi ketika botol air jarak nya lebih dekat dari 5 cm
   if (!objectDetected) {
      detectionTime = millis();
      objectDetected = true;
    }

// Buzzer aktif dengan delay 30 detik
    if (objectDetected && !buzzerActive && (currentMillis - detectionTime >= BUZZER_DELAY)) {
      buzzerActive = true;
      digitalWrite(BUZZER_PIN, HIGH);
    }

// ketika buzzer aktif, LED hijau mati
    if (buzzerActive) {
      digitalWrite(GREEN_LED_PIN, LOW);
    } else {
      digitalWrite(GREEN_LED_PIN, HIGH);
    }

    digitalWrite(RED_LED_PIN, LOW);
  } else if (jarak > DISTANCE_THRESHOLD_1 || jarak == 0) {
// Kondisi ketika botol air jarak nya lebih jauh dari 5 cm atau tidak terdeteksi
    digitalWrite(GREEN_LED_PIN, LOW);
    digitalWrite(RED_LED_PIN, HIGH);
    digitalWrite(YELLOW_LED_PIN, LOW);
    buzzerActive = false;
    objectDetected = false;
    digitalWrite(BUZZER_PIN, LOW);
  } else {
    digitalWrite(GREEN_LED_PIN, LOW);
    digitalWrite(RED_LED_PIN, LOW);
    digitalWrite(YELLOW_LED_PIN, LOW);
  }

// Ketika buzzer aktif, LED kuning berkedip
  if (buzzerActive) {
    if (currentMillis - previousMillis >= BLINK_INTERVAL) {
      previousMillis = currentMillis;
      ledState = !ledState;
      digitalWrite(YELLOW_LED_PIN, ledState ? HIGH : LOW);
    }
  } else {
    digitalWrite(YELLOW_LED_PIN, LOW); // Ketika buzzer mati, LED kuning mati
  }

  delay(50); // Delay kecil untuk menstabilkan pembacaan sensor
}
Leave a Comment