Skip to content

Commit 6191791

Browse files
committed
First implementation of Tone
1 parent f587c9e commit 6191791

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

cores/arduino/Tone.cpp

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
#include "Arduino.h"
2+
#include "mbed.h"
3+
4+
class Tone {
5+
mbed::DigitalOut *pin;
6+
mbed::Timer timer;
7+
mbed::Timeout timeout; // calls a callback once when a timeout expires
8+
mbed::Ticker ticker; // calls a callback repeatedly with a timeout
9+
uint32_t frequency;
10+
uint32_t duration;
11+
12+
public:
13+
Tone(PinName _pin, unsigned int frequency, unsigned long duration) : frequency(frequency), duration(duration) {
14+
pin = new mbed::DigitalOut(_pin);
15+
}
16+
17+
~Tone() {
18+
stop();
19+
timeout.detach();
20+
delete pin;
21+
}
22+
23+
void start(void) {
24+
ticker.attach(mbed::callback(this, &Tone::toggle), 0.5f / float(frequency));
25+
start_timeout();
26+
}
27+
28+
void toggle() {
29+
*pin = !*pin;
30+
}
31+
32+
void stop(void) {
33+
ticker.detach();
34+
pin = 0;
35+
}
36+
37+
void start_timeout(void) {
38+
timeout.attach(mbed::callback(this, &Tone::stop), duration/1000.0f);
39+
}
40+
};
41+
42+
Tone* active_tone = NULL;
43+
44+
void tone(uint8_t pin, unsigned int frequency, unsigned long duration) {
45+
if (active_tone) {
46+
delete active_tone;
47+
}
48+
Tone* t = new Tone(digitalPinToPinName(pin), frequency, duration);
49+
t->start();
50+
active_tone = t;
51+
};
52+
53+
void noTone(uint8_t pin) {
54+
if (active_tone) {
55+
active_tone->stop();
56+
delete active_tone;
57+
active_tone = NULL;
58+
}
59+
};

0 commit comments

Comments
 (0)