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.
Revision 111:ac492142f160, committed 2021-10-28
- Comitter:
- CSTritt
- Date:
- Thu Oct 28 02:28:59 2021 +0000
- Parent:
- 110:e80444a6fe3a
- Commit message:
- First version. Demo of PWM setup and speaker operation.
Changed in this revision
main.cpp | Show annotated file Show diff for this revision Revisions of this file |
--- a/main.cpp Tue Oct 05 13:18:23 2021 +0000 +++ b/main.cpp Thu Oct 28 02:28:59 2021 +0000 @@ -1,45 +1,32 @@ /* - Project: 21_BC_Improved_v5 (Improved Binary Counter (while loop) Version) + Project: 21_Speaker_v5 File: main.cpp - - Displays 8-bit binary count on bar graph display. This version uses a while - loop which provides a much better starting point for an Up/Down counter. - - Error in pow function use corrected in v. 1.0. - - Note: I tried to use count for the loop counter but this resulted in an - ambiguous name error. - + + Use PWM to sound speaker audio alarm. + Written by: Dr. C. S. Tritt - Created: 10/5/21 (v. 1.1) + Created: 10/27/21 (v. 1.0) */ #include "mbed.h" -DigitalIn uB(USER_BUTTON); // Button is active low (up = 1, down = 0). -const int bits = 8; // Number of bits to use. -const int c_max = pow(2, bits) - 1; // Maximum count. pow is type double. -const int sleepTime = 100; // Sleep time in milliseconds. -int myCount = 0; // Count to be displayed. Loop counter. -BusOut barGraph(D2, D3, D4, D5, D6, D7, D8, D9); // The display. +DigitalIn uB(USER_BUTTON); // The user button input (normally high). +PwmOut spkrOut(D12); // The speaker output. -int main() { - // Test the wiring. - ThisThread::sleep_for(400); // For 0.4 seconds. - barGraph = 0b01010101; // Odd bars on (binary). - ThisThread::sleep_for(400); // Test even bars for 0.4 seconds. - barGraph = 0b10101010; // Even bars on (binary). - ThisThread::sleep_for(400); // Test even bars for 0.4 seconds. - barGraph = 0xFF; // All bars on. Hex. - ThisThread::sleep_for(400); // For 0.4 seconds. - - barGraph = myCount; // Initialize the display to myCount. - // Enter main loop. +const int SLP_TIME = 100; // 0.1 s sample interval. +// PWM period: 2500 uS = 2.5 mS --> 400 Hz. +const int PWM_PRD = 2500; +const float DUTY_CYCLE = 0.5f; // Duty cycle as a fraction. +int main(void) +{ + // Setup. + spkrOut.period_us(PWM_PRD); + // Enter main loop. while(true) { - while (myCount >= 0 && myCount <= c_max) { - barGraph = myCount; // Set display to myCount. - ThisThread::sleep_for(sleepTime); // Display value for 0.1 seconds. - myCount++; + if (uB) { + spkrOut.write(0); // No sound. + } else { + spkrOut.write(DUTY_CYCLE); // Set duty cycle to sound speaker. } - myCount = 0; + ThisThread::sleep_for(SLP_TIME); // Display value for 0.1 seconds. } } \ No newline at end of file