#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <OneWire.h>
#include <DallasTemperature.h>

LiquidCrystal_I2C lcd(0x27, 16, 2);  // Alamat I2C sesuaikan dengan alamat modul Anda

OneWire oneWire(4);  // Gunakan pin digital 4 untuk sensor suhu DS18B20
DallasTemperature sensors(&oneWire);

const int trigPin = 3;  // Pin Trig sensor ultrasonik
const int echoPin = 2;  // Pin Echo sensor ultrasonik
unsigned long parkingStartTime = 0;

void setup() {
  lcd.init();
  lcd.backlight();
  lcd.setCursor(0, 0);
  lcd.print("Kendaraan: Tidak");
  lcd.setCursor(0, 1);
  lcd.print("Durasi: 0 s");
  sensors.begin();
}

void loop() {
  // Baca suhu
  sensors.requestTemperatures();
  float temperature = sensors.getTempCByIndex(0);

  // Baca jarak
  long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration / 2) / 29.1;  // Konversi ke centimeter

  // Tampilkan suhu di LCD
  lcd.setCursor(0, 0);
  lcd.print("Suhu: ");
  lcd.print(temperature);
  lcd.print("C");

  // Deteksi kendaraan
  if (distance < 20) {
    if (parkingStartTime == 0) {
      parkingStartTime = millis();
      lcd.setCursor(0, 1);
      lcd.print("Kendaraan: Ya");
    }
  } else {
    if (parkingStartTime != 0) {
      unsigned long parkingDuration = (millis() - parkingStartTime) / 1000;
      lcd.setCursor(0, 1);
      lcd.print("Kendaraan: Tidak");
      lcd.setCursor(0, 1);
      lcd.print("Durasi: ");
      lcd.print(parkingDuration);
      lcd.print(" s");
      parkingStartTime = 0;
    }
  }
}