#include <Arduino.h>
#include <LiquidCrystal_I2C.h>

#define TRIG_PIN PA_1
#define ECHO_PIN PA_4
#define LED_PIN PA_6
#define BUZZER_PIN PA_7

#define MAX_DISTANCE 200 // Maximum distance in centimeters
#define TRIGGER_THRESHOLD 20 // Threshold distance to trigger LED and buzzer

LiquidCrystal_I2C lcd(0x27, D14, D15);
unsigned long previousMillis = 0;
unsigned long interval = 1000; // Update interval: 1 second

void setup() {
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  pinMode(LED_PIN, OUTPUT);
  pinMode(BUZZER_PIN, OUTPUT);
  
  lcd.begin(16, 2);
  lcd.backlight();
  lcd.setCursor(0, 0);
  lcd.print("Distance: ");
}

void loop() {
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;
    
    // Simulate distance measurement
    unsigned int distance = simulateDistance();
    
    // Display distance on LCD
    lcd.setCursor(0, 1);
    lcd.print("            "); // Clear previous distance value
    lcd.setCursor(0, 1);
    lcd.print(distance);
    lcd.print(" cm");
    
    // Check if the distance is below threshold
    if (distance < TRIGGER_THRESHOLD) {
      // Activate LED and buzzer
      digitalWrite(LED_PIN, HIGH);
      digitalWrite(BUZZER_PIN, HIGH);
    } else {
      // Turn off LED and buzzer
      digitalWrite(LED_PIN, LOW);
      digitalWrite(BUZZER_PIN, LOW);
    }
  }
}

// Function to simulate distance measurement
unsigned int simulateDistance() {
  static unsigned int distance = MAX_DISTANCE; // Start with maximum distance
  if (distance > 0)
    distance -= 2; // Simulate object getting closer
  return distance;
}