avnish aggarwal / Mbed 2 deprecated Book-PE_09-10_Metronomexx

Dependencies:   mbed

Fork of Book-PE_09-10_Metronomex by avnish aggarwal

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 /*Program Example 9.10: Metronome. Uses Ticker to set beat rate
00002  
00003  
00004                                                                     */            
00005 #include "mbed.h"
00006 #include <stdio.h>
00007 Serial pc(USBTX, USBRX);
00008 DigitalIn up_button(p15);
00009 DigitalIn down_button(p16);
00010 DigitalOut redled(LED1);             //displays the metronome beat
00011 Ticker beat_rate;  
00012 PwmOut spkr(p26);  
00013                
00014 void beat(void);
00015 float period (1);               
00016 float rate (60);                   
00017 
00018 int main() {
00019   pc.printf("\r\n");
00020   pc.printf("mbed metronome!\r\n");
00021   pc.printf("_______________\r\n");
00022   period = 1;
00023   redled = 1;        //diagnostic
00024   wait(.1);
00025   redled = 0;
00026   beat_rate.attach(&beat, period);  //initialises the beat rate 
00027   //main loop checks buttons, updates rates and displays
00028   while(1){
00029     if (up_button ==1)   //increase rate by 4
00030       rate = rate + 4;
00031     if (down_button ==1)   //decrease rate by 4
00032       rate = rate - 4;
00033     if (rate > 208)        //limit the maximum beat rate to 208
00034       rate = 208;
00035     if (rate < 40)      //limit the minimum beat rate to 40
00036       rate = 40;
00037     period = 60/rate;       //calculate the beat period
00038     pc.printf("metronome rate is   %f\r\n", rate);
00039     pc.printf("metronome period is %f\r\n", period);  
00040     wait (0.5);
00041   }
00042 }
00043 
00044   void beat() {                         //this is the metronome beat
00045     beat_rate.attach(&beat, period);    //update beat rate at this moment
00046 
00047     // speaker    
00048     spkr.period(1.0/5000);
00049     spkr=0.5;
00050     
00051     // led
00052     redled = 1;
00053     wait(.1);
00054     
00055     // turn off speaker and led
00056     redled = 0;
00057     spkr = 0.0;
00058   }
00059