-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpir_and_buzzer.ino
63 lines (55 loc) · 1.45 KB
/
pir_and_buzzer.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include "pitches.h"
int led = 13; //led pin
int inputPir = 2; //input pin for PIR sensor
int pirState = LOW; //no motion at start
int temp = 0; //variable for reading pin status
int melody[] = {NOTE_C4, NOTE_G3,NOTE_G3, NOTE_A3, NOTE_G3,0, NOTE_B3, NOTE_C4};
// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = {4, 8, 8, 4,4,4,4,4 };
void setup()
{
pinMode(led, OUTPUT);
pinMode(inputPir, INPUT);
Serial.begin(9600);
}
void loop()//loop
{
temp = digitalRead(inputPir); //read input PIR value
if(temp == HIGH)
{
digitalWrite(led, HIGH); //turn LED on
if (pirState == LOW)
{
song(); //play melody
Serial.println("Motion Detected");
pirState = HIGH;
}
}
else
{
digitalWrite(led, LOW); //turn LED off
if(pirState==HIGH)
{
Serial.println("Motion Ended");
pirState=LOW;
}
}
}
//from arduino library
void song()
{
// iterate over the notes of the melody:
for (int thisNote = 0; thisNote < 8; thisNote++) {
// to calculate the note duration, take one second
// divided by the note type.
//e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
int noteDuration = 1000/noteDurations[thisNote];
tone(8, melody[thisNote],noteDuration);
// to distinguish the notes, set a minimum time between them.
// the note's duration + 30% seems to work well:
int pauseBetweenNotes = noteDuration * 1.30;
delay(pauseBetweenNotes);
// stop the tone playing:
noTone(8);
}
}