Testing PWM with a speaker

Dependencies:   mbed

Committer:
ffxx68
Date:
Thu Jan 08 15:22:35 2015 +0000
Revision:
1:aa7cd19c6a4f
Parent:
0:b82c05c12d48
Child:
2:ad1ac14ce44a
initial (not tested yet)

Who changed what in which revision?

UserRevisionLine numberNew contents of line
bcostm 0:b82c05c12d48 1 #include "mbed.h"
bcostm 0:b82c05c12d48 2
bcostm 0:b82c05c12d48 3 DigitalOut my_led(LED1);
bcostm 0:b82c05c12d48 4 InterruptIn my_button(USER_BUTTON);
ffxx68 1:aa7cd19c6a4f 5 PwmOut my_speaker(PB_3); // Speaker outut on PB 3
ffxx68 1:aa7cd19c6a4f 6
ffxx68 1:aa7cd19c6a4f 7 // Configuration for sinewave
ffxx68 1:aa7cd19c6a4f 8 #define PI (3.141592653589793238462)
ffxx68 1:aa7cd19c6a4f 9 #define AMPLITUDE (1.0) // x * 3.3V
ffxx68 1:aa7cd19c6a4f 10 #define PHASE (PI * 1) // 2*pi is one period
ffxx68 1:aa7cd19c6a4f 11 #define RANGE (4096/2) // 12 bits DAC
ffxx68 1:aa7cd19c6a4f 12 #define OFFSET (4096/2) // 12 bits DAC
ffxx68 1:aa7cd19c6a4f 13 #define BUFFER_SIZE (360)
ffxx68 1:aa7cd19c6a4f 14 uint16_t buffer[BUFFER_SIZE];
ffxx68 1:aa7cd19c6a4f 15
ffxx68 1:aa7cd19c6a4f 16 void calculate_sinewave(void){
ffxx68 1:aa7cd19c6a4f 17 for (int i = 0; i < BUFFER_SIZE; i++) {
ffxx68 1:aa7cd19c6a4f 18 double rads = (PI * i)/180.0; // Convert degree in radian
ffxx68 1:aa7cd19c6a4f 19 buffer[i] = (uint16_t)(AMPLITUDE * (RANGE * (cos(rads + PHASE))) + OFFSET);
ffxx68 1:aa7cd19c6a4f 20 }
ffxx68 1:aa7cd19c6a4f 21 }
bcostm 0:b82c05c12d48 22
bcostm 0:b82c05c12d48 23 void pressed() {
ffxx68 1:aa7cd19c6a4f 24 // change mode
ffxx68 1:aa7cd19c6a4f 25 my_led = !my_led;
bcostm 0:b82c05c12d48 26 }
bcostm 0:b82c05c12d48 27
bcostm 0:b82c05c12d48 28 int main()
bcostm 0:b82c05c12d48 29 {
ffxx68 1:aa7cd19c6a4f 30 my_speaker.period_ms(5); // PWM initial frequency: 200Hz
ffxx68 1:aa7cd19c6a4f 31 my_speaker.write(0); // Set duty to null, initially
ffxx68 1:aa7cd19c6a4f 32 my_led = 1; // turn on led and action
ffxx68 1:aa7cd19c6a4f 33 my_button.fall(&pressed); // Set button action
ffxx68 1:aa7cd19c6a4f 34 calculate_sinewave(); // Fill in the sinewave buffer
bcostm 0:b82c05c12d48 35
ffxx68 1:aa7cd19c6a4f 36 while(1) {
ffxx68 1:aa7cd19c6a4f 37 if (my_led) {
ffxx68 1:aa7cd19c6a4f 38 // play a continuos square wave
ffxx68 1:aa7cd19c6a4f 39 my_speaker.period_ms(2); // Frequency 500Hz
ffxx68 1:aa7cd19c6a4f 40 my_speaker.write(0.5); // Duty to 50%
ffxx68 1:aa7cd19c6a4f 41 }
ffxx68 1:aa7cd19c6a4f 42 else {
ffxx68 1:aa7cd19c6a4f 43 // play a sinewave
ffxx68 1:aa7cd19c6a4f 44 my_speaker.period_us(5); // PWM frequency: 200KHz
ffxx68 1:aa7cd19c6a4f 45 for (int i = 0; i < BUFFER_SIZE; i++) {
ffxx68 1:aa7cd19c6a4f 46 my_speaker.write( buffer[i] / (RANGE + OFFSET) ); // duty = sound amplitude
ffxx68 1:aa7cd19c6a4f 47 wait_us(50); // period: 360*50us -> 1350 Hz sinusoid
ffxx68 1:aa7cd19c6a4f 48 }
ffxx68 1:aa7cd19c6a4f 49 }
bcostm 0:b82c05c12d48 50 }
bcostm 0:b82c05c12d48 51 }