3      Copyright (C) Dean Camera, 2013. 
   5   dean [at] fourwalledcubicle [dot] com 
  10   Copyright 2013  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 disclaims 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 AudioOutput demo. This file contains the main tasks of the demo and 
  34  *  is responsible for the initial application hardware configuration. 
  37 #include "AudioOutput.h" 
  39 /** Flag to indicate if the streaming audio alternative interface has been selected by the host. */ 
  40 static bool StreamingAudioInterfaceSelected 
= false; 
  42 /** Current audio sampling frequency of the streaming audio endpoint. */ 
  43 static uint32_t CurrentAudioSampleFrequency 
= 48000; 
  46 /** Main program entry point. This routine contains the overall program flow, including initial 
  47  *  setup of all components and the main program loop. 
  53         LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY
); 
  54         GlobalInterruptEnable(); 
  62 /** Configures the board hardware and chip peripherals for the demo's functionality. */ 
  63 void SetupHardware(void) 
  65         /* Disable watchdog if enabled by bootloader/fuses */ 
  66         MCUSR 
&= ~(1 << WDRF
); 
  69         /* Disable clock division */ 
  70         clock_prescale_set(clock_div_1
); 
  72         /* Hardware Initialization */ 
  77 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs, and 
  78  *  configures the sample update and PWM timers. 
  80 void EVENT_USB_Device_Connect(void) 
  82         /* Indicate USB enumerating */ 
  83         LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING
); 
  85         /* Sample reload timer initialization */ 
  86         TIMSK0 
= (1 << OCIE0A
); 
  87         OCR0A  
= ((F_CPU 
/ 8 / CurrentAudioSampleFrequency
) - 1); 
  88         TCCR0A 
= (1 << WGM01
);  // CTC mode 
  89         TCCR0B 
= (1 << CS01
);   // Fcpu/8 speed 
  91         #if defined(AUDIO_OUT_MONO) 
  92         /* Set speaker as output */ 
  94         #elif defined(AUDIO_OUT_STEREO) 
  95         /* Set speakers as outputs */ 
  96         DDRC  
|= ((1 << 6) | (1 << 5)); 
  97         #elif defined(AUDIO_OUT_PORTC) 
  98         /* Set PORTC as outputs */ 
 102         #if (defined(AUDIO_OUT_MONO) || defined(AUDIO_OUT_STEREO)) 
 103         /* PWM speaker timer initialization */ 
 104         TCCR3A 
= ((1 << WGM30
) | (1 << COM3A1
) | (1 << COM3A0
) 
 105                                | (1 << COM3B1
) | (1 << COM3B0
)); // Set on match, clear on TOP 
 106         TCCR3B 
= ((1 << WGM32
) | (1 << CS30
));  // Fast 8-Bit PWM, F_CPU speed 
 110 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via 
 111  *  the status LEDs, disables the sample update and PWM output timers and stops the USB and Audio management tasks. 
 113 void EVENT_USB_Device_Disconnect(void) 
 115         /* Stop the timers */ 
 117         #if (defined(AUDIO_OUT_MONO) || defined(AUDIO_OUT_STEREO)) 
 121         #if defined(AUDIO_OUT_MONO) 
 122         /* Set speaker as input to reduce current draw */ 
 124         #elif defined(AUDIO_OUT_STEREO) 
 125         /* Set speakers as inputs to reduce current draw */ 
 126         DDRC  
&= ~((1 << 6) | (1 << 5)); 
 127         #elif defined(AUDIO_OUT_PORTC) 
 132         /* Indicate streaming audio interface not selected */ 
 133         StreamingAudioInterfaceSelected 
= false; 
 135         /* Indicate USB not ready */ 
 136         LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY
); 
 139 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host set the current configuration 
 140  *  of the USB device after enumeration - the device endpoints are configured. 
 142 void EVENT_USB_Device_ConfigurationChanged(void) 
 144         bool ConfigSuccess 
= true; 
 146         /* Setup Audio Stream Endpoint */ 
 147         ConfigSuccess 
&= Endpoint_ConfigureEndpoint(AUDIO_STREAM_EPADDR
, EP_TYPE_ISOCHRONOUS
, AUDIO_STREAM_EPSIZE
, 2); 
 149         /* Indicate endpoint configuration success or failure */ 
 150         LEDs_SetAllLEDs(ConfigSuccess ? LEDMASK_USB_READY 
: LEDMASK_USB_ERROR
); 
 153 /** Event handler for the USB_ControlRequest event. This is used to catch and process control requests sent to 
 154  *  the device from the USB host before passing along unhandled control requests to the library for processing 
 157 void EVENT_USB_Device_ControlRequest(void) 
 159         /* Process General and Audio specific control requests */ 
 160         switch (USB_ControlRequest
.bRequest
) 
 162                 case REQ_SetInterface
: 
 163                         /* Set Interface is not handled by the library, as its function is application-specific */ 
 164                         if (USB_ControlRequest
.bmRequestType 
== (REQDIR_HOSTTODEVICE 
| REQTYPE_STANDARD 
| REQREC_INTERFACE
)) 
 166                                 Endpoint_ClearSETUP(); 
 167                                 Endpoint_ClearStatusStage(); 
 169                                 /* Check if the host is enabling the audio interface (setting AlternateSetting to 1) */ 
 170                                 StreamingAudioInterfaceSelected 
= ((USB_ControlRequest
.wValue
) != 0); 
 174                 case AUDIO_REQ_GetStatus
: 
 175                         /* Get Status request can be directed at either the interface or endpoint, neither is currently used 
 176                          * according to the latest USB Audio 1.0 standard, but must be ACKed with no data when requested */ 
 177                         if ((USB_ControlRequest
.bmRequestType 
== (REQDIR_HOSTTODEVICE 
| REQTYPE_CLASS 
| REQREC_INTERFACE
)) || 
 178                             (USB_ControlRequest
.bmRequestType 
== (REQDIR_HOSTTODEVICE 
| REQTYPE_CLASS 
| REQREC_ENDPOINT
))) 
 180                                 Endpoint_ClearSETUP(); 
 181                                 Endpoint_ClearStatusStage(); 
 185                 case AUDIO_REQ_SetCurrent
: 
 186                         if (USB_ControlRequest
.bmRequestType 
== (REQDIR_HOSTTODEVICE 
| REQTYPE_CLASS 
| REQREC_ENDPOINT
)) 
 188                                 /* Extract out the relevant request information to get the target Endpoint address and control being set */ 
 189                                 uint8_t EndpointAddress 
= (uint8_t)USB_ControlRequest
.wIndex
; 
 190                                 uint8_t EndpointControl 
= (USB_ControlRequest
.wValue 
>> 8); 
 192                                 /* Only handle SET CURRENT requests to the audio endpoint's sample frequency property */ 
 193                                 if ((EndpointAddress 
== AUDIO_STREAM_EPADDR
) && (EndpointControl 
== AUDIO_EPCONTROL_SamplingFreq
)) 
 195                                         uint8_t SampleRate
[3]; 
 197                                         Endpoint_ClearSETUP(); 
 198                                         Endpoint_Read_Control_Stream_LE(SampleRate
, sizeof(SampleRate
)); 
 201                                         /* Set the new sampling frequency to the value given by the host */ 
 202                                         CurrentAudioSampleFrequency 
= (((uint32_t)SampleRate
[2] << 16) | ((uint32_t)SampleRate
[1] << 8) | (uint32_t)SampleRate
[0]); 
 204                                         /* Adjust sample reload timer to the new frequency */ 
 205                                         OCR0A 
= ((F_CPU 
/ 8 / CurrentAudioSampleFrequency
) - 1); 
 210                 case AUDIO_REQ_GetCurrent
: 
 211                         if (USB_ControlRequest
.bmRequestType 
== (REQDIR_HOSTTODEVICE 
| REQTYPE_CLASS 
| REQREC_ENDPOINT
)) 
 213                                 /* Extract out the relevant request information to get the target Endpoint address and control being retrieved */ 
 214                                 uint8_t EndpointAddress 
= (uint8_t)USB_ControlRequest
.wIndex
; 
 215                                 uint8_t EndpointControl 
= (USB_ControlRequest
.wValue 
>> 8); 
 217                                 /* Only handle GET CURRENT requests to the audio endpoint's sample frequency property */ 
 218                                 if ((EndpointAddress 
== AUDIO_STREAM_EPADDR
) && (EndpointControl 
== AUDIO_EPCONTROL_SamplingFreq
)) 
 220                                         uint8_t SampleRate
[3]; 
 222                                         /* Convert the sampling rate value into the 24-bit format the host expects for the property */ 
 223                                         SampleRate
[2] = (CurrentAudioSampleFrequency 
>> 16); 
 224                                         SampleRate
[1] = (CurrentAudioSampleFrequency 
>> 8); 
 225                                         SampleRate
[0] = (CurrentAudioSampleFrequency 
&  0xFF); 
 227                                         Endpoint_ClearSETUP(); 
 228                                         Endpoint_Write_Control_Stream_LE(SampleRate
, sizeof(SampleRate
)); 
 237 /** ISR to handle the reloading of the PWM timer with the next sample. */ 
 238 ISR(TIMER0_COMPA_vect
, ISR_BLOCK
) 
 240         uint8_t PrevEndpoint 
= Endpoint_GetCurrentEndpoint(); 
 242         /* Select the audio stream endpoint */ 
 243         Endpoint_SelectEndpoint(AUDIO_STREAM_EPADDR
); 
 245         /* Check if the current endpoint can be read from (contains a packet) and the host is sending data */ 
 246         if (Endpoint_IsOUTReceived() && StreamingAudioInterfaceSelected
) 
 248                 /* Retrieve the signed 16-bit left and right audio samples, convert to 8-bit */ 
 249                 int8_t LeftSample_8Bit   
= ((int16_t)Endpoint_Read_16_LE() >> 8); 
 250                 int8_t RightSample_8Bit  
= ((int16_t)Endpoint_Read_16_LE() >> 8); 
 252                 /* Mix the two channels together to produce a mono, 8-bit sample */ 
 253                 int8_t MixedSample_8Bit  
= (((int16_t)LeftSample_8Bit 
+ (int16_t)RightSample_8Bit
) >> 1); 
 255                 /* Check to see if the bank is now empty */ 
 256                 if (!(Endpoint_IsReadWriteAllowed())) 
 258                         /* Acknowledge the packet, clear the bank ready for the next packet */ 
 262                 #if defined(AUDIO_OUT_MONO) 
 263                 /* Load the sample into the PWM timer channel */ 
 264                 OCR3A 
= (MixedSample_8Bit 
^ (1 << 7)); 
 265                 #elif defined(AUDIO_OUT_STEREO) 
 266                 /* Load the dual 8-bit samples into the PWM timer channels */ 
 267                 OCR3A 
= (LeftSample_8Bit  
^ (1 << 7)); 
 268                 OCR3B 
= (RightSample_8Bit 
^ (1 << 7)); 
 269                 #elif defined(AUDIO_OUT_PORTC) 
 270                 /* Load the 8-bit mixed sample into PORTC */ 
 271                 PORTC 
= MixedSample_8Bit
; 
 274                 uint8_t LEDMask 
= LEDS_NO_LEDS
; 
 276                 /* Turn on LEDs as the sample amplitude increases */ 
 277                 if (MixedSample_8Bit 
> 16) 
 278                   LEDMask 
= (LEDS_LED1 
| LEDS_LED2 
| LEDS_LED3 
| LEDS_LED4
); 
 279                 else if (MixedSample_8Bit 
> 8) 
 280                   LEDMask 
= (LEDS_LED1 
| LEDS_LED2 
| LEDS_LED3
); 
 281                 else if (MixedSample_8Bit 
> 4) 
 282                   LEDMask 
= (LEDS_LED1 
| LEDS_LED2
); 
 283                 else if (MixedSample_8Bit 
> 2) 
 284                   LEDMask 
= (LEDS_LED1
); 
 286                 LEDs_SetAllLEDs(LEDMask
); 
 289         Endpoint_SelectEndpoint(PrevEndpoint
);