Add branch for the conversion of demos to use standard C header files for configurati...
[pub/USBasp.git] / Demos / Device / LowLevel / AudioOutput / AudioOutput.c
1 /*
2 LUFA Library
3 Copyright (C) Dean Camera, 2012.
4
5 dean [at] fourwalledcubicle [dot] com
6 www.lufa-lib.org
7 */
8
9 /*
10 Copyright 2012 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 the demo and
34 * is responsible for the initial application hardware configuration.
35 */
36
37 #include "AudioOutput.h"
38
39 /** Flag to indicate if the streaming audio alternative interface has been selected by the host. */
40 static bool StreamingAudioInterfaceSelected = false;
41
42 /** Current audio sampling frequency of the streaming audio endpoint. */
43 static uint32_t CurrentAudioSampleFrequency = 48000;
44
45
46 /** Main program entry point. This routine contains the overall program flow, including initial
47 * setup of all components and the main program loop.
48 */
49 int main(void)
50 {
51 SetupHardware();
52
53 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
54 sei();
55
56 for (;;)
57 {
58 USB_USBTask();
59 }
60 }
61
62 /** Configures the board hardware and chip peripherals for the demo's functionality. */
63 void SetupHardware(void)
64 {
65 /* Disable watchdog if enabled by bootloader/fuses */
66 MCUSR &= ~(1 << WDRF);
67 wdt_disable();
68
69 /* Disable clock division */
70 clock_prescale_set(clock_div_1);
71
72 /* Hardware Initialization */
73 LEDs_Init();
74 USB_Init();
75 }
76
77 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs, and
78 * configures the sample update and PWM timers.
79 */
80 void EVENT_USB_Device_Connect(void)
81 {
82 /* Indicate USB enumerating */
83 LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
84
85 /* Sample reload timer initialization */
86 TIMSK0 = (1 << OCIE0A);
87 OCR0A = ((F_CPU / 8 / CurrentAudioSampleFrequency) - 1);
88 TCCR0A = (1 << WGM01); // CTC mode
89 TCCR0B = (1 << CS01); // Fcpu/8 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 TCCR3A = ((1 << WGM30) | (1 << COM3A1) | (1 << COM3A0)
105 | (1 << COM3B1) | (1 << COM3B0)); // Set on match, clear on TOP
106 TCCR3B = ((1 << WGM32) | (1 << CS30)); // Fast 8-Bit PWM, F_CPU 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 void EVENT_USB_Device_Disconnect(void)
114 {
115 /* Stop the timers */
116 TCCR0B = 0;
117 #if (defined(AUDIO_OUT_MONO) || defined(AUDIO_OUT_STEREO))
118 TCCR3B = 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 /* Indicate streaming audio interface not selected */
133 StreamingAudioInterfaceSelected = false;
134
135 /* Indicate USB not ready */
136 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
137 }
138
139 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host set the current configuration
140 * of the USB device after enumeration - the device endpoints are configured.
141 */
142 void EVENT_USB_Device_ConfigurationChanged(void)
143 {
144 bool ConfigSuccess = true;
145
146 /* Setup Audio Stream Endpoint */
147 ConfigSuccess &= Endpoint_ConfigureEndpoint(AUDIO_STREAM_EPADDR, EP_TYPE_ISOCHRONOUS, AUDIO_STREAM_EPSIZE, 2);
148
149 /* Indicate endpoint configuration success or failure */
150 LEDs_SetAllLEDs(ConfigSuccess ? LEDMASK_USB_READY : LEDMASK_USB_ERROR);
151 }
152
153 /** Event handler for the USB_ControlRequest event. This is used to catch and process control requests sent to
154 * the device from the USB host before passing along unhandled control requests to the library for processing
155 * internally.
156 */
157 void EVENT_USB_Device_ControlRequest(void)
158 {
159 /* Process General and Audio specific control requests */
160 switch (USB_ControlRequest.bRequest)
161 {
162 case REQ_SetInterface:
163 /* Set Interface is not handled by the library, as its function is application-specific */
164 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_STANDARD | REQREC_INTERFACE))
165 {
166 Endpoint_ClearSETUP();
167 Endpoint_ClearStatusStage();
168
169 /* Check if the host is enabling the audio interface (setting AlternateSetting to 1) */
170 StreamingAudioInterfaceSelected = ((USB_ControlRequest.wValue) != 0);
171 }
172
173 break;
174 case AUDIO_REQ_GetStatus:
175 /* Get Status request can be directed at either the interface or endpoint, neither is currently used
176 * according to the latest USB Audio 1.0 standard, but must be ACKed with no data when requested */
177 if ((USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE)) ||
178 (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_ENDPOINT)))
179 {
180 Endpoint_ClearSETUP();
181 Endpoint_ClearStatusStage();
182 }
183
184 break;
185 case AUDIO_REQ_SetCurrent:
186 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_ENDPOINT))
187 {
188 /* Extract out the relevant request information to get the target Endpoint address and control being set */
189 uint8_t EndpointAddress = (uint8_t)USB_ControlRequest.wIndex;
190 uint8_t EndpointControl = (USB_ControlRequest.wValue >> 8);
191
192 /* Only handle SET CURRENT requests to the audio endpoint's sample frequency property */
193 if ((EndpointAddress == AUDIO_STREAM_EPADDR) && (EndpointControl == AUDIO_EPCONTROL_SamplingFreq))
194 {
195 uint8_t SampleRate[3];
196
197 Endpoint_ClearSETUP();
198 Endpoint_Read_Control_Stream_LE(SampleRate, sizeof(SampleRate));
199 Endpoint_ClearOUT();
200
201 /* Set the new sampling frequency to the value given by the host */
202 CurrentAudioSampleFrequency = (((uint32_t)SampleRate[2] << 16) | ((uint32_t)SampleRate[1] << 8) | (uint32_t)SampleRate[0]);
203
204 /* Adjust sample reload timer to the new frequency */
205 OCR0A = ((F_CPU / 8 / CurrentAudioSampleFrequency) - 1);
206 }
207 }
208
209 break;
210 case AUDIO_REQ_GetCurrent:
211 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_ENDPOINT))
212 {
213 /* Extract out the relevant request information to get the target Endpoint address and control being retrieved */
214 uint8_t EndpointAddress = (uint8_t)USB_ControlRequest.wIndex;
215 uint8_t EndpointControl = (USB_ControlRequest.wValue >> 8);
216
217 /* Only handle GET CURRENT requests to the audio endpoint's sample frequency property */
218 if ((EndpointAddress == AUDIO_STREAM_EPADDR) && (EndpointControl == AUDIO_EPCONTROL_SamplingFreq))
219 {
220 uint8_t SampleRate[3];
221
222 /* Convert the sampling rate value into the 24-bit format the host expects for the property */
223 SampleRate[2] = (CurrentAudioSampleFrequency >> 16);
224 SampleRate[1] = (CurrentAudioSampleFrequency >> 8);
225 SampleRate[0] = (CurrentAudioSampleFrequency & 0xFF);
226
227 Endpoint_ClearSETUP();
228 Endpoint_Write_Control_Stream_LE(SampleRate, sizeof(SampleRate));
229 Endpoint_ClearOUT();
230 }
231 }
232
233 break;
234 }
235 }
236
237 /** ISR to handle the reloading of the PWM timer with the next sample. */
238 ISR(TIMER0_COMPA_vect, ISR_BLOCK)
239 {
240 uint8_t PrevEndpoint = Endpoint_GetCurrentEndpoint();
241
242 /* Select the audio stream endpoint */
243 Endpoint_SelectEndpoint(AUDIO_STREAM_EPADDR);
244
245 /* Check if the current endpoint can be read from (contains a packet) and the host is sending data */
246 if (Endpoint_IsOUTReceived() && StreamingAudioInterfaceSelected)
247 {
248 /* Retrieve the signed 16-bit left and right audio samples, convert to 8-bit */
249 int8_t LeftSample_8Bit = ((int16_t)Endpoint_Read_16_LE() >> 8);
250 int8_t RightSample_8Bit = ((int16_t)Endpoint_Read_16_LE() >> 8);
251
252 /* Mix the two channels together to produce a mono, 8-bit sample */
253 int8_t MixedSample_8Bit = (((int16_t)LeftSample_8Bit + (int16_t)RightSample_8Bit) >> 1);
254
255 /* Check to see if the bank is now empty */
256 if (!(Endpoint_IsReadWriteAllowed()))
257 {
258 /* Acknowledge the packet, clear the bank ready for the next packet */
259 Endpoint_ClearOUT();
260 }
261
262 #if defined(AUDIO_OUT_MONO)
263 /* Load the sample into the PWM timer channel */
264 OCR3A = (MixedSample_8Bit ^ (1 << 7));
265 #elif defined(AUDIO_OUT_STEREO)
266 /* Load the dual 8-bit samples into the PWM timer channels */
267 OCR3A = (LeftSample_8Bit ^ (1 << 7));
268 OCR3B = (RightSample_8Bit ^ (1 << 7));
269 #elif defined(AUDIO_OUT_PORTC)
270 /* Load the 8-bit mixed sample into PORTC */
271 PORTC = MixedSample_8Bit;
272 #endif
273
274 uint8_t LEDMask = LEDS_NO_LEDS;
275
276 /* Turn on LEDs as the sample amplitude increases */
277 if (MixedSample_8Bit > 16)
278 LEDMask = (LEDS_LED1 | LEDS_LED2 | LEDS_LED3 | LEDS_LED4);
279 else if (MixedSample_8Bit > 8)
280 LEDMask = (LEDS_LED1 | LEDS_LED2 | LEDS_LED3);
281 else if (MixedSample_8Bit > 4)
282 LEDMask = (LEDS_LED1 | LEDS_LED2);
283 else if (MixedSample_8Bit > 2)
284 LEDMask = (LEDS_LED1);
285
286 LEDs_SetAllLEDs(LEDMask);
287 }
288
289 Endpoint_SelectEndpoint(PrevEndpoint);
290 }
291