int inputPin = 2; // Pin for the motion sensor input
int pirState = LOW; // Initial state for motion detection
int val = 0; // Variable to store the input state
int pinSpeaker = 9; // Pin connected to the buzzer
int ledPin = 10; // LED pin
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(inputPin, INPUT);
pinMode(pinSpeaker, OUTPUT);
Serial.begin(9600);
}
void loop() {
val = digitalRead(inputPin);
if (val == HIGH) { // If motion is detected
digitalWrite(ledPin, HIGH); // Turn on LED
delay(150); // Short delay
if (pirState == LOW) {
Serial.println("Metal Detected!");
pirState = HIGH;
// Play a tone when motion is detected
playTone(100, 5); // Play tone for 100ms with a frequency of 5Hz
}
} else {
digitalWrite(ledPin, LOW); // Turn off LED
delay(300); // Longer delay
if (pirState == HIGH) {
Serial.println("No Metal Detected!");
pirState = LOW;
}
}
}
void playTone(long duration, int freq) {
duration *= 1000;
int period = (1.0 / freq) * 1000000;
long elapsed_time = 0;
while (elapsed_time < duration) {
digitalWrite(pinSpeaker, HIGH);
delayMicroseconds(period / 2);
digitalWrite(pinSpeaker, LOW);
delayMicroseconds(period / 2);
elapsed_time += (period);
}
}