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