Updated all host mode demos and projects to use the EVENT_USB_Host_DeviceEnumerationC...
[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 USB_USBTask();
54 }
55 }
56
57 /** Configures the board hardware and chip peripherals for the demo's functionality. */
58 void SetupHardware(void)
59 {
60 /* Disable watchdog if enabled by bootloader/fuses */
61 MCUSR &= ~(1 << WDRF);
62 wdt_disable();
63
64 /* Disable clock division */
65 clock_prescale_set(clock_div_1);
66
67 /* Hardware Initialization */
68 Serial_Init(9600, false);
69 Buttons_Init();
70 ADC_Init(ADC_FREE_RUNNING | ADC_PRESCALE_32);
71 ADC_SetupChannel(MIC_IN_ADC_CHANNEL);
72 LEDs_Init();
73 USB_Init();
74
75 /* Create a stdio stream for the serial port for stdin and stdout */
76 Serial_CreateStream(NULL);
77 }
78
79 /** Event handler for the USB_DeviceAttached event. This indicates that a device has been attached to the host, and
80 * starts the library USB task to begin the enumeration and USB management process.
81 */
82 void EVENT_USB_Host_DeviceAttached(void)
83 {
84 puts_P(PSTR(ESC_FG_GREEN "Device Attached.\r\n" ESC_FG_WHITE));
85 LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
86 }
87
88 /** Event handler for the USB_DeviceUnattached event. This indicates that a device has been removed from the host, and
89 * stops the library USB task management process.
90 */
91 void EVENT_USB_Host_DeviceUnattached(void)
92 {
93 puts_P(PSTR(ESC_FG_GREEN "Device Unattached.\r\n" ESC_FG_WHITE));
94 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
95 }
96
97 /** Event handler for the USB_DeviceEnumerationComplete event. This indicates that a device has been successfully
98 * enumerated by the host and is now ready to be used by the application.
99 */
100 void EVENT_USB_Host_DeviceEnumerationComplete(void)
101 {
102 puts_P(PSTR("Getting Config Data.\r\n"));
103
104 uint8_t ErrorCode;
105
106 /* Get and process the configuration descriptor data */
107 if ((ErrorCode = ProcessConfigurationDescriptor()) != SuccessfulConfigRead)
108 {
109 if (ErrorCode == ControlError)
110 puts_P(PSTR(ESC_FG_RED "Control Error (Get Configuration).\r\n"));
111 else
112 puts_P(PSTR(ESC_FG_RED "Invalid Device.\r\n"));
113
114 printf_P(PSTR(" -- Error Code: %d\r\n" ESC_FG_WHITE), ErrorCode);
115
116 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
117 return;
118 }
119
120 /* Set the device configuration to the first configuration (rarely do devices use multiple configurations) */
121 if ((ErrorCode = USB_Host_SetDeviceConfiguration(1)) != HOST_SENDCONTROL_Successful)
122 {
123 printf_P(PSTR(ESC_FG_RED "Control Error (Set Configuration).\r\n"
124 " -- Error Code: %d\r\n" ESC_FG_WHITE), ErrorCode);
125
126 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
127 return;
128 }
129
130 if ((ErrorCode = USB_Host_SetInterfaceAltSetting(StreamingInterfaceIndex,
131 StreamingInterfaceAltSetting)) != HOST_SENDCONTROL_Successful)
132 {
133 printf_P(PSTR(ESC_FG_RED "Could not set alternative streaming interface setting.\r\n"
134 " -- Error Code: %d\r\n" ESC_FG_WHITE), ErrorCode);
135
136 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
137 return;
138 }
139
140 USB_ControlRequest = (USB_Request_Header_t)
141 {
142 .bmRequestType = (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_ENDPOINT),
143 .bRequest = AUDIO_REQ_SetCurrent,
144 .wValue = (AUDIO_EPCONTROL_SamplingFreq << 8),
145 .wIndex = StreamingEndpointAddress,
146 .wLength = sizeof(USB_Audio_SampleFreq_t),
147 };
148
149 USB_Audio_SampleFreq_t SampleRate = AUDIO_SAMPLE_FREQ(48000);
150
151 /* Select the control pipe for the request transfer */
152 Pipe_SelectPipe(PIPE_CONTROLPIPE);
153
154 /* Set the sample rate on the streaming interface endpoint */
155 if ((ErrorCode = USB_Host_SendControlRequest(&SampleRate)) != HOST_SENDCONTROL_Successful)
156 {
157 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
158 USB_Host_SetDeviceConfiguration(0);
159 return;
160 }
161
162 /* Sample reload timer initialization */
163 TIMSK0 = (1 << OCIE0A);
164 OCR0A = ((F_CPU / 8 / 48000) - 1);
165 TCCR0A = (1 << WGM01); // CTC mode
166 TCCR0B = (1 << CS01); // Fcpu/8 speed
167
168 puts_P(PSTR("Speaker Enumerated.\r\n"));
169 LEDs_SetAllLEDs(LEDMASK_USB_READY);
170 }
171
172 /** Event handler for the USB_HostError event. This indicates that a hardware error occurred while in host mode. */
173 void EVENT_USB_Host_HostError(const uint8_t ErrorCode)
174 {
175 USB_Disable();
176
177 printf_P(PSTR(ESC_FG_RED "Host Mode Error\r\n"
178 " -- Error Code %d\r\n" ESC_FG_WHITE), ErrorCode);
179
180 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
181 for(;;);
182 }
183
184 /** Event handler for the USB_DeviceEnumerationFailed event. This indicates that a problem occurred while
185 * enumerating an attached USB device.
186 */
187 void EVENT_USB_Host_DeviceEnumerationFailed(const uint8_t ErrorCode,
188 const uint8_t SubErrorCode)
189 {
190 printf_P(PSTR(ESC_FG_RED "Dev Enum Error\r\n"
191 " -- Error Code %d\r\n"
192 " -- Sub Error Code %d\r\n"
193 " -- In State %d\r\n" ESC_FG_WHITE), ErrorCode, SubErrorCode, USB_HostState);
194
195 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
196 }
197
198 /** ISR to handle the reloading of the endpoint with the next sample. */
199 ISR(TIMER0_COMPA_vect, ISR_BLOCK)
200 {
201 uint8_t PrevPipe = Pipe_GetCurrentPipe();
202
203 Pipe_SelectPipe(AUDIO_DATA_OUT_PIPE);
204 Pipe_Unfreeze();
205
206 /* Check if the current pipe can be written to (device ready for more data) */
207 if (Pipe_IsOUTReady())
208 {
209 int16_t AudioSample;
210
211 #if defined(USE_TEST_TONE)
212 static uint8_t SquareWaveSampleCount;
213 static int16_t CurrentWaveValue;
214
215 /* In test tone mode, generate a square wave at 1/256 of the sample rate */
216 if (SquareWaveSampleCount++ == 0xFF)
217 CurrentWaveValue ^= 0x8000;
218
219 /* Only generate audio if the board button is being pressed */
220 AudioSample = (Buttons_GetStatus() & BUTTONS_BUTTON1) ? CurrentWaveValue : 0;
221 #else
222 /* Audio sample is ADC value scaled to fit the entire range */
223 AudioSample = ((SAMPLE_MAX_RANGE / ADC_MAX_RANGE) * ADC_GetResult());
224
225 #if defined(MICROPHONE_BIASED_TO_HALF_RAIL)
226 /* Microphone is biased to half rail voltage, subtract the bias from the sample value */
227 AudioSample -= (SAMPLE_MAX_RANGE / 2);
228 #endif
229 #endif
230
231 Pipe_Write_16_LE(AudioSample);
232 Pipe_Write_16_LE(AudioSample);
233
234 if (!(Pipe_IsReadWriteAllowed()))
235 Pipe_ClearOUT();
236 }
237
238 Pipe_Freeze();
239 Pipe_SelectPipe(PrevPipe);
240 }