Gabriel Karerangabo / Mbed 2 deprecated Blink_SwitchButton

Dependencies:   mbed

Files at this revision

API Documentation at this revision

Comitter:
kgabriel
Date:
Fri Jun 04 16:33:22 2021 +0000
Parent:
0:f792b1ecc7b3
Commit message:
Good Program

Changed in this revision

PlayingSoundWithSpeaker.cpp Show annotated file Show diff for this revision Revisions of this file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/PlayingSoundWithSpeaker.cpp	Fri Jun 04 16:33:22 2021 +0000
@@ -0,0 +1,56 @@
+// Add mbed library (Mandatory)
+#include "mbed.h"
+
+// Add a yellow LED on pin 5 and initialize it to 1 (ON)
+DigitalOut yellowLed(p5, 1);
+
+// Add a red LED on pin 5 and initialize it to 0 (OFF)
+DigitalOut redLed(p6, 0);
+
+// Add a switch BUTTON on pin 8
+DigitalIn switchButton(p8);
+
+// Add a speaker
+PwmOut speaker(p21);
+
+
+int acceptSwitchOnAction = 1;
+
+void play_tone(float frequency, float volume, int interval, int rest) {
+    speaker.period(1.0 / frequency);
+    speaker = volume;
+    wait_ms(interval);
+    speaker = 0.0;
+    wait(rest);
+}
+
+void control_leds() {
+        if (switchButton) { // When SwitchButton ON
+            if (acceptSwitchOnAction) {
+                int yellowBlinkingTimeCounter = 0;
+                while (yellowBlinkingTimeCounter < 5) {
+                    yellowLed = !yellowLed; // inverse the state of the LED
+                    yellowBlinkingTimeCounter++; // Increment counter
+                    play_tone(250, 0.2, 500, 0); ; // subprogram play sound
+                    wait_ms(500);
+                }
+                yellowLed = 0; // Yellow LED is OFF
+                acceptSwitchOnAction = 0;
+            }
+        } else { // When SwitchButton OFF
+            yellowLed = 1; // Yellow LED is ON
+            acceptSwitchOnAction = 1;
+        }
+        redLed = !yellowLed; // Inverse the state of yellow LED
+}
+
+int main() {
+    while (1) { // Do forever
+        control_leds(); // subprogram control leds
+        if (redLed) {
+          play_tone(250, 0.2, 500, 0); // subprogram play sound
+        } else {
+          wait_ms(500); // Sleep (duty-cycling)
+        }
+    }
+}
\ No newline at end of file