NuMaker PWM0 play notes (to speaker)

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 //NuMaker-PFM-NUC472 PWM0 output note to a speaker
00002 #include "mbed.h"
00003 
00004 #define _C5   523  // C5      =  523.25Hz
00005 #define _D5   587  // D5      =  587.33Hz
00006 #define _E5   659  // E5      =  659.26Hz
00007 #define _F5   698  // F5      =  698.46Hz
00008 #define _G5   784  // G5      =  783.99Hz
00009 #define _A5   880  // A5      =  880.00Hz
00010 #define _B5   988  // B5      =  987.77Hz
00011 #define _C6   1046 // C6      = 1046.50Hz
00012 #define _D6   1175 // D6      = 1174.66Hz
00013 #define _E6   1319 // E6      = 1318.51Hz
00014 #define _F6   1397 // F6      = 1396.91Hz
00015 #define _G6   1568 // G6      = 1567.98Hz
00016 #define _A6   1760 // A6      = 1760.00Hz
00017 #define _B6   1976 // B6      = 1975.53Hz
00018 
00019 /* NOTE: Most targets has UNO D2 for PWM. Check it for supporting new targets */
00020 PwmOut pwm0(D2);
00021 
00022 
00023 int main()
00024 {
00025         int i =0;
00026         int note[15] = { // array of notes
00027         _C5, _D5, _E5, _F5, _G5, _A5, _B5,         
00028         _C6, _D6, _E6, _F6, _G6, _A6, _B6};
00029 #ifdef MBED_MAJOR_VERSION
00030     printf("Mbed OS version %d.%d.%d\r\n\n", MBED_MAJOR_VERSION, MBED_MINOR_VERSION, MBED_PATCH_VERSION);
00031 #endif
00032         
00033         for (i=0; i<14; i++) {
00034             pwm0.period_us(1000000/note[i]);       // set period per note
00035             pwm0.pulsewidth_us(1000000/note[i]/2); // set duty cycle to 50%
00036 #if MBED_MAJOR_VERSION >= 6
00037         ThisThread::sleep_for(100);
00038 #else
00039             Thread::wait(100);
00040 #endif
00041         }
00042         pwm0.pulsewidth_us(0); // set dutycycle = 0% to stop
00043 }