MEM / Mbed 2 deprecated ES_5_p9

Dependencies:   mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001  /*Program Example 9: Metronome. Uses Ticker to set beat rate
00002  */
00003  #include "mbed.h"
00004  #include <stdio.h>
00005  Serial pc(USBTX, USBRX);
00006  DigitalIn button(PC_13);
00007  DigitalIn dir(D4,PullDown);
00008  DigitalOut redled(D8); //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, initial value 0.5
00012  int rate (120); //metronome rate, initial value 120
00013  int main()
00014  {
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); //initializes the beat rate
00023      //main loop checks buttons, updates rates and displays
00024      while(1) {
00025          if (button ==0) {
00026          if (dir)
00027          //increase rate by 4
00028          rate = rate + 4;
00029          else
00030          //decrease rate by 4
00031          rate = rate - 4;
00032      }
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 %i\r", rate);
00039      //pc.printf("metronome period is %f\r\n", period); //optional check
00040      wait (0.5);
00041      }
00042  }
00043  void beat() //this is the metronome beat
00044  {
00045      beat_rate.attach(&beat, period); //update beat rate at this moment
00046      redled = 1;
00047      wait(.1);
00048      redled = 0;
00049  }