![](/media/cache/group/headphones.png.50x50_q85.jpg)
play sounds with a buzzer
Dependencies: mbed
main.cpp@1:1eefeb256849, 2016-05-12 (annotated)
- Committer:
- maclobdell
- Date:
- Thu May 12 17:34:03 2016 +0000
- Revision:
- 1:1eefeb256849
- Parent:
- 0:586507ee54a5
fixed play tone function to not set frequency as the period
Who changed what in which revision?
User | Revision | Line number | New contents of line |
---|---|---|---|
maclobdell | 0:586507ee54a5 | 1 | #include "mbed.h" // this tells us to load mbed related functions |
maclobdell | 0:586507ee54a5 | 2 | #include "tones.h" // list of all the tones and their frequencies |
maclobdell | 0:586507ee54a5 | 3 | |
maclobdell | 0:586507ee54a5 | 4 | InterruptIn btn2(SW2); // we create a variable 'btn2', use it as an in port |
maclobdell | 0:586507ee54a5 | 5 | InterruptIn btn3(SW3); // we create a variable 'btn3', use it as an in port |
maclobdell | 0:586507ee54a5 | 6 | |
maclobdell | 0:586507ee54a5 | 7 | PwmOut buzzer(D3); // our buzzer is a PWM output (pulse-width modulation) |
maclobdell | 0:586507ee54a5 | 8 | |
maclobdell | 0:586507ee54a5 | 9 | Timeout tone_timeout; //TimeOut = a interrupt to call a function after a specified delay |
maclobdell | 0:586507ee54a5 | 10 | |
maclobdell | 0:586507ee54a5 | 11 | static void silence() { |
maclobdell | 0:586507ee54a5 | 12 | buzzer.write(0.0f); // silence! |
maclobdell | 0:586507ee54a5 | 13 | } |
maclobdell | 0:586507ee54a5 | 14 | |
maclobdell | 0:586507ee54a5 | 15 | // this is our function that plays a tone. |
maclobdell | 0:586507ee54a5 | 16 | // Takes in a tone frequency, and after duration (in ms.) we stop playing again |
maclobdell | 0:586507ee54a5 | 17 | static void play_tone(int tone, int duration) { |
maclobdell | 1:1eefeb256849 | 18 | buzzer.period_us(1000000/(tone)); |
maclobdell | 0:586507ee54a5 | 19 | buzzer.write(0.10f); // 10% duty cycle, otherwise it's too loud |
maclobdell | 0:586507ee54a5 | 20 | |
maclobdell | 0:586507ee54a5 | 21 | // we wait for duration ms. and then call the silence function |
maclobdell | 0:586507ee54a5 | 22 | tone_timeout.attach_us(&silence, duration*1000); // setup tone_timeout to call silence after duration ms |
maclobdell | 0:586507ee54a5 | 23 | } |
maclobdell | 0:586507ee54a5 | 24 | |
maclobdell | 0:586507ee54a5 | 25 | // YOUR CODE HERE |
maclobdell | 0:586507ee54a5 | 26 | |
maclobdell | 0:586507ee54a5 | 27 | // this code runs when the microcontroller starts up |
maclobdell | 0:586507ee54a5 | 28 | int main() { |
maclobdell | 0:586507ee54a5 | 29 | btn2.fall(play_note1); |
maclobdell | 0:586507ee54a5 | 30 | btn3.fall(play_note2); |
maclobdell | 0:586507ee54a5 | 31 | } |