-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhomealarm.ino
101 lines (90 loc) · 2.76 KB
/
homealarm.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/*
* Unlocked the door is
* As I lost my keys
* In my bed I cannot sleep
* I am scared like a sheep
* Dear Arduino, help me
* PIR sensor, I trust thee
* With my piezzo forces unite
* In case trespassers interrupt my night.
*/
// Pins
#define PIR_SENSOR 2
#define PIEZZO 4
#define LED LED_BUILTIN
// Alarm playback
typedef struct {
unsigned long duration;
unsigned int frequency;
} Note;
const unsigned int TEMPO = 120; // bpm
#define FREQ_PAUSE 0
#define FREQ_G4 392 // Hz
#define FREQ_Eb4 311
#define FREQ_Bb4 466
#define FREQ_Gb4 369
#define FREQ_Eb5 622
#define FREQ_D5 587
void fireAlarm();
bool ignoreFirstHighSignal = false;
void setup() {
pinMode(PIR_SENSOR, INPUT);
pinMode(PIEZZO, OUTPUT);
pinMode(LED, OUTPUT);
delay(8000); // enables one to setup the device before it triggers the alarm
if (digitalRead(PIR_SENSOR) == HIGH) {
// sometimes the sensor is high
// at the beginning
// for some period of time
ignoreFirstHighSignal = true;
}
}
void loop() {
int signalState = digitalRead(PIR_SENSOR);
if (ignoreFirstHighSignal && signalState == LOW) {
// first high signal has now gone low
// proceed as usual
ignoreFirstHighSignal = false;
} else if (signalState == HIGH) {
digitalWrite(LED, HIGH);
fireAlarm();
}
}
void fireAlarm() {
unsigned long beatDuration = (1000 * TEMPO) / 60; // milliseconds
Note melody[] = {
Note {beatDuration, FREQ_G4},
Note {2*beatDuration/3, FREQ_G4},
Note {beatDuration/3, FREQ_G4},
Note {beatDuration, FREQ_G4},
Note {2*beatDuration/3, FREQ_Eb4},
Note {beatDuration/3, FREQ_Bb4},
Note {beatDuration, FREQ_G4},
Note {2*beatDuration/3, FREQ_Eb4},
Note {beatDuration/3, FREQ_Bb4},
Note {beatDuration, FREQ_G4},
Note {beatDuration, FREQ_PAUSE},
Note {beatDuration, FREQ_D5},
Note {2*beatDuration/3, FREQ_D5},
Note {beatDuration/3, FREQ_D5},
Note {beatDuration, FREQ_D5},
Note {2*beatDuration/3, FREQ_Eb5},
Note {beatDuration/3, FREQ_Bb4},
Note {beatDuration, FREQ_Gb4},
Note {2*beatDuration/3, FREQ_Eb4},
Note {beatDuration/3, FREQ_Bb4},
Note {beatDuration, FREQ_G4},
Note {beatDuration, FREQ_PAUSE}
};
int melodyNotesCount = sizeof(melody)/sizeof(Note);
while (true) {
for (int i=0; i < melodyNotesCount; i++) {
if (melody[i].frequency == FREQ_PAUSE) {
noTone(PIEZZO);
} else {
tone(PIEZZO, melody[i].frequency, melody[i].duration);
}
delay(melody[i].duration);
}
}
}