First version. Demo of PWM setup and speaker operation. Fine grain control of the PWM parameters is an advantage Mbed has over the Arduino environment.

Committer:
CSTritt
Date:
Thu Oct 28 02:28:59 2021 +0000
Revision:
111:ac492142f160
Parent:
110:e80444a6fe3a
First version. Demo of PWM setup and speaker operation.

Who changed what in which revision?

UserRevisionLine numberNew contents of line
CSTritt 107:61b9c99a4e27 1 /*
CSTritt 111:ac492142f160 2 Project: 21_Speaker_v5
CSTritt 108:eee3167b25b4 3 File: main.cpp
CSTritt 111:ac492142f160 4
CSTritt 111:ac492142f160 5 Use PWM to sound speaker audio alarm.
CSTritt 111:ac492142f160 6
CSTritt 108:eee3167b25b4 7 Written by: Dr. C. S. Tritt
CSTritt 111:ac492142f160 8 Created: 10/27/21 (v. 1.0)
CSTritt 107:61b9c99a4e27 9 */
Jonathan Austin 0:2757d7abb7d9 10 #include "mbed.h"
CSTritt 108:eee3167b25b4 11
CSTritt 111:ac492142f160 12 DigitalIn uB(USER_BUTTON); // The user button input (normally high).
CSTritt 111:ac492142f160 13 PwmOut spkrOut(D12); // The speaker output.
CSTritt 108:eee3167b25b4 14
CSTritt 111:ac492142f160 15 const int SLP_TIME = 100; // 0.1 s sample interval.
CSTritt 111:ac492142f160 16 // PWM period: 2500 uS = 2.5 mS --> 400 Hz.
CSTritt 111:ac492142f160 17 const int PWM_PRD = 2500;
CSTritt 111:ac492142f160 18 const float DUTY_CYCLE = 0.5f; // Duty cycle as a fraction.
CSTritt 111:ac492142f160 19 int main(void)
CSTritt 111:ac492142f160 20 {
CSTritt 111:ac492142f160 21 // Setup.
CSTritt 111:ac492142f160 22 spkrOut.period_us(PWM_PRD);
CSTritt 111:ac492142f160 23 // Enter main loop.
CSTritt 108:eee3167b25b4 24 while(true) {
CSTritt 111:ac492142f160 25 if (uB) {
CSTritt 111:ac492142f160 26 spkrOut.write(0); // No sound.
CSTritt 111:ac492142f160 27 } else {
CSTritt 111:ac492142f160 28 spkrOut.write(DUTY_CYCLE); // Set duty cycle to sound speaker.
CSTritt 108:eee3167b25b4 29 }
CSTritt 111:ac492142f160 30 ThisThread::sleep_for(SLP_TIME); // Display value for 0.1 seconds.
CSTritt 108:eee3167b25b4 31 }
CSTritt 108:eee3167b25b4 32 }