#include <DHT.h>
#include <Adafruit_SSD1306.h>
#define led_hijau 11
#define led_kuning 12
#define led_merah 13

#define TRIG_PIN  3
#define ECHO_PIN  4
float duration, distance;
#define DISTANCE_THRESHOLD 50 

#define buzzer 7

DHT dht(2, DHT22);
Adafruit_SSD1306 layar(128, 64, &Wire, -1);

void updateDisplay(char kondisi){
  layar.clearDisplay();
  layar.setTextColor(1);
  layar.setCursor(5, 4);
  if (kondisi == 'r')layar.print("AIR PENUH"); 
  if (kondisi == 'c') layar.print("AIR CUKUP"); 
  if (kondisi == 'p') layar.print("AIR KOSONG");
  layar.display();
}
void setup() {
  Serial.begin(9600);
  pinMode(led_merah, OUTPUT);
  pinMode(led_kuning, OUTPUT);
  pinMode(led_hijau, OUTPUT);
  pinMode(buzzer, OUTPUT);

  pinMode(TRIG_PIN, OUTPUT); 
  pinMode(ECHO_PIN, INPUT);

  layar.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  dht.begin();
}

void loop() {
  float t = dht.readTemperature();\

  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);
  duration = pulseIn(ECHO_PIN, HIGH);
  distance = 0.017 * duration;

  if (distance >= 50 || t < 35 ){
    digitalWrite(led_hijau, 1);
    digitalWrite(led_merah, 0);
    digitalWrite(led_kuning, 0);
    updateDisplay('r');
    tone(buzzer, 500);
    delay(2000);
    noTone(buzzer);
  }
  else if (distance <= 5){
    digitalWrite(led_hijau, 0);
    digitalWrite(led_merah, 1);
    digitalWrite(led_kuning, 0);
    updateDisplay('p');
    tone(buzzer, 500);
    
  }
  else {
    digitalWrite(led_hijau, 0);
    digitalWrite(led_merah, 0);
    digitalWrite(led_kuning, 1);
    updateDisplay('c');
    noTone(buzzer);
  }

  Serial.print("Ketinggian Air: ");
  Serial.print(distance);
  Serial.println("cm");
  Serial.print("Temperatur : ");
  Serial.println(t);
  delay(500);
}