Gabriel Karerangabo / Mbed 2 deprecated Blink_SwitchButton

Dependencies:   mbed

PlayingSoundWithSpeaker.cpp

Committer:
kgabriel
Date:
2021-06-04
Revision:
1:f2ac268b3b17

File content as of revision 1:f2ac268b3b17:

// 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)
        }
    }
}