Rob Toulson / Mbed 2 deprecated PE_09-10_Metronome

Dependencies:   mbed

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 #include "mbed.h"
00004 #include <stdio.h>
00005 Serial pc(USBTX, USBRX);
00006 DigitalIn up_button(p5);
00007 DigitalIn down_button(p6);
00008 DigitalOut redled(p19);             //displays the metronome beat
00009 Ticker beat_rate;                   //define a Ticker, with name “beat_rate”
00010 void beat(void);
00011 float period (0.5);              //metronome period in seconds, inital value 0.5
00012 int rate (120);                  //metronome rate, initial value 120
00013 
00014 int main() {
00015   pc.printf("\r\n");
00016   pc.printf("mbed metronome!\r\n");
00017   pc.printf("_______________\r\n");
00018   period = 1;
00019   redled = 1;        //diagnostic
00020   wait(.1);
00021   redled = 0;
00022   beat_rate.attach(&beat, period);  //initialises the beat rate 
00023   //main loop checks buttons, updates rates and displays
00024   while(1){
00025     if (up_button ==1)   //increase rate by 4
00026       rate = rate + 4;
00027     if (down_button ==1)   //decrease rate by 4
00028       rate = rate - 4;
00029     if (rate > 208)        //limit the maximum beat rate to 208
00030       rate = 208;
00031     if (rate < 40)      //limit the minimum beat rate to 40
00032       rate = 40;
00033     period = 60/rate;       //calculate the beat period
00034     pc.printf("metronome rate is %i\r", rate);
00035     //pc.printf("metronome period is %f\r\n", period);  //optional check
00036     wait (0.5);
00037   }
00038 }
00039 
00040   void beat() {                         //this is the metronome beat
00041     beat_rate.attach(&beat, period);    //update beat rate at this moment
00042     redled = 1;
00043     wait(.1);
00044     redled = 0;
00045   }
00046