USBAudio example using a microphone

Dependencies:   USBDevice mbed

Revision:
5:b49b6a8ca111
Parent:
4:bef3b485f22e
Child:
6:be128039be16
--- a/main.cpp	Mon Dec 19 16:13:32 2011 +0000
+++ b/main.cpp	Tue Dec 20 10:44:10 2011 +0000
@@ -1,28 +1,43 @@
 #include "mbed.h"
 #include "USBAudio.h"
 
-extern "C" void HardFault_Handler() {
-    error("Hard Fault!\n");
-}
+// frequency: 8 kHz
+#define FREQ 8000
+
+// 1 channel: mono
+#define NB_CHA 1
 
-USBAudio audio(8000, 1, 0x74ac, 0x8788);
+// 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
+#define AUDIO_LENGTH_PACKET (FREQ/500) * NB_CHA
+
+USBAudio audio(FREQ, NB_CHA, 0xaac0, 0xa734);
 AnalogIn mic(p20);
-DigitalOut p(p21);
+DigitalOut p(p19);
 
-int16_t buf[8];
-
+// length of buffer = AUDIO_LENGTH_PACKET/2 because we are handling int16 and not bytes.
+int16_t buf[AUDIO_LENGTH_PACKET/2];
 
 int main() {
+    double mic_mean = 0.0;
+    double mic_value;
+
+    // compute average value of the microphone. We can then center the audio signal sent to the computer
+    for (int j = 0; j < 1000; j++) {
+        mic_value = (mic.read_u16() >> 3);
+        mic_mean = (mic_mean*j + mic_value)/(j+1);
+    }
 
     while (1) {
-        p = 1;
-        for (int i = 0; i < 8; i++) {
-            buf[i] = (mic.read_u16() >> 3) - 4100;
-            if (i != 7) {
+
+        // read 8 micro samples
+        for (int i = 0; i < AUDIO_LENGTH_PACKET/2; i++) {
+            buf[i] = (mic.read_u16() >> 3) - mic_mean;
+            if (i != AUDIO_LENGTH_PACKET/2) {
                 wait_us(110);
             }
         }
-        p = 0;
+        // send
         audio.write((uint8_t *)buf);
+
     }
 }