Run wspurify script on /trunk/ and /branches/ C source files, to remove any trailing...
[pub/lufa.git] / Demos / Device / ClassDriver / AudioOutput / AudioOutput.c
1 /*
2 LUFA Library
3 Copyright (C) Dean Camera, 2011.
4
5 dean [at] fourwalledcubicle [dot] com
6 www.lufa-lib.org
7 */
8
9 /*
10 Copyright 2011 Dean Camera (dean [at] fourwalledcubicle [dot] com)
11
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.
20
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
28 this software.
29 */
30
31 /** \file
32 *
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.
35 */
36
37 #include "AudioOutput.h"
38
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.
42 */
43 USB_ClassInfo_Audio_Device_t Speaker_Audio_Interface =
44 {
45 .Config =
46 {
47 .StreamingInterfaceNumber = 1,
48
49 .DataOUTEndpointNumber = AUDIO_STREAM_EPNUM,
50 .DataOUTEndpointSize = AUDIO_STREAM_EPSIZE,
51 },
52 };
53
54 /** Current audio sampling frequency of the streaming audio endpoint. */
55 static uint32_t CurrentAudioSampleFrequency = 48000;
56
57
58 /** Main program entry point. This routine contains the overall program flow, including initial
59 * setup of all components and the main program loop.
60 */
61 int main(void)
62 {
63 SetupHardware();
64
65 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
66 sei();
67
68 for (;;)
69 {
70 Audio_Device_USBTask(&Speaker_Audio_Interface);
71 USB_USBTask();
72 }
73 }
74
75 /** Configures the board hardware and chip peripherals for the demo's functionality. */
76 void SetupHardware(void)
77 {
78 /* Disable watchdog if enabled by bootloader/fuses */
79 MCUSR &= ~(1 << WDRF);
80 wdt_disable();
81
82 /* Disable clock division */
83 clock_prescale_set(clock_div_1);
84
85 /* Hardware Initialization */
86 LEDs_Init();
87 USB_Init();
88 }
89
90 /** ISR to handle the reloading of the PWM timer with the next sample. */
91 ISR(TIMER0_COMPA_vect, ISR_BLOCK)
92 {
93 uint8_t PrevEndpoint = Endpoint_GetCurrentEndpoint();
94
95 /* Check that the USB bus is ready for the next sample to read */
96 if (Audio_Device_IsSampleReceived(&Speaker_Audio_Interface))
97 {
98 /* Retrieve the signed 16-bit left and right audio samples, convert to 8-bit */
99 int8_t LeftSample_8Bit = (Audio_Device_ReadSample16(&Speaker_Audio_Interface) >> 8);
100 int8_t RightSample_8Bit = (Audio_Device_ReadSample16(&Speaker_Audio_Interface) >> 8);
101
102 /* Mix the two channels together to produce a mono, 8-bit sample */
103 int8_t MixedSample_8Bit = (((int16_t)LeftSample_8Bit + (int16_t)RightSample_8Bit) >> 1);
104
105 #if defined(AUDIO_OUT_MONO)
106 /* Load the sample into the PWM timer channel */
107 OCR3A = (MixedSample_8Bit ^ (1 << 7));
108 #elif defined(AUDIO_OUT_STEREO)
109 /* Load the dual 8-bit samples into the PWM timer channels */
110 OCR3A = (LeftSample_8Bit ^ (1 << 7));
111 OCR3B = (RightSample_8Bit ^ (1 << 7));
112 #elif defined(AUDIO_OUT_PORTC)
113 /* Load the 8-bit mixed sample into PORTC */
114 PORTC = MixedSample_8Bit;
115 #endif
116
117 uint8_t LEDMask = LEDS_NO_LEDS;
118
119 /* Turn on LEDs as the sample amplitude increases */
120 if (MixedSample_8Bit > 16)
121 LEDMask = (LEDS_LED1 | LEDS_LED2 | LEDS_LED3 | LEDS_LED4);
122 else if (MixedSample_8Bit > 8)
123 LEDMask = (LEDS_LED1 | LEDS_LED2 | LEDS_LED3);
124 else if (MixedSample_8Bit > 4)
125 LEDMask = (LEDS_LED1 | LEDS_LED2);
126 else if (MixedSample_8Bit > 2)
127 LEDMask = (LEDS_LED1);
128
129 LEDs_SetAllLEDs(LEDMask);
130 }
131
132 Endpoint_SelectEndpoint(PrevEndpoint);
133 }
134
135 /** Event handler for the library USB Connection event. */
136 void EVENT_USB_Device_Connect(void)
137 {
138 LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
139
140 /* Sample reload timer initialization */
141 TIMSK0 = (1 << OCIE0A);
142 OCR0A = ((F_CPU / 8 / CurrentAudioSampleFrequency) - 1);
143 TCCR0A = (1 << WGM01); // CTC mode
144 TCCR0B = (1 << CS01); // Fcpu/8 speed
145
146 #if defined(AUDIO_OUT_MONO)
147 /* Set speaker as output */
148 DDRC |= (1 << 6);
149 #elif defined(AUDIO_OUT_STEREO)
150 /* Set speakers as outputs */
151 DDRC |= ((1 << 6) | (1 << 5));
152 #elif defined(AUDIO_OUT_PORTC)
153 /* Set PORTC as outputs */
154 DDRC |= 0xFF;
155 #endif
156
157 #if (defined(AUDIO_OUT_MONO) || defined(AUDIO_OUT_STEREO))
158 /* PWM speaker timer initialization */
159 TCCR3A = ((1 << WGM30) | (1 << COM3A1) | (1 << COM3A0)
160 | (1 << COM3B1) | (1 << COM3B0)); // Set on match, clear on TOP
161 TCCR3B = ((1 << WGM32) | (1 << CS30)); // Fast 8-Bit PWM, F_CPU speed
162 #endif
163 }
164
165 /** Event handler for the library USB Disconnection event. */
166 void EVENT_USB_Device_Disconnect(void)
167 {
168 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
169
170 /* Stop the sample reload timer */
171 TCCR0B = 0;
172
173 #if (defined(AUDIO_OUT_MONO) || defined(AUDIO_OUT_STEREO))
174 /* Stop the PWM generation timer */
175 TCCR3B = 0;
176 #endif
177
178 #if defined(AUDIO_OUT_MONO)
179 /* Set speaker as input to reduce current draw */
180 DDRC &= ~(1 << 6);
181 #elif defined(AUDIO_OUT_STEREO)
182 /* Set speakers as inputs to reduce current draw */
183 DDRC &= ~((1 << 6) | (1 << 5));
184 #elif defined(AUDIO_OUT_PORTC)
185 /* Set PORTC low */
186 PORTC = 0x00;
187 #endif
188 }
189
190 /** Event handler for the library USB Configuration Changed event. */
191 void EVENT_USB_Device_ConfigurationChanged(void)
192 {
193 bool ConfigSuccess = true;
194
195 ConfigSuccess &= Audio_Device_ConfigureEndpoints(&Speaker_Audio_Interface);
196
197 LEDs_SetAllLEDs(ConfigSuccess ? LEDMASK_USB_READY : LEDMASK_USB_ERROR);
198 }
199
200 /** Event handler for the library USB Control Request reception event. */
201 void EVENT_USB_Device_ControlRequest(void)
202 {
203 Audio_Device_ProcessControlRequest(&Speaker_Audio_Interface);
204 }
205
206 /** Audio class driver callback for the setting and retrieval of streaming endpoint properties. This callback must be implemented
207 * in the user application to handle property manipulations on streaming audio endpoints.
208 *
209 * When the DataLength parameter is NULL, this callback should only indicate whether the specified operation is valid for
210 * the given endpoint index, and should return as fast as possible. When non-NULL, this value may be altered for GET operations
211 * to indicate the size of the retreived data.
212 *
213 * \note The length of the retrieved data stored into the Data buffer on GET operations should not exceed the initial value
214 * of the \c DataLength parameter.
215 *
216 * \param[in,out] AudioInterfaceInfo Pointer to a structure containing an Audio Class configuration and state.
217 * \param[in] EndpointProperty Property of the endpoint to get or set, a value from Audio_ClassRequests_t.
218 * \param[in] EndpointAddress Address of the streaming endpoint whose property is being referenced.
219 * \param[in] EndpointControl Parameter of the endpoint to get or set, a value from Audio_EndpointControls_t.
220 * \param[in,out] DataLength For SET operations, the length of the parameter data to set. For GET operations, the maximum
221 * length of the retrieved data. When NULL, the function should return whether the given property
222 * and parameter is valid for the requested endpoint without reading or modifying the Data buffer.
223 * \param[in,out] Data Pointer to a location where the parameter data is stored for SET operations, or where
224 * the retrieved data is to be stored for GET operations.
225 *
226 * \return Boolean true if the property get/set was successful, false otherwise
227 */
228 bool CALLBACK_Audio_Device_GetSetEndpointProperty(USB_ClassInfo_Audio_Device_t* const AudioInterfaceInfo,
229 const uint8_t EndpointProperty,
230 const uint8_t EndpointAddress,
231 const uint8_t EndpointControl,
232 uint16_t* const DataLength,
233 uint8_t* Data)
234 {
235 /* Check the requested endpoint to see if a supported endpoint is being manipulated */
236 if (EndpointAddress == (ENDPOINT_DIR_OUT | Speaker_Audio_Interface.Config.DataOUTEndpointNumber))
237 {
238 /* Check the requested control to see if a supported control is being manipulated */
239 if (EndpointControl == AUDIO_EPCONTROL_SamplingFreq)
240 {
241 switch (EndpointProperty)
242 {
243 case AUDIO_REQ_SetCurrent:
244 /* Check if we are just testing for a valid property, or actually adjusting it */
245 if (DataLength != NULL)
246 {
247 /* Set the new sampling frequency to the value given by the host */
248 CurrentAudioSampleFrequency = (((uint32_t)Data[2] << 16) | ((uint32_t)Data[1] << 8) | (uint32_t)Data[0]);
249
250 /* Adjust sample reload timer to the new frequency */
251 OCR0A = ((F_CPU / 8 / CurrentAudioSampleFrequency) - 1);
252 }
253
254 return true;
255 case AUDIO_REQ_GetCurrent:
256 /* Check if we are just testing for a valid property, or actually reading it */
257 if (DataLength != NULL)
258 {
259 *DataLength = 3;
260
261 Data[2] = (CurrentAudioSampleFrequency >> 16);
262 Data[1] = (CurrentAudioSampleFrequency >> 8);
263 Data[0] = (CurrentAudioSampleFrequency & 0xFF);
264 }
265
266 return true;
267 }
268 }
269 }
270
271 return false;
272 }
273