Move completed low level Audio Host demos into the LowLevel folder from the Incomplet...
[pub/USBasp.git] / Demos / Host / LowLevel / AudioOutputHost / AudioOutputHost.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 AudioOutputHost demo. This file contains the main tasks of
34 * the demo and is responsible for the initial application hardware configuration.
35 */
36
37 #include "AudioOutputHost.h"
38
39 /** Main program entry point. This routine configures the hardware required by the application, then
40 * enters a loop to run the application tasks in sequence.
41 */
42 int main(void)
43 {
44 SetupHardware();
45
46 puts_P(PSTR(ESC_FG_CYAN "Audio Output Host Demo running.\r\n" ESC_FG_WHITE));
47
48 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
49 sei();
50
51 for (;;)
52 {
53 Audio_Task();
54 USB_USBTask();
55 }
56 }
57
58 /** Configures the board hardware and chip peripherals for the demo's functionality. */
59 void SetupHardware(void)
60 {
61 /* Disable watchdog if enabled by bootloader/fuses */
62 MCUSR &= ~(1 << WDRF);
63 wdt_disable();
64
65 /* Disable clock division */
66 clock_prescale_set(clock_div_1);
67
68 /* Hardware Initialization */
69 Serial_Init(9600, false);
70 Buttons_Init();
71 LEDs_Init();
72 USB_Init();
73
74 /* Create a stdio stream for the serial port for stdin and stdout */
75 Serial_CreateStream(NULL);
76 }
77
78 /** Event handler for the USB_DeviceAttached event. This indicates that a device has been attached to the host, and
79 * starts the library USB task to begin the enumeration and USB management process.
80 */
81 void EVENT_USB_Host_DeviceAttached(void)
82 {
83 puts_P(PSTR(ESC_FG_GREEN "Device Attached.\r\n" ESC_FG_WHITE));
84 LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
85 }
86
87 /** Event handler for the USB_DeviceUnattached event. This indicates that a device has been removed from the host, and
88 * stops the library USB task management process.
89 */
90 void EVENT_USB_Host_DeviceUnattached(void)
91 {
92 puts_P(PSTR(ESC_FG_GREEN "Device Unattached.\r\n" ESC_FG_WHITE));
93 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
94 }
95
96 /** Event handler for the USB_DeviceEnumerationComplete event. This indicates that a device has been successfully
97 * enumerated by the host and is now ready to be used by the application.
98 */
99 void EVENT_USB_Host_DeviceEnumerationComplete(void)
100 {
101 LEDs_SetAllLEDs(LEDMASK_USB_READY);
102 }
103
104 /** Event handler for the USB_HostError event. This indicates that a hardware error occurred while in host mode. */
105 void EVENT_USB_Host_HostError(const uint8_t ErrorCode)
106 {
107 USB_Disable();
108
109 printf_P(PSTR(ESC_FG_RED "Host Mode Error\r\n"
110 " -- Error Code %d\r\n" ESC_FG_WHITE), ErrorCode);
111
112 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
113 for(;;);
114 }
115
116 /** Event handler for the USB_DeviceEnumerationFailed event. This indicates that a problem occurred while
117 * enumerating an attached USB device.
118 */
119 void EVENT_USB_Host_DeviceEnumerationFailed(const uint8_t ErrorCode,
120 const uint8_t SubErrorCode)
121 {
122 printf_P(PSTR(ESC_FG_RED "Dev Enum Error\r\n"
123 " -- Error Code %d\r\n"
124 " -- Sub Error Code %d\r\n"
125 " -- In State %d\r\n" ESC_FG_WHITE), ErrorCode, SubErrorCode, USB_HostState);
126
127 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
128 }
129
130 void Audio_Task(void)
131 {
132 uint8_t ErrorCode;
133
134 switch (USB_HostState)
135 {
136 case HOST_STATE_Addressed:
137 puts_P(PSTR("Getting Config Data.\r\n"));
138
139 /* Get and process the configuration descriptor data */
140 if ((ErrorCode = ProcessConfigurationDescriptor()) != SuccessfulConfigRead)
141 {
142 if (ErrorCode == ControlError)
143 puts_P(PSTR(ESC_FG_RED "Control Error (Get Configuration).\r\n"));
144 else
145 puts_P(PSTR(ESC_FG_RED "Invalid Device.\r\n"));
146
147 printf_P(PSTR(" -- Error Code: %d\r\n" ESC_FG_WHITE), ErrorCode);
148
149 /* Indicate error status */
150 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
151
152 /* Wait until USB device disconnected */
153 USB_HostState = HOST_STATE_WaitForDeviceRemoval;
154 break;
155 }
156
157 /* Set the device configuration to the first configuration (rarely do devices use multiple configurations) */
158 if ((ErrorCode = USB_Host_SetDeviceConfiguration(1)) != HOST_SENDCONTROL_Successful)
159 {
160 printf_P(PSTR(ESC_FG_RED "Control Error (Set Configuration).\r\n"
161 " -- Error Code: %d\r\n" ESC_FG_WHITE), ErrorCode);
162
163 /* Indicate error status */
164 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
165
166 /* Wait until USB device disconnected */
167 USB_HostState = HOST_STATE_WaitForDeviceRemoval;
168 break;
169 }
170
171 if ((ErrorCode = USB_Host_SetInterfaceAltSetting(StreamingInterfaceIndex,
172 StreamingInterfaceAltSetting)) != HOST_SENDCONTROL_Successful)
173 {
174 printf_P(PSTR(ESC_FG_RED "Could not set alternative streaming interface setting.\r\n"
175 " -- Error Code: %d\r\n" ESC_FG_WHITE), ErrorCode);
176
177 /* Indicate error status */
178 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
179
180 /* Wait until USB device disconnected */
181 USB_HostState = HOST_STATE_WaitForDeviceRemoval;
182 break;
183 }
184
185 USB_ControlRequest = (USB_Request_Header_t)
186 {
187 .bmRequestType = (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_ENDPOINT),
188 .bRequest = AUDIO_REQ_SetCurrent,
189 .wValue = (AUDIO_EPCONTROL_SamplingFreq << 8),
190 .wIndex = StreamingEndpointAddress,
191 .wLength = sizeof(USB_Audio_SampleFreq_t),
192 };
193
194 USB_Audio_SampleFreq_t SampleRate = AUDIO_SAMPLE_FREQ(48000);
195
196 /* Select the control pipe for the request transfer */
197 Pipe_SelectPipe(PIPE_CONTROLPIPE);
198
199 /* Set the sample rate on the streaming interface endpoint */
200 if ((ErrorCode = USB_Host_SendControlRequest(&SampleRate)) != HOST_SENDCONTROL_Successful)
201 {
202 /* Indicate error status */
203 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
204
205 /* Wait until USB device disconnected */
206 USB_HostState = HOST_STATE_WaitForDeviceRemoval;
207 break;
208 }
209
210 /* Sample reload timer initialization */
211 TIMSK0 = (1 << OCIE0A);
212 OCR0A = ((F_CPU / 8 / 48000) - 1);
213 TCCR0A = (1 << WGM01); // CTC mode
214 TCCR0B = (1 << CS01); // Fcpu/8 speed
215
216 puts_P(PSTR("Speaker Enumerated.\r\n"));
217
218 USB_HostState = HOST_STATE_Configured;
219 break;
220 case HOST_STATE_Configured:
221 /* Do nothing - audio stream is handled by the timer interrupt routine */
222 break;
223 }
224 }
225
226 /** ISR to handle the reloading of the endpoint with the next sample. */
227 ISR(TIMER0_COMPA_vect, ISR_BLOCK)
228 {
229 uint8_t PrevPipe = Pipe_GetCurrentPipe();
230
231 Pipe_SelectPipe(AUDIO_DATA_OUT_PIPE);
232 Pipe_Unfreeze();
233
234 /* Check if the current pipe can be written to (device ready for more data) */
235 if (Pipe_IsOUTReady())
236 {
237 static uint8_t SquareWaveSampleCount;
238 static int16_t CurrentWaveValue;
239
240 if (SquareWaveSampleCount++ == 0xFF)
241 CurrentWaveValue ^= 0x8000;
242
243 /* Only generate audio if the board button is being pressed */
244 int16_t Sample_16Bit = (Buttons_GetStatus() & BUTTONS_BUTTON1) ? CurrentWaveValue : 0;
245
246 Pipe_Write_16_LE(Sample_16Bit);
247 Pipe_Write_16_LE(Sample_16Bit);
248
249 if (!(Pipe_IsReadWriteAllowed()))
250 Pipe_ClearOUT();
251 }
252
253 Pipe_Freeze();
254 Pipe_SelectPipe(PrevPipe);
255 }