ok

Dependencies:   mbed

Fork of Book-PE_09-10_Metronomex by avnish aggarwal

main.cpp

Committer:
avnisha
Date:
2013-10-16
Revision:
2:d1d15e8c083f
Parent:
1:733a0de4d34c
Child:
3:0de69a4b8aac

File content as of revision 2:d1d15e8c083f:

/*Program Example 9.10: Metronome. Uses Ticker to set beat rate
 
 
//BusIn joy(p15,p12,p13,p16);  
                                                                    */            
#include "mbed.h"
#include <stdio.h>
Serial pc(USBTX, USBRX);
DigitalIn up_button(p15);
DigitalIn down_button(p16);
DigitalOut redled(LED1);             //displays the metronome beat
Ticker beat_rate;  
PwmOut spkr(p26);  
               
void beat(void);
float period (1);              //metronome period in seconds, inital value 0.5
int rate (60);                  //metronome rate, initial value 120

int main() {
  pc.printf("\r\n");
  pc.printf("mbed metronome!\r\n");
  pc.printf("_______________\r\n");
  period = 1;
  redled = 1;        //diagnostic
  wait(.1);
  redled = 0;
  beat_rate.attach(&beat, period);  //initialises the beat rate 
  //main loop checks buttons, updates rates and displays
  while(1){
    if (up_button ==1)   //increase rate by 4
      rate = rate + 4;
    if (down_button ==1)   //decrease rate by 4
      rate = rate - 4;
    if (rate > 208)        //limit the maximum beat rate to 208
      rate = 208;
    if (rate < 40)      //limit the minimum beat rate to 40
      rate = 40;
    period = 60/rate;       //calculate the beat period
    pc.printf("metronome rate is %i\r", rate);
    //pc.printf("metronome period is %f\r\n", period);  //optional check
    wait (0.5);
  }
}

  void beat() {                         //this is the metronome beat
    beat_rate.attach(&beat, period);    //update beat rate at this moment

    // speaker    
    spkr.period(1.0/5000);
    spkr=0.5;
    
    // led
    redled = 1;
    wait(.1);
    
    // turn off speaker and led
    redled = 0;
    spkr = 0.0;
  }

#ifdef spkr
DigitalIn fire(p14);
PwmOut spkr(p26);

int main()
{
    while (1) {
        for (float i=2000.0; i<10000.0; i+=100) {
            spkr.period(1.0/i);
            spkr=0.5;
            wait(0.1);
        }
        spkr=0.0;
        while(!fire) {}
    }
}
#endif