Esercitazione5_9

Dependencies:   mbed

Revision:
0:f7509ce18bc8
diff -r 000000000000 -r f7509ce18bc8 main.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main.cpp	Mon Oct 31 11:14:36 2016 +0000
@@ -0,0 +1,52 @@
+/*Program Example 9: Metronome. Uses Ticker to set beat rate
+*/
+#include "mbed.h"
+#include <stdio.h>
+Serial pc(USBTX, USBRX);
+DigitalIn button(USER_BUTTON);
+DigitalIn dir(D4,PullDown);
+DigitalOut redled(D8); //displays the metronome beat
+Ticker beat_rate; //define a Ticker, with name “beat_rate”
+void beat(void); 
+float period (0.5); //metronome period in seconds, initial value 0.5
+int rate (120); //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); //initializes the beat rate
+    //main loop checks buttons, updates rates and displays
+    while(1) {
+        if (button ==0) {
+            if (dir)
+                //increase rate by 4
+                rate = rate + 4;
+            else
+                //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
+    redled = 1;
+    wait(.1);
+    redled = 0;
+}
\ No newline at end of file