Samuel Mokrani
/
USBAudio_micro
USBAudio example using a microphone
main.cpp@6:be128039be16, 2011-12-20 (annotated)
- Committer:
- samux
- Date:
- Tue Dec 20 11:17:33 2011 +0000
- Revision:
- 6:be128039be16
- Parent:
- 5:b49b6a8ca111
- Child:
- 7:6b0012b8fd01
works for m0 and m3 with cleaning up
Who changed what in which revision?
User | Revision | Line number | New contents of line |
---|---|---|---|
samux |
0:539ec61e1fbb | 1 | #include "mbed.h" |
samux |
0:539ec61e1fbb | 2 | #include "USBAudio.h" |
samux |
0:539ec61e1fbb | 3 | |
samux |
6:be128039be16 | 4 | extern "C" void HardFault_Handler() { |
samux |
6:be128039be16 | 5 | error("Hard Fault!\n"); |
samux |
6:be128039be16 | 6 | } |
samux |
6:be128039be16 | 7 | |
samux |
5:b49b6a8ca111 | 8 | // frequency: 8 kHz |
samux |
5:b49b6a8ca111 | 9 | #define FREQ 8000 |
samux |
5:b49b6a8ca111 | 10 | |
samux |
5:b49b6a8ca111 | 11 | // 1 channel: mono |
samux |
5:b49b6a8ca111 | 12 | #define NB_CHA 1 |
samux |
0:539ec61e1fbb | 13 | |
samux |
5:b49b6a8ca111 | 14 | // 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 | 15 | #define AUDIO_LENGTH_PACKET (FREQ/500) * NB_CHA |
samux |
5:b49b6a8ca111 | 16 | |
samux |
6:be128039be16 | 17 | USBAudio audio(FREQ, NB_CHA, 0x1111, 0x78ab); |
samux |
6:be128039be16 | 18 | |
samux |
3:e6a29c83ac52 | 19 | AnalogIn mic(p20); |
samux |
5:b49b6a8ca111 | 20 | DigitalOut p(p19); |
samux |
0:539ec61e1fbb | 21 | |
samux |
5:b49b6a8ca111 | 22 | int16_t buf[AUDIO_LENGTH_PACKET/2]; |
samux |
4:bef3b485f22e | 23 | |
samux |
0:539ec61e1fbb | 24 | int main() { |
samux |
6:be128039be16 | 25 | |
samux |
5:b49b6a8ca111 | 26 | double mic_mean = 0.0; |
samux |
5:b49b6a8ca111 | 27 | double mic_value; |
samux |
5:b49b6a8ca111 | 28 | |
samux |
5:b49b6a8ca111 | 29 | // compute average value of the microphone. We can then center the audio signal sent to the computer |
samux |
5:b49b6a8ca111 | 30 | for (int j = 0; j < 1000; j++) { |
samux |
5:b49b6a8ca111 | 31 | mic_value = (mic.read_u16() >> 3); |
samux |
5:b49b6a8ca111 | 32 | mic_mean = (mic_mean*j + mic_value)/(j+1); |
samux |
5:b49b6a8ca111 | 33 | } |
samux |
3:e6a29c83ac52 | 34 | |
samux |
0:539ec61e1fbb | 35 | while (1) { |
samux |
6:be128039be16 | 36 | p = 1; |
samux |
5:b49b6a8ca111 | 37 | for (int i = 0; i < AUDIO_LENGTH_PACKET/2; i++) { |
samux |
5:b49b6a8ca111 | 38 | buf[i] = (mic.read_u16() >> 3) - mic_mean; |
samux |
5:b49b6a8ca111 | 39 | if (i != AUDIO_LENGTH_PACKET/2) { |
samux |
6:be128039be16 | 40 | wait_us(80); |
samux |
3:e6a29c83ac52 | 41 | } |
samux |
3:e6a29c83ac52 | 42 | } |
samux |
6:be128039be16 | 43 | p = 0; |
samux |
0:539ec61e1fbb | 44 | audio.write((uint8_t *)buf); |
samux |
0:539ec61e1fbb | 45 | } |
samux |
0:539ec61e1fbb | 46 | } |