USB Speak with Digital Volume Control
Dependencies: AD5206 USBDevice mbed
Fork of USBAUDIO_speaker by
main.cpp
- Committer:
- taoqiuyang
- Date:
- 2015-10-17
- Revision:
- 11:d62d67b930f7
- Parent:
- 10:352d3dbfd6ec
File content as of revision 11:d62d67b930f7:
// USBAudio speaker example #include "mbed.h" #include "USBAudio.h" #include "AD5206.h" AD5206 digipot(p5, p6, p7,p8); int val=150; DigitalOut led1(LED1); DigitalOut led2(LED2); DigitalIn but1(p22); DigitalIn but2(p21); // frequency: 48 kHz #define FREQ 48000 // 1 channel: mono #define NB_CHA 1 // 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 48 * 2 * 1 // USBAudio (we just use audio packets received, we don't send audio packets to the computer in this example) USBAudio audio(FREQ, NB_CHA, 8000, 1, 0x7180, 0x7500); // speaker connected to the AnalogOut output. The audio stream received over USb will be sent to the speaker AnalogOut speaker(p18); // ticker to send data to the speaker at the good frequency Ticker tic; Ticker tic2; // buffer where will be store one audio packet (LENGTH_AUDIO_PACKET/2 because we are storing int16 and not uint8) int16_t buf[AUDIO_LENGTH_PACKET/2]; // show if an audio packet is available volatile bool available = false; // index of the value which will be send to the speaker int index_buf = 0; // previous value sent to the speaker uint16_t p_val = 0; // function executed each 1/FREQ s void tic_handler() { float speaker_value; if (available) { //convert 2 bytes in float speaker_value = (float)(buf[index_buf]); // speaker_value between 0 and 65535 speaker_value += 32768.0; // adjust according to current volume speaker_value *= audio.getVolume(); // as two bytes has been read, we move the index of two bytes index_buf++; // if we have read all the buffer, no more data available if (index_buf == AUDIO_LENGTH_PACKET/2) { index_buf = 0; available = false; } } else { speaker_value = p_val; } p_val = speaker_value; // send value to the speaker speaker.write_u16((uint16_t)speaker_value); } void tic_handler2() { led1=0; led2=0; if (!but1){led1=1;val+=20;} if (!but2){led2=1;val-=20;} digipot.write_AD5206(0,val); if (val>255){val=255;} if (val<0) {val=0;} } int main() { // attach a function executed each 1/FREQ s tic.attach_us(tic_handler, 1000000.0/(float)FREQ); tic2.attach(tic_handler2, 0.2); while (1) { // read an audio packet audio.read((uint8_t *)buf); available = true; } }