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 
  34  *  the demo and is responsible for the initial application hardware configuration. 
  37 #include "AudioOutput.h" 
  39 /** LUFA Audio Class driver interface configuration and state information. This structure is 
  40  *  passed to all Audio Class driver functions, so that multiple instances of the same class 
  41  *  within a device can be differentiated from one another. 
  43 USB_ClassInfo_Audio_Device_t Speaker_Audio_Interface 
= 
  47                                 .ControlInterfaceNumber   
= INTERFACE_ID_AudioControl
, 
  48                                 .StreamingInterfaceNumber 
= INTERFACE_ID_AudioStream
, 
  51                                                 .Address          
= AUDIO_STREAM_EPADDR
, 
  52                                                 .Size             
= AUDIO_STREAM_EPSIZE
, 
  58 /** Current audio sampling frequency of the streaming audio endpoint. */ 
  59 static uint32_t CurrentAudioSampleFrequency 
= 48000; 
  62 /** Main program entry point. This routine contains the overall program flow, including initial 
  63  *  setup of all components and the main program loop. 
  69         LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY
); 
  70         GlobalInterruptEnable(); 
  74                 Audio_Device_USBTask(&Speaker_Audio_Interface
); 
  79 /** Configures the board hardware and chip peripherals for the demo's functionality. */ 
  80 void SetupHardware(void) 
  82 #if (ARCH == ARCH_AVR8) 
  83         /* Disable watchdog if enabled by bootloader/fuses */ 
  84         MCUSR 
&= ~(1 << WDRF
); 
  87         /* Disable clock division */ 
  88         clock_prescale_set(clock_div_1
); 
  91         /* Hardware Initialization */ 
  96 /** ISR to handle the reloading of the PWM timer with the next sample. */ 
  97 ISR(TIMER0_COMPA_vect
, ISR_BLOCK
) 
  99         uint8_t PrevEndpoint 
= Endpoint_GetCurrentEndpoint(); 
 101         /* Check that the USB bus is ready for the next sample to read */ 
 102         if (Audio_Device_IsSampleReceived(&Speaker_Audio_Interface
)) 
 104                 /* Retrieve the signed 16-bit left and right audio samples, convert to 8-bit */ 
 105                 int8_t LeftSample_8Bit  
= (Audio_Device_ReadSample16(&Speaker_Audio_Interface
) >> 8); 
 106                 int8_t RightSample_8Bit 
= (Audio_Device_ReadSample16(&Speaker_Audio_Interface
) >> 8); 
 108                 /* Mix the two channels together to produce a mono, 8-bit sample */ 
 109                 int8_t MixedSample_8Bit 
= (((int16_t)LeftSample_8Bit 
+ (int16_t)RightSample_8Bit
) >> 1); 
 111                 #if defined(AUDIO_OUT_MONO) 
 112                 /* Load the sample into the PWM timer channel */ 
 113                 OCR3A 
= (MixedSample_8Bit 
^ (1 << 7)); 
 114                 #elif defined(AUDIO_OUT_STEREO) 
 115                 /* Load the dual 8-bit samples into the PWM timer channels */ 
 116                 OCR3A 
= (LeftSample_8Bit  
^ (1 << 7)); 
 117                 OCR3B 
= (RightSample_8Bit 
^ (1 << 7)); 
 118                 #elif defined(AUDIO_OUT_PORTC) 
 119                 /* Load the 8-bit mixed sample into PORTC */ 
 120                 PORTC 
= MixedSample_8Bit
; 
 123                 uint8_t LEDMask 
= LEDS_NO_LEDS
; 
 125                 /* Turn on LEDs as the sample amplitude increases */ 
 126                 if (MixedSample_8Bit 
> 16) 
 127                   LEDMask 
= (LEDS_LED1 
| LEDS_LED2 
| LEDS_LED3 
| LEDS_LED4
); 
 128                 else if (MixedSample_8Bit 
> 8) 
 129                   LEDMask 
= (LEDS_LED1 
| LEDS_LED2 
| LEDS_LED3
); 
 130                 else if (MixedSample_8Bit 
> 4) 
 131                   LEDMask 
= (LEDS_LED1 
| LEDS_LED2
); 
 132                 else if (MixedSample_8Bit 
> 2) 
 133                   LEDMask 
= (LEDS_LED1
); 
 135                 LEDs_SetAllLEDs(LEDMask
); 
 138         Endpoint_SelectEndpoint(PrevEndpoint
); 
 141 /** Event handler for the library USB Connection event. */ 
 142 void EVENT_USB_Device_Connect(void) 
 144         LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING
); 
 146         /* Sample reload timer initialization */ 
 147         TIMSK0  
= (1 << OCIE0A
); 
 148         OCR0A   
= ((F_CPU 
/ 8 / CurrentAudioSampleFrequency
) - 1); 
 149         TCCR0A  
= (1 << WGM01
);  // CTC mode 
 150         TCCR0B  
= (1 << CS01
);   // Fcpu/8 speed 
 152         #if defined(AUDIO_OUT_MONO) 
 153         /* Set speaker as output */ 
 155         #elif defined(AUDIO_OUT_STEREO) 
 156         /* Set speakers as outputs */ 
 157         DDRC   
|= ((1 << 6) | (1 << 5)); 
 158         #elif defined(AUDIO_OUT_PORTC) 
 159         /* Set PORTC as outputs */ 
 163         #if (defined(AUDIO_OUT_MONO) || defined(AUDIO_OUT_STEREO)) 
 164         /* PWM speaker timer initialization */ 
 165         TCCR3A  
= ((1 << WGM30
) | (1 << COM3A1
) | (1 << COM3A0
) 
 166                 | (1 << COM3B1
) | (1 << COM3B0
)); // Set on match, clear on TOP 
 167         TCCR3B  
= ((1 << WGM32
) | (1 << CS30
));  // Fast 8-Bit PWM, F_CPU speed 
 171 /** Event handler for the library USB Disconnection event. */ 
 172 void EVENT_USB_Device_Disconnect(void) 
 174         LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY
); 
 176         /* Stop the sample reload timer */ 
 179         #if (defined(AUDIO_OUT_MONO) || defined(AUDIO_OUT_STEREO)) 
 180         /* Stop the PWM generation timer */ 
 184         #if defined(AUDIO_OUT_MONO) 
 185         /* Set speaker as input to reduce current draw */ 
 187         #elif defined(AUDIO_OUT_STEREO) 
 188         /* Set speakers as inputs to reduce current draw */ 
 189         DDRC  
&= ~((1 << 6) | (1 << 5)); 
 190         #elif defined(AUDIO_OUT_PORTC) 
 196 /** Event handler for the library USB Configuration Changed event. */ 
 197 void EVENT_USB_Device_ConfigurationChanged(void) 
 199         bool ConfigSuccess 
= true; 
 201         ConfigSuccess 
&= Audio_Device_ConfigureEndpoints(&Speaker_Audio_Interface
); 
 203         LEDs_SetAllLEDs(ConfigSuccess ? LEDMASK_USB_READY 
: LEDMASK_USB_ERROR
); 
 206 /** Event handler for the library USB Control Request reception event. */ 
 207 void EVENT_USB_Device_ControlRequest(void) 
 209         Audio_Device_ProcessControlRequest(&Speaker_Audio_Interface
); 
 212 /** Audio class driver callback for the setting and retrieval of streaming endpoint properties. This callback must be implemented 
 213  *  in the user application to handle property manipulations on streaming audio endpoints. 
 215  *  When the DataLength parameter is NULL, this callback should only indicate whether the specified operation is valid for 
 216  *  the given endpoint index, and should return as fast as possible. When non-NULL, this value may be altered for GET operations 
 217  *  to indicate the size of the retrieved data. 
 219  *  \note The length of the retrieved data stored into the Data buffer on GET operations should not exceed the initial value 
 220  *        of the \c DataLength parameter. 
 222  *  \param[in,out] AudioInterfaceInfo  Pointer to a structure containing an Audio Class configuration and state. 
 223  *  \param[in]     EndpointProperty    Property of the endpoint to get or set, a value from Audio_ClassRequests_t. 
 224  *  \param[in]     EndpointAddress     Address of the streaming endpoint whose property is being referenced. 
 225  *  \param[in]     EndpointControl     Parameter of the endpoint to get or set, a value from Audio_EndpointControls_t. 
 226  *  \param[in,out] DataLength          For SET operations, the length of the parameter data to set. For GET operations, the maximum 
 227  *                                     length of the retrieved data. When NULL, the function should return whether the given property 
 228  *                                     and parameter is valid for the requested endpoint without reading or modifying the Data buffer. 
 229  *  \param[in,out] Data                Pointer to a location where the parameter data is stored for SET operations, or where 
 230  *                                     the retrieved data is to be stored for GET operations. 
 232  *  \return Boolean \c true if the property get/set was successful, \c false otherwise 
 234 bool CALLBACK_Audio_Device_GetSetEndpointProperty(USB_ClassInfo_Audio_Device_t
* const AudioInterfaceInfo
, 
 235                                                   const uint8_t EndpointProperty
, 
 236                                                   const uint8_t EndpointAddress
, 
 237                                                   const uint8_t EndpointControl
, 
 238                                                   uint16_t* const DataLength
, 
 241         /* Check the requested endpoint to see if a supported endpoint is being manipulated */ 
 242         if (EndpointAddress 
== Speaker_Audio_Interface
.Config
.DataOUTEndpoint
.Address
) 
 244                 /* Check the requested control to see if a supported control is being manipulated */ 
 245                 if (EndpointControl 
== AUDIO_EPCONTROL_SamplingFreq
) 
 247                         switch (EndpointProperty
) 
 249                                 case AUDIO_REQ_SetCurrent
: 
 250                                         /* Check if we are just testing for a valid property, or actually adjusting it */ 
 251                                         if (DataLength 
!= NULL
) 
 253                                                 /* Set the new sampling frequency to the value given by the host */ 
 254                                                 CurrentAudioSampleFrequency 
= (((uint32_t)Data
[2] << 16) | ((uint32_t)Data
[1] << 8) | (uint32_t)Data
[0]); 
 256                                                 /* Adjust sample reload timer to the new frequency */ 
 257                                                 OCR0A 
= ((F_CPU 
/ 8 / CurrentAudioSampleFrequency
) - 1); 
 261                                 case AUDIO_REQ_GetCurrent
: 
 262                                         /* Check if we are just testing for a valid property, or actually reading it */ 
 263                                         if (DataLength 
!= NULL
) 
 267                                                 Data
[2] = (CurrentAudioSampleFrequency 
>> 16); 
 268                                                 Data
[1] = (CurrentAudioSampleFrequency 
>> 8); 
 269                                                 Data
[0] = (CurrentAudioSampleFrequency 
&  0xFF); 
 280 /** Audio class driver callback for the setting and retrieval of streaming interface properties. This callback must be implemented 
 281  *  in the user application to handle property manipulations on streaming audio interfaces. 
 283  *  When the DataLength parameter is NULL, this callback should only indicate whether the specified operation is valid for 
 284  *  the given entity and should return as fast as possible. When non-NULL, this value may be altered for GET operations 
 285  *  to indicate the size of the retrieved data. 
 287  *  \note The length of the retrieved data stored into the Data buffer on GET operations should not exceed the initial value 
 288  *        of the \c DataLength parameter. 
 290  *  \param[in,out] AudioInterfaceInfo  Pointer to a structure containing an Audio Class configuration and state. 
 291  *  \param[in]     Property            Property of the interface to get or set, a value from Audio_ClassRequests_t. 
 292  *  \param[in]     EntityAddress       Address of the audio entity whose property is being referenced. 
 293  *  \param[in]     Parameter           Parameter of the entity to get or set, specific to each type of entity (see USB Audio specification). 
 294  *  \param[in,out] DataLength          For SET operations, the length of the parameter data to set. For GET operations, the maximum 
 295  *                                     length of the retrieved data. When NULL, the function should return whether the given property 
 296  *                                     and parameter is valid for the requested endpoint without reading or modifying the Data buffer. 
 297  *  \param[in,out] Data                Pointer to a location where the parameter data is stored for SET operations, or where 
 298  *                                     the retrieved data is to be stored for GET operations. 
 300  *  \return Boolean \c true if the property GET/SET was successful, \c false otherwise 
 302 bool CALLBACK_Audio_Device_GetSetInterfaceProperty(USB_ClassInfo_Audio_Device_t
* const AudioInterfaceInfo
, 
 303                                                    const uint8_t Property
, 
 304                                                    const uint8_t EntityAddress
, 
 305                                                    const uint16_t Parameter
, 
 306                                                    uint16_t* const DataLength
, 
 309         /* No audio interface entities in the device descriptor, thus no properties to get or set. */