forked from leeseungcheol/ODROID-GO
-
Notifications
You must be signed in to change notification settings - Fork 35
/
Speaker.cpp
78 lines (65 loc) · 1.93 KB
/
Speaker.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
#include "Speaker.h"
SPEAKER::SPEAKER(void) {
_volume = 8;
}
void SPEAKER::begin() {
ledcSetup(TONE_PIN_CHANNEL, 0, 13); // PWM channel, frequency, resolution in bits
ledcAttachPin(SPEAKER_PIN, TONE_PIN_CHANNEL);
// digitalWrite(SPEAKER_PIN, 0);
pinMode(SPEAKER_ENABLE_PIN, OUTPUT);
digitalWrite(SPEAKER_ENABLE_PIN, HIGH); // IO25 drives PAM8304 'IN-' and '/SD' pins
setBeep(1000, 100); // standard beep is 1kHz for 0.1 seconds
}
void SPEAKER::end() {
ledcDetachPin(SPEAKER_PIN);
// digitalWrite(SPEAKER_ENABLE_PIN, LOW);
}
void SPEAKER::tone(uint16_t frequency) {
ledcWriteTone(TONE_PIN_CHANNEL, frequency);
}
void SPEAKER::tone(uint16_t frequency, uint32_t duration) {
tone(frequency);
_count = millis() + duration;
speaker_on = 1;
}
void SPEAKER::beep() {
tone(_beep_freq, _beep_duration);
}
void SPEAKER::setBeep(uint16_t frequency, uint16_t duration) {
_beep_freq = frequency;
_beep_duration = duration;
}
void SPEAKER::setVolume(uint8_t volume) {
_volume = 11 - volume;
}
void SPEAKER::mute() {
ledcWriteTone(TONE_PIN_CHANNEL, 0);
digitalWrite(SPEAKER_PIN, 0);
}
void SPEAKER::update() {
if(speaker_on) {
if(millis() > _count) {
speaker_on = 0;
mute();
}
}
}
void SPEAKER::write(uint8_t value) {
dacWrite(SPEAKER_PIN, value);
}
void SPEAKER::playMusic(const uint8_t* music_data, uint16_t sample_rate) {
uint32_t length = strlen((char*)music_data);
uint16_t delay_interval = ((uint32_t)1000000/sample_rate);
if(_volume != 11) {
for(int i=0; i<length; i++) {
dacWrite(SPEAKER_PIN, music_data[i]/_volume);
delayMicroseconds(delay_interval);
}
for(int t=music_data[length-1]/_volume; t>=0; t--) {
dacWrite(SPEAKER_PIN, t);
delay(2);
}
}
// ledcSetup(TONE_PIN_CHANNEL, 0, 13);
ledcAttachPin(SPEAKER_PIN, TONE_PIN_CHANNEL);
}