USBAudio example using a microphone

Dependencies:   USBDevice mbed

Committer:
samux
Date:
Tue Dec 20 10:44:10 2011 +0000
Revision:
5:b49b6a8ca111
Parent:
4:bef3b485f22e
Child:
6:be128039be16
doesn\'t work but cleaning up...

Who changed what in which revision?

UserRevisionLine numberNew contents of line
samux 0:539ec61e1fbb 1 #include "mbed.h"
samux 0:539ec61e1fbb 2 #include "USBAudio.h"
samux 0:539ec61e1fbb 3
samux 5:b49b6a8ca111 4 // frequency: 8 kHz
samux 5:b49b6a8ca111 5 #define FREQ 8000
samux 5:b49b6a8ca111 6
samux 5:b49b6a8ca111 7 // 1 channel: mono
samux 5:b49b6a8ca111 8 #define NB_CHA 1
samux 0:539ec61e1fbb 9
samux 5:b49b6a8ca111 10 // length of an audio packet: each ms, we receive 48 * 16bits ->48 * 2 bytes. as there is one channel, the length will be 48 * 2 * 1
samux 5:b49b6a8ca111 11 #define AUDIO_LENGTH_PACKET (FREQ/500) * NB_CHA
samux 5:b49b6a8ca111 12
samux 5:b49b6a8ca111 13 USBAudio audio(FREQ, NB_CHA, 0xaac0, 0xa734);
samux 3:e6a29c83ac52 14 AnalogIn mic(p20);
samux 5:b49b6a8ca111 15 DigitalOut p(p19);
samux 0:539ec61e1fbb 16
samux 5:b49b6a8ca111 17 // length of buffer = AUDIO_LENGTH_PACKET/2 because we are handling int16 and not bytes.
samux 5:b49b6a8ca111 18 int16_t buf[AUDIO_LENGTH_PACKET/2];
samux 4:bef3b485f22e 19
samux 0:539ec61e1fbb 20 int main() {
samux 5:b49b6a8ca111 21 double mic_mean = 0.0;
samux 5:b49b6a8ca111 22 double mic_value;
samux 5:b49b6a8ca111 23
samux 5:b49b6a8ca111 24 // compute average value of the microphone. We can then center the audio signal sent to the computer
samux 5:b49b6a8ca111 25 for (int j = 0; j < 1000; j++) {
samux 5:b49b6a8ca111 26 mic_value = (mic.read_u16() >> 3);
samux 5:b49b6a8ca111 27 mic_mean = (mic_mean*j + mic_value)/(j+1);
samux 5:b49b6a8ca111 28 }
samux 3:e6a29c83ac52 29
samux 0:539ec61e1fbb 30 while (1) {
samux 5:b49b6a8ca111 31
samux 5:b49b6a8ca111 32 // read 8 micro samples
samux 5:b49b6a8ca111 33 for (int i = 0; i < AUDIO_LENGTH_PACKET/2; i++) {
samux 5:b49b6a8ca111 34 buf[i] = (mic.read_u16() >> 3) - mic_mean;
samux 5:b49b6a8ca111 35 if (i != AUDIO_LENGTH_PACKET/2) {
samux 4:bef3b485f22e 36 wait_us(110);
samux 3:e6a29c83ac52 37 }
samux 3:e6a29c83ac52 38 }
samux 5:b49b6a8ca111 39 // send
samux 0:539ec61e1fbb 40 audio.write((uint8_t *)buf);
samux 5:b49b6a8ca111 41
samux 0:539ec61e1fbb 42 }
samux 0:539ec61e1fbb 43 }