// Pin assignments for Exercise A & B
const int pirPin = 2;      // PIR sensor output pin
const int ldrPin = A0;     // LDR analog input pin
const int relayPin = 5;    // Relay Pin
const int buzzer1 = 6;      // Buzzer Pin

// Threshold values
int ldrThreshold = 300;    // Threshold for the LDR
int pirValue = 0;          // PIR sensor value

void setup() {
  Serial.begin(9600);          // Initialize serial communication
  pinMode(pirPin, INPUT);      // PIR sensor as input
  pinMode(relayPin, OUTPUT);   // Relay as output
  pinMode(buzzer1, OUTPUT);    // Buzzer as output (added)
  Serial.println("Program start.");
}

void loop() {
  // Read PIR sensor value
  pirValue = digitalRead(pirPin);
  
  // Read LDR value (light level)
  int ldrValue = analogRead(ldrPin);
  
  // Print LDR and PIR values (for debugging)
  Serial.print("LDR Value: ");
  Serial.print(ldrValue);
  Serial.print(" | PIR Value: ");
  Serial.print(pirValue );

  // If PIR detects motion and ambient light level is low, turn on the Relay and Buzzer
  if (pirValue == HIGH && ldrValue < ldrThreshold) {
    digitalWrite(relayPin, HIGH);  // Turn on the Relay
    tone(buzzer1, 1000);            // Turn on the Buzzer
    Serial.println(" RELAY ON | BUZZER ON");
  } 
  // If PIR detects motion but ambient light is above the threshold, turn off the Relay but keep the Buzzer ON
  else if (pirValue == HIGH && ldrValue >= ldrThreshold) {
    digitalWrite(relayPin, LOW);   // Turn off the Relay
    tone(buzzer1, 1000);            // Keep the Buzzer ON
    Serial.println(" RELAY OFF | BUZZER ON");
  }
  // DEFAULT STATE: No motion detected, turn off the Relay and Buzzer
  else {
    digitalWrite(relayPin, LOW);   // Turn off the Relay
    noTone(buzzer1);     // Turn off the Buzzer
    Serial.println(" RELAY OFF | BUZZER OFF");
  }
  delay(500);  // Short delay to avoid bouncing
}
NOCOMNCVCCGNDINLED1PWRRelay Module