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