-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMusicale.cpp
84 lines (70 loc) · 1.92 KB
/
Musicale.cpp
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
#include "Musicale.h"
#define DEBUG
#ifdef DEBUG
#define LED 13
#endif
Musicale::Musicale(int soundOutPin) {
_soundOutPin = soundOutPin;
_bpm = 120;
}
void Musicale::setBeatsPerMinute(int bpm) {
_bpm = bpm;
}
Musicale::Musicale(int soundOutPin, int bpm) {
_soundOutPin = soundOutPin;
_bpm = bpm;
}
void Musicale::begin() {
pinMode(_soundOutPin, OUTPUT);
}
int Musicale::hertzToDelay(float hertz) {
return (int) 1000.0 / hertz * 1000.0;
}
Musicale& Musicale::rest(float noteValue) {
delay(this->valueToDuration(noteValue) / 100.0);
// Serial.println("Rest.");
return *this;
}
Musicale& Musicale::playNote(float noteValue, float frequency) {
#ifdef DEBUG
Serial.println("playing note: ");
Serial.print(noteValue, DEC);
Serial.print('\t');
Serial.print(frequency, DEC);
Serial.print('\t');
Serial.print(valueToDuration(noteValue), DEC);
Serial.println("");
#endif
this->emitTone(this->valueToDuration(noteValue), this->hertzToDelay(frequency));
return *this;
}
float Musicale::valueToDuration(float noteValue) { // in µSec
return 100000 * 60 * noteValue / _bpm;
}
void Musicale::blink(int on, int off, int frequency) {
#ifdef DEBUG
digitalWrite(LED, HIGH);
emitTone(on, frequency);
digitalWrite(LED, LOW);
delay(off);
#endif
}
void Musicale::emitTone(float durationInMiliseconds, int frequencyInMicroseconds) { // Emit tone on pin _soundOutPin
#ifdef DEBUG
digitalWrite(LED, HIGH);
Serial.println("Emitting tone: ");
Serial.print(durationInMiliseconds * 10 / frequencyInMicroseconds, DEC);
Serial.print('\t');
Serial.print(frequencyInMicroseconds, DEC);
Serial.println("");
#endif
for (int i = 0; i < durationInMiliseconds * 10 / frequencyInMicroseconds; i++) {
digitalWrite(_soundOutPin, HIGH);
delayMicroseconds(frequencyInMicroseconds / 2);
digitalWrite(_soundOutPin, LOW);
delayMicroseconds(frequencyInMicroseconds / 2);
}
#ifdef DEBUG
digitalWrite(LED, LOW);
#endif
}