Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
Fork of USBAUDIO_speaker by
main.cpp
- Committer:
- samux
- Date:
- 2011-11-30
- Revision:
- 1:0335b5c18618
- Parent:
- 0:5176b3dfccd6
- Child:
- 2:c3edc567ae33
File content as of revision 1:0335b5c18618:
// Hello World example for the USBMIDI library #include "mbed.h" #include "USBAudio.h" #include "CircBuffer.h" Serial pc(USBTX, USBRX); // 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_AUDIO_PACKET 48 * 2 * 1 // USBAudio USBAudio audio(FREQ, NB_CHA, 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; // 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_AUDIO_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_AUDIO_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); } int main() { // attach a function executed each 1/FREQ s tic.attach_us(tic_handler, 1000000.0/(float)FREQ); while (1) { // read an audio packet audio.read((uint8_t *)buf); available = true; } }