The sound input from a microphone is output from a speaker. Check device : BSHSAU01BK

Dependencies:   USBHostDac USBHost_custom_Addiso

main.cpp

Committer:
Osamu Nakamura
Date:
2017-04-24
Revision:
2:0b9331cde97b
Parent:
0:48a46b0d0cdd

File content as of revision 2:0b9331cde97b:

#include "mbed.h"
#include "USBHostDac.h"

#if defined(TARGET_RZ_A1H)
#include "usb_host_setting.h"
#else
#define USB_HOST_CH     0
#endif

#if (USB_HOST_CH == 1) //Audio Shield USB1
DigitalOut usb1en(P3_8);
#endif
DigitalIn  button(USER_BUTTON0);

#define AUDIO_READ_BUFF_SIZE   (2048)
#define AUDIO_WRITE_BUFF_SIZE  (AUDIO_READ_BUFF_SIZE * 2)

#define AUDIO_WRITE_BUFF_NUM   (2)

static uint16_t audio_read_buff[AUDIO_READ_BUFF_SIZE/2];
static uint16_t audio_write_buff[AUDIO_WRITE_BUFF_NUM][AUDIO_WRITE_BUFF_SIZE/2];

Semaphore sem(0);

void test_task(void const* arg) {
    int buf_index = 0;
    USBHostDac * p_usbdac = (USBHostDac *)arg;

    while (1) {
        sem.wait();

        p_usbdac->send((uint8_t *)audio_write_buff[buf_index], AUDIO_WRITE_BUFF_SIZE, false);

        buf_index++;
        if (buf_index >= AUDIO_WRITE_BUFF_NUM) {
            buf_index = 0;
        }
    }
}

int main() {
    int buf_index = 0;

#if (USB_HOST_CH == 1) //Audio Shield USB1
    //Audio Shield USB1 enable
    usb1en = 1;        //Outputs high level
    Thread::wait(5);
    usb1en = 0;        //Outputs low level
#endif

    USBHostDac usbdac;
    Thread TestTask(test_task, &usbdac, osPriorityNormal, 1024 * 8);

    while(1) {
        // try to connect a usbdac device
        while(!usbdac.connect()) {
            Thread::wait(500);
        }

        while (1) {
            // if device disconnected, try to connect again
            if (!usbdac.connected()) {
                break;
            }
            int ret = usbdac.receive((uint8_t *)audio_read_buff, AUDIO_READ_BUFF_SIZE);
            if (ret > 0) {
                //1ch -> 2ch
                uint16_t * p_write = audio_write_buff[buf_index];
                uint16_t * p_read  = audio_read_buff;

                for (int cnt = 0; cnt < (ret / 2); cnt++) {
                    *p_write = *p_read;
                    p_write++;
                    *p_write = *p_read;
                    p_write++;
                    p_read++;
                }

                sem.release();

                buf_index++;
                if (buf_index >= AUDIO_WRITE_BUFF_NUM) {
                    buf_index = 0;
                }
            }
        }
    }
}