forked from MrRonne/lab2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuzzer.h
75 lines (61 loc) · 1.41 KB
/
buzzer.h
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
#pragma once
#define BUZZER_NOTE_DURATION 100
#define NOTE_SILENCE 0
class Buzzer
{
public:
Buzzer(int _pin)
{
pin = _pin;
pinMode(pin, OUTPUT);
isEnabled = false;
currentNote = 0;
noteStartedMs = 0;
notes = 0;
durations = 0;
melodyLength = 0;
}
void turnSoundOn()
{
isEnabled = true;
currentNote = 0;
noteStartedMs = 0;
}
void turnSoundOff()
{
isEnabled = false;
currentNote = 0;
noteStartedMs = 0;
noTone(pin);
}
void setMelody(int _notes[], double _durations[], int _melodyLength)
{
notes = _notes;
durations = _durations;
melodyLength = _melodyLength;
}
void playSound()
{
if (!isEnabled)
return;
unsigned long duration = round(BUZZER_NOTE_DURATION*durations[currentNote]);
if ((millis() - noteStartedMs) > duration)
{
int note = notes[currentNote];
if (note == NOTE_SILENCE)
noTone(pin);
else
tone(pin, notes[currentNote]);
noteStartedMs = millis();
currentNote = (currentNote + 1)%melodyLength;
}
}
private:
int pin;
bool isEnabled;
int currentNote;
unsigned long noteStartedMs;
int* notes;
double* durations;
int melodyLength;
};