3      Copyright (C) Dean Camera, 2011. 
   5   dean [at] fourwalledcubicle [dot] com 
  10   Copyright 2011  Dean Camera (dean [at] fourwalledcubicle [dot] com) 
  12   Permission to use, copy, modify, distribute, and sell this 
  13   software and its documentation for any purpose is hereby granted 
  14   without fee, provided that the above copyright notice appear in 
  15   all copies and that both that the copyright notice and this 
  16   permission notice and warranty disclaimer appear in supporting 
  17   documentation, and that the name of the author not be used in 
  18   advertising or publicity pertaining to distribution of the 
  19   software without specific, written prior permission. 
  21   The author disclaim all warranties with regard to this 
  22   software, including all implied warranties of merchantability 
  23   and fitness.  In no event shall the author be liable for any 
  24   special, indirect or consequential damages or any damages 
  25   whatsoever resulting from loss of use, data or profits, whether 
  26   in an action of contract, negligence or other tortious action, 
  27   arising out of or in connection with the use or performance of 
  33  *  Main source file for the AudioOutputHost demo. This file contains the main tasks of 
  34  *  the demo and is responsible for the initial application hardware configuration. 
  37 #include "AudioOutputHost.h" 
  39 /** Main program entry point. This routine configures the hardware required by the application, then 
  40  *  enters a loop to run the application tasks in sequence. 
  46         puts_P(PSTR(ESC_FG_CYAN 
"Audio Output Host Demo running.\r\n" ESC_FG_WHITE
)); 
  48         LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY
); 
  58 /** Configures the board hardware and chip peripherals for the demo's functionality. */ 
  59 void SetupHardware(void) 
  61         /* Disable watchdog if enabled by bootloader/fuses */ 
  62         MCUSR 
&= ~(1 << WDRF
); 
  65         /* Disable clock division */ 
  66         clock_prescale_set(clock_div_1
); 
  68         /* Hardware Initialization */ 
  69         Serial_Init(9600, false); 
  71         ADC_Init(ADC_FREE_RUNNING 
| ADC_PRESCALE_32
); 
  72         ADC_SetupChannel(MIC_IN_ADC_CHANNEL
);    
  76         /* Create a stdio stream for the serial port for stdin and stdout */ 
  77         Serial_CreateStream(NULL
); 
  80 /** Event handler for the USB_DeviceAttached event. This indicates that a device has been attached to the host, and 
  81  *  starts the library USB task to begin the enumeration and USB management process. 
  83 void EVENT_USB_Host_DeviceAttached(void) 
  85         puts_P(PSTR(ESC_FG_GREEN 
"Device Attached.\r\n" ESC_FG_WHITE
)); 
  86         LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING
); 
  89 /** Event handler for the USB_DeviceUnattached event. This indicates that a device has been removed from the host, and 
  90  *  stops the library USB task management process. 
  92 void EVENT_USB_Host_DeviceUnattached(void) 
  94         puts_P(PSTR(ESC_FG_GREEN 
"Device Unattached.\r\n" ESC_FG_WHITE
)); 
  95         LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY
); 
  98 /** Event handler for the USB_DeviceEnumerationComplete event. This indicates that a device has been successfully 
  99  *  enumerated by the host and is now ready to be used by the application. 
 101 void EVENT_USB_Host_DeviceEnumerationComplete(void) 
 103         LEDs_SetAllLEDs(LEDMASK_USB_READY
); 
 106 /** Event handler for the USB_HostError event. This indicates that a hardware error occurred while in host mode. */ 
 107 void EVENT_USB_Host_HostError(const uint8_t ErrorCode
) 
 111         printf_P(PSTR(ESC_FG_RED 
"Host Mode Error\r\n" 
 112                                  " -- Error Code %d\r\n" ESC_FG_WHITE
), ErrorCode
); 
 114         LEDs_SetAllLEDs(LEDMASK_USB_ERROR
); 
 118 /** Event handler for the USB_DeviceEnumerationFailed event. This indicates that a problem occurred while 
 119  *  enumerating an attached USB device. 
 121 void EVENT_USB_Host_DeviceEnumerationFailed(const uint8_t ErrorCode
, 
 122                                             const uint8_t SubErrorCode
) 
 124         printf_P(PSTR(ESC_FG_RED 
"Dev Enum Error\r\n" 
 125                                  " -- Error Code %d\r\n" 
 126                                  " -- Sub Error Code %d\r\n" 
 127                                  " -- In State %d\r\n" ESC_FG_WHITE
), ErrorCode
, SubErrorCode
, USB_HostState
); 
 129         LEDs_SetAllLEDs(LEDMASK_USB_ERROR
); 
 132 void Audio_Task(void) 
 136         switch (USB_HostState
) 
 138                 case HOST_STATE_Addressed
: 
 139                         puts_P(PSTR("Getting Config Data.\r\n")); 
 141                         /* Get and process the configuration descriptor data */ 
 142                         if ((ErrorCode 
= ProcessConfigurationDescriptor()) != SuccessfulConfigRead
) 
 144                                 if (ErrorCode 
== ControlError
) 
 145                                   puts_P(PSTR(ESC_FG_RED 
"Control Error (Get Configuration).\r\n")); 
 147                                   puts_P(PSTR(ESC_FG_RED 
"Invalid Device.\r\n")); 
 149                                 printf_P(PSTR(" -- Error Code: %d\r\n" ESC_FG_WHITE
), ErrorCode
); 
 151                                 /* Indicate error status */ 
 152                                 LEDs_SetAllLEDs(LEDMASK_USB_ERROR
); 
 154                                 /* Wait until USB device disconnected */ 
 155                                 USB_HostState 
= HOST_STATE_WaitForDeviceRemoval
; 
 159                         /* Set the device configuration to the first configuration (rarely do devices use multiple configurations) */ 
 160                         if ((ErrorCode 
= USB_Host_SetDeviceConfiguration(1)) != HOST_SENDCONTROL_Successful
) 
 162                                 printf_P(PSTR(ESC_FG_RED 
"Control Error (Set Configuration).\r\n" 
 163                                                          " -- Error Code: %d\r\n" ESC_FG_WHITE
), ErrorCode
); 
 165                                 /* Indicate error status */ 
 166                                 LEDs_SetAllLEDs(LEDMASK_USB_ERROR
); 
 168                                 /* Wait until USB device disconnected */ 
 169                                 USB_HostState 
= HOST_STATE_WaitForDeviceRemoval
; 
 173                         if ((ErrorCode 
= USB_Host_SetInterfaceAltSetting(StreamingInterfaceIndex
, 
 174                                                                          StreamingInterfaceAltSetting
)) != HOST_SENDCONTROL_Successful
) 
 176                                 printf_P(PSTR(ESC_FG_RED 
"Could not set alternative streaming interface setting.\r\n" 
 177                                                          " -- Error Code: %d\r\n" ESC_FG_WHITE
), ErrorCode
); 
 179                                 /* Indicate error status */ 
 180                                 LEDs_SetAllLEDs(LEDMASK_USB_ERROR
); 
 182                                 /* Wait until USB device disconnected */ 
 183                                 USB_HostState 
= HOST_STATE_WaitForDeviceRemoval
; 
 187                         USB_ControlRequest 
= (USB_Request_Header_t
) 
 189                                         .bmRequestType 
= (REQDIR_HOSTTODEVICE 
| REQTYPE_CLASS 
| REQREC_ENDPOINT
), 
 190                                         .bRequest      
= AUDIO_REQ_SetCurrent
, 
 191                                         .wValue        
= (AUDIO_EPCONTROL_SamplingFreq 
<< 8), 
 192                                         .wIndex        
= StreamingEndpointAddress
, 
 193                                         .wLength       
= sizeof(USB_Audio_SampleFreq_t
), 
 196                         USB_Audio_SampleFreq_t SampleRate 
= AUDIO_SAMPLE_FREQ(48000); 
 198                         /* Select the control pipe for the request transfer */ 
 199                         Pipe_SelectPipe(PIPE_CONTROLPIPE
); 
 201                         /* Set the sample rate on the streaming interface endpoint */ 
 202                         if ((ErrorCode 
= USB_Host_SendControlRequest(&SampleRate
)) != HOST_SENDCONTROL_Successful
) 
 204                                 /* Indicate error status */ 
 205                                 LEDs_SetAllLEDs(LEDMASK_USB_ERROR
); 
 207                                 /* Wait until USB device disconnected */ 
 208                                 USB_HostState 
= HOST_STATE_WaitForDeviceRemoval
; 
 212                         /* Sample reload timer initialization */ 
 213                         TIMSK0  
= (1 << OCIE0A
); 
 214                         OCR0A   
= ((F_CPU 
/ 8 / 48000) - 1); 
 215                         TCCR0A  
= (1 << WGM01
);  // CTC mode 
 216                         TCCR0B  
= (1 << CS01
);   // Fcpu/8 speed         
 218                         puts_P(PSTR("Speaker Enumerated.\r\n")); 
 220                         USB_HostState 
= HOST_STATE_Configured
; 
 222                 case HOST_STATE_Configured
: 
 223                         /* Do nothing - audio stream is handled by the timer interrupt routine */ 
 228 /** ISR to handle the reloading of the endpoint with the next sample. */ 
 229 ISR(TIMER0_COMPA_vect
, ISR_BLOCK
) 
 231         uint8_t PrevPipe 
= Pipe_GetCurrentPipe(); 
 233         Pipe_SelectPipe(AUDIO_DATA_OUT_PIPE
); 
 236         /* Check if the current pipe can be written to (device ready for more data) */ 
 237         if (Pipe_IsOUTReady()) 
 241                 #if defined(USE_TEST_TONE) 
 242                         static uint8_t SquareWaveSampleCount
; 
 243                         static int16_t CurrentWaveValue
; 
 245                         /* In test tone mode, generate a square wave at 1/256 of the sample rate */ 
 246                         if (SquareWaveSampleCount
++ == 0xFF) 
 247                           CurrentWaveValue 
^= 0x8000; 
 249                         /* Only generate audio if the board button is being pressed */ 
 250                         AudioSample 
= (Buttons_GetStatus() & BUTTONS_BUTTON1
) ? CurrentWaveValue 
: 0; 
 252                         /* Audio sample is ADC value scaled to fit the entire range */ 
 253                         AudioSample 
= ((SAMPLE_MAX_RANGE 
/ ADC_MAX_RANGE
) * ADC_GetResult()); 
 255                         #if defined(MICROPHONE_BIASED_TO_HALF_RAIL) 
 256                         /* Microphone is biased to half rail voltage, subtract the bias from the sample value */ 
 257                         AudioSample 
-= (SAMPLE_MAX_RANGE 
/ 2); 
 261                 Pipe_Write_16_LE(AudioSample
); 
 262                 Pipe_Write_16_LE(AudioSample
); 
 264                 if (!(Pipe_IsReadWriteAllowed())) 
 269         Pipe_SelectPipe(PrevPipe
);