Endpoint configuration is now refined to give better output when all configurations...
[pub/USBasp.git] / Demos / Device / AudioOutput / AudioOutput.c
1 /*
2 LUFA Library
3 Copyright (C) Dean Camera, 2009.
4
5 dean [at] fourwalledcubicle [dot] com
6 www.fourwalledcubicle.com
7 */
8
9 /*
10 Copyright 2009 Dean Camera (dean [at] fourwalledcubicle [dot] com)
11
12 Permission to use, copy, modify, and distribute this software
13 and its documentation for any purpose and without fee is hereby
14 granted, provided that the above copyright notice appear in all
15 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 Audio Output demo. This file contains the main tasks of the demo and
34 * is responsible for the initial application hardware configuration.
35 */
36
37 #include "AudioOutput.h"
38
39 /* Scheduler Task List */
40 TASK_LIST
41 {
42 { .Task = USB_USBTask , .TaskStatus = TASK_STOP },
43 { .Task = USB_Audio_Task , .TaskStatus = TASK_STOP },
44 };
45
46
47 /** Main program entry point. This routine configures the hardware required by the application, then
48 * starts the scheduler to run the application tasks.
49 */
50 int main(void)
51 {
52 /* Disable watchdog if enabled by bootloader/fuses */
53 MCUSR &= ~(1 << WDRF);
54 wdt_disable();
55
56 /* Disable clock division */
57 clock_prescale_set(clock_div_1);
58
59 /* Hardware Initialization */
60 LEDs_Init();
61
62 /* Indicate USB not ready */
63 UpdateStatus(Status_USBNotReady);
64
65 /* Initialize Scheduler so that it can be used */
66 Scheduler_Init();
67
68 /* Initialize USB Subsystem */
69 USB_Init();
70
71 /* Scheduling - routine never returns, so put this last in the main function */
72 Scheduler_Start();
73 }
74
75 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs, and
76 * configures the sample update and PWM timers.
77 */
78 EVENT_HANDLER(USB_Connect)
79 {
80 /* Start USB management task */
81 Scheduler_SetTaskMode(USB_USBTask, TASK_RUN);
82
83 /* Indicate USB enumerating */
84 UpdateStatus(Status_USBEnumerating);
85
86 /* Sample reload timer initialization */
87 OCR0A = (F_CPU / AUDIO_SAMPLE_FREQUENCY) - 1;
88 TCCR0A = (1 << WGM01); // CTC mode
89 TCCR0B = (1 << CS00); // Fcpu speed
90
91 #if defined(AUDIO_OUT_MONO)
92 /* Set speaker as output */
93 DDRC |= (1 << 6);
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 */
99 DDRC |= 0xFF;
100 #endif
101
102 #if (defined(AUDIO_OUT_MONO) || defined(AUDIO_OUT_STEREO))
103 /* PWM speaker timer initialization */
104 TCCRxA = ((1 << WGMx0) | (1 << COMxA1) | (1 << COMxA0)
105 | (1 << COMxB1) | (1 << COMxB0)); // Set on match, clear on TOP
106 TCCRxB = ((1 << WGMx2) | (1 << CSx0)); // Fast 8-Bit PWM, Fcpu speed
107 #endif
108 }
109
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.
112 */
113 EVENT_HANDLER(USB_Disconnect)
114 {
115 /* Stop the timers */
116 TCCR0B = 0;
117 #if (defined(AUDIO_OUT_MONO) || defined(AUDIO_OUT_STEREO))
118 TCCRxB = 0;
119 #endif
120
121 #if defined(AUDIO_OUT_MONO)
122 /* Set speaker as input to reduce current draw */
123 DDRC &= ~(1 << 6);
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)
128 /* Set PORTC low */
129 PORTC = 0x00;
130 #endif
131
132 /* Stop running audio and USB management tasks */
133 Scheduler_SetTaskMode(USB_Audio_Task, TASK_STOP);
134 Scheduler_SetTaskMode(USB_USBTask, TASK_STOP);
135
136 /* Indicate USB not ready */
137 UpdateStatus(Status_USBNotReady);
138 }
139
140 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host set the current configuration
141 * of the USB device after enumeration - the device endpoints are configured.
142 */
143 EVENT_HANDLER(USB_ConfigurationChanged)
144 {
145 /* Setup audio stream endpoint */
146 Endpoint_ConfigureEndpoint(AUDIO_STREAM_EPNUM, EP_TYPE_ISOCHRONOUS,
147 ENDPOINT_DIR_OUT, AUDIO_STREAM_EPSIZE,
148 ENDPOINT_BANK_DOUBLE);
149
150 /* Indicate USB connected and ready */
151 UpdateStatus(Status_USBReady);
152 }
153
154 /** Event handler for the USB_UnhandledControlPacket event. This is used to catch standard and class specific
155 * control requests that are not handled internally by the USB library (including the Audio class-specific
156 * requests) so that they can be handled appropriately for the application.
157 */
158 EVENT_HANDLER(USB_UnhandledControlPacket)
159 {
160 /* Process General and Audio specific control requests */
161 switch (USB_ControlRequest.bRequest)
162 {
163 case REQ_SetInterface:
164 /* Set Interface is not handled by the library, as its function is application-specific */
165 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_STANDARD | REQREC_INTERFACE))
166 {
167 Endpoint_ClearSETUP();
168
169 /* Check if the host is enabling the audio interface (setting AlternateSetting to 1) */
170 if (USB_ControlRequest.wValue)
171 {
172 /* Start audio task */
173 Scheduler_SetTaskMode(USB_Audio_Task, TASK_RUN);
174 }
175 else
176 {
177 /* Stop audio task */
178 Scheduler_SetTaskMode(USB_Audio_Task, TASK_STOP);
179 }
180
181 /* Acknowledge status stage */
182 while (!(Endpoint_IsINReady()));
183 Endpoint_ClearIN();
184 }
185
186 break;
187 }
188 }
189
190 /** Function to manage status updates to the user. This is done via LEDs on the given board, if available, but may be changed to
191 * log to a serial port, or anything else that is suitable for status updates.
192 *
193 * \param CurrentStatus Current status of the system, from the AudioOutput_StatusCodes_t enum
194 */
195 void UpdateStatus(uint8_t CurrentStatus)
196 {
197 uint8_t LEDMask = LEDS_NO_LEDS;
198
199 /* Set the LED mask to the appropriate LED mask based on the given status code */
200 switch (CurrentStatus)
201 {
202 case Status_USBNotReady:
203 LEDMask = (LEDS_LED1);
204 break;
205 case Status_USBEnumerating:
206 LEDMask = (LEDS_LED1 | LEDS_LED2);
207 break;
208 case Status_USBReady:
209 LEDMask = (LEDS_LED2 | LEDS_LED4);
210 break;
211 }
212
213 /* Set the board LEDs to the new LED mask */
214 LEDs_SetAllLEDs(LEDMask);
215 }
216
217 /** Task to manage the Audio interface, reading in audio samples from the host, and outputting them to the speakers/LEDs as
218 * desired.
219 */
220 TASK(USB_Audio_Task)
221 {
222 /* Select the audio stream endpoint */
223 Endpoint_SelectEndpoint(AUDIO_STREAM_EPNUM);
224
225 /* Check if the current endpoint can be read from (contains a packet) and that the next sample should be read */
226 if (Endpoint_IsOUTReceived() && (TIFR0 & (1 << OCF0A)))
227 {
228 /* Clear the sample reload timer */
229 TIFR0 |= (1 << OCF0A);
230
231 /* Retrieve the signed 16-bit left and right audio samples */
232 int16_t LeftSample_16Bit = (int16_t)Endpoint_Read_Word_LE();
233 int16_t RightSample_16Bit = (int16_t)Endpoint_Read_Word_LE();
234
235 /* Check to see if the bank is now empty */
236 if (!(Endpoint_IsReadWriteAllowed()))
237 {
238 /* Acknowledge the packet, clear the bank ready for the next packet */
239 Endpoint_ClearOUT();
240 }
241
242 /* Massage signed 16-bit left and right audio samples into signed 8-bit */
243 int8_t LeftSample_8Bit = (LeftSample_16Bit >> 8);
244 int8_t RightSample_8Bit = (RightSample_16Bit >> 8);
245
246 #if defined(AUDIO_OUT_MONO)
247 /* Mix the two channels together to produce a mono, 8-bit sample */
248 int8_t MixedSample_8Bit = (((int16_t)LeftSample_8Bit + (int16_t)RightSample_8Bit) >> 1);
249
250 /* Load the sample into the PWM timer channel */
251 OCRxA = ((uint8_t)MixedSample_8Bit ^ (1 << 7));
252 #elif defined(AUDIO_OUT_STEREO)
253 /* Load the dual 8-bit samples into the PWM timer channels */
254 OCRxA = ((uint8_t)LeftSample_8Bit ^ (1 << 7));
255 OCRxB = ((uint8_t)RightSample_8Bit ^ (1 << 7));
256 #elif defined(AUDIO_OUT_PORTC)
257 /* Mix the two channels together to produce a mono, 8-bit sample */
258 int8_t MixedSample_8Bit = (((int16_t)LeftSample_8Bit + (int16_t)RightSample_8Bit) >> 1);
259
260 PORTC = MixedSample_8Bit;
261 #else
262 uint8_t LEDMask = LEDS_NO_LEDS;
263
264 /* Make left channel positive (absolute) */
265 if (LeftSample_8Bit < 0)
266 LeftSample_8Bit = -LeftSample_8Bit;
267
268 /* Make right channel positive (absolute) */
269 if (RightSample_8Bit < 0)
270 RightSample_8Bit = -RightSample_8Bit;
271
272 /* Set first LED based on sample value */
273 if (LeftSample_8Bit < ((128 / 8) * 1))
274 LEDMask |= LEDS_LED2;
275 else if (LeftSample_8Bit < ((128 / 8) * 3))
276 LEDMask |= (LEDS_LED1 | LEDS_LED2);
277 else
278 LEDMask |= LEDS_LED1;
279
280 /* Set second LED based on sample value */
281 if (RightSample_8Bit < ((128 / 8) * 1))
282 LEDMask |= LEDS_LED4;
283 else if (RightSample_8Bit < ((128 / 8) * 3))
284 LEDMask |= (LEDS_LED3 | LEDS_LED4);
285 else
286 LEDMask |= LEDS_LED3;
287
288 LEDs_SetAllLEDs(LEDMask);
289 #endif
290 }
291 }