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

Dependencies:   mbed

Fork of Book-PE_09-10_Metronomex by avnish aggarwal

main.cpp

Committer:
avnisha
Date:
2013-10-28
Revision:
3:0de69a4b8aac
Parent:
2:d1d15e8c083f

File content as of revision 3:0de69a4b8aac:

/*Program Example 9.10: Metronome. Uses Ticker to set beat rate
 
 
                                                                    */            
#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);               
float rate (60);                   

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   %f\r\n", rate);
    pc.printf("metronome period is %f\r\n", period);  
    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;
  }