Skip to content
This repository was archived by the owner on Apr 16, 2021. It is now read-only.

Commit 23f01a6

Browse files
committed
First implementation of Tone
1 parent a89067f commit 23f01a6

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

cores/arduino/Tone.cpp

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

0 commit comments

Comments
 (0)