Guide
1/12/2018 mbed Starter Kit Experiment Guide - learn.sparkfun.com
https://learn.sparkfun.com/tutorials/mbed-starter-kit-experiment-guide/all 54/65
This demo is simple! We don’t need any libraries.
Navigate to the mbed.org, login, and navigate to your Compiler.
Create a new program with the “Blinky LED Hello World” template. Name it something like “pwm_song.”
Click on “main.cpp” in your project, remove the template code, and copy in the following code.
// Plays a familiar melody using PWM to the headphones. To find the frequencies
// of notes, see http://en.wikipedia.org/wiki/Piano_key_frequencies
// Based on the "speaker_demo_PWM" program by Jim Hamblen
#include "mbed.h"
#define VOLUME 0.01
#define BPM 100.0
PwmOut pwm_pin(p21);
// Plays a sound with the defined frequency, duration, and volume
void playNote(float frequency, float duration, float volume) {
pwm_pin.period(1.0/frequency);
pwm_pin = volume/2.0;
wait(duration);
pwm_pin = 0.0;
}
int main()
{
float beat_duration;
// Calculate duration of a quarter note from bpm
beat_duration = 60.0 / BPM;
// Loop forever
while(1) {
// First measure
playNote(391.995, (beat_duration - 0.1), VOLUME);
wait(0.1);
playNote(391.995, (beat_duration - 0.1), VOLUME);
wait(0.1);
playNote(391.995, (beat_duration - 0.1), VOLUME);
wait(0.1);
playNote(311.127, (0.75 * beat_duration), VOLUME);
playNote(466.164, (0.25 * beat_duration), VOLUME);
// Second measure
playNote(391.995, (beat_duration - 0.1), VOLUME);
wait(0.1);
playNote(311.127, (0.75 * beat_duration), VOLUME);
playNote(466.164, (0.25 * beat_duration), VOLUME);
playNote(391.995, ((2 * beat_duration) - 0.1), VOLUME);
wait(0.1);
// Third measure
playNote(587.330, (beat_duration - 0.1), VOLUME);
wait(0.1);
playNote(587.330, (beat_duration - 0.1), VOLUME);
wait(0.1);
playNote(587.330, (beat_duration - 0.1), VOLUME);
wait(0.1);
playNote(622.254, (0.75 * beat_duration), VOLUME);
playNote(466.164, (0.25 * beat_duration), VOLUME);
// Fourth measure
playNote(369.994, (beat_duration - 0.1), VOLUME);
wait(0.1);
playNote(311.127, (0.75 * beat_duration), VOLUME);
playNote(466.164, (0.25 * beat_duration), VOLUME);
playNote(391.995, ((2 * beat_duration) - 0.1), VOLUME);
wait(0.1);
}
}
Run
Compile the program and copy the downloaded file to the mbed. Connect a set of headphones or speakers to the audio jack. Press the mbed’s reset button, and
you should hear a tune come out of your headphones or speakers!
If the volume is too low, adjust the VOLUME constant in the program (try 0.1 or 1).