// Define pins
const int pirPin = 2; // PIR motion sensor pin
const int soundPin = 8; // Piezo buzzer pin
// Variables
int pirState = LOW;
int lastPirState = LOW;
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Set PIR pin as input
pinMode(pirPin, INPUT);
// Set sound pin as output
pinMode(soundPin, OUTPUT);
}
void loop() {
// Read PIR sensor state
pirState = digitalRead(pirPin);
// If motion detected
if (pirState == HIGH && lastPirState == LOW) {
// Print message
Serial.println("Motion detected!");
// Play alarm
while (pirState == HIGH) {
// Pulse the buzzer
tone(soundPin, 500); // You can adjust the frequency as needed
delay(500); // Pulse duration
noTone(soundPin);
delay(300); // Delay between pulses
// Read PIR sensor state again
pirState = digitalRead(pirPin);
}
// Print message when motion stops
Serial.println("Motion stopped.");
// Update last state
lastPirState = LOW;
}
}