]> git.friedersdorff.com Git - max/tmk_keyboard.git/blob - protocol/lufa/LUFA-git/Demos/Host/ClassDriver/AudioOutputHost/AudioOutputHost.c
Squashed 'tmk_core/' changes from caca2c0..dc0e46e
[max/tmk_keyboard.git] / protocol / lufa / LUFA-git / Demos / Host / ClassDriver / AudioOutputHost / AudioOutputHost.c
1 /*
2              LUFA Library
3      Copyright (C) Dean Camera, 2014.
4
5   dean [at] fourwalledcubicle [dot] com
6            www.lufa-lib.org
7 */
8
9 /*
10   Copyright 2014  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 disclaims 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 /** LUFA Audio Class driver interface configuration and state information. This structure is
40  *  passed to all Audio Class driver functions, so that multiple instances of the same class
41  *  within a device can be differentiated from one another.
42  */
43 USB_ClassInfo_Audio_Host_t Speaker_Audio_Interface =
44         {
45                 .Config =
46                         {
47                                 .DataOUTPipe            =
48                                         {
49                                                 .Address        = (PIPE_DIR_OUT | 2),
50                                         },
51                         },
52         };
53
54
55 /** Main program entry point. This routine configures the hardware required by the application, then
56  *  enters a loop to run the application tasks in sequence.
57  */
58 int main(void)
59 {
60         SetupHardware();
61
62         puts_P(PSTR(ESC_FG_CYAN "Audio Output Host Demo running.\r\n" ESC_FG_WHITE));
63
64         LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
65         GlobalInterruptEnable();
66
67         for (;;)
68         {
69                 Audio_Host_USBTask(&Speaker_Audio_Interface);
70                 USB_USBTask();
71         }
72 }
73
74 /** ISR to handle the reloading of the PWM timer with the next sample. */
75 ISR(TIMER0_COMPA_vect, ISR_BLOCK)
76 {
77         uint8_t PrevPipe = Pipe_GetCurrentPipe();
78
79         /* Check that the USB bus is ready for the next sample to write */
80         if (Audio_Host_IsReadyForNextSample(&Speaker_Audio_Interface))
81         {
82                 int16_t AudioSample;
83
84                 #if defined(USE_TEST_TONE)
85                         static uint8_t SquareWaveSampleCount;
86                         static int16_t CurrentWaveValue;
87
88                         /* In test tone mode, generate a square wave at 1/256 of the sample rate */
89                         if (SquareWaveSampleCount++ == 0xFF)
90                           CurrentWaveValue ^= 0x8000;
91
92                         /* Only generate audio if the board button is being pressed */
93                         AudioSample = (Buttons_GetStatus() & BUTTONS_BUTTON1) ? CurrentWaveValue : 0;
94                 #else
95                         /* Audio sample is ADC value scaled to fit the entire range */
96                         AudioSample = ((SAMPLE_MAX_RANGE / ADC_MAX_RANGE) * ADC_GetResult());
97
98                         #if defined(MICROPHONE_BIASED_TO_HALF_RAIL)
99                         /* Microphone is biased to half rail voltage, subtract the bias from the sample value */
100                         AudioSample -= (SAMPLE_MAX_RANGE / 2);
101                         #endif
102                 #endif
103
104                 Audio_Host_WriteSample16(&Speaker_Audio_Interface, AudioSample);
105                 Audio_Host_WriteSample16(&Speaker_Audio_Interface, AudioSample);
106         }
107
108         Pipe_SelectPipe(PrevPipe);
109 }
110
111 /** Configures the board hardware and chip peripherals for the demo's functionality. */
112 void SetupHardware(void)
113 {
114 #if (ARCH == ARCH_AVR8)
115         /* Disable watchdog if enabled by bootloader/fuses */
116         MCUSR &= ~(1 << WDRF);
117         wdt_disable();
118
119         /* Disable clock division */
120         clock_prescale_set(clock_div_1);
121 #endif
122
123         /* Hardware Initialization */
124         Serial_Init(9600, false);
125         LEDs_Init();
126         Buttons_Init();
127         ADC_Init(ADC_FREE_RUNNING | ADC_PRESCALE_32);
128         ADC_SetupChannel(MIC_IN_ADC_CHANNEL);
129         USB_Init();
130
131         /* Create a stdio stream for the serial port for stdin and stdout */
132         Serial_CreateStream(NULL);
133
134         /* Start the ADC conversion in free running mode */
135         ADC_StartReading(ADC_REFERENCE_AVCC | ADC_RIGHT_ADJUSTED | ADC_GET_CHANNEL_MASK(MIC_IN_ADC_CHANNEL));
136 }
137
138 /** Event handler for the USB_DeviceAttached event. This indicates that a device has been attached to the host, and
139  *  starts the library USB task to begin the enumeration and USB management process.
140  */
141 void EVENT_USB_Host_DeviceAttached(void)
142 {
143         puts_P(PSTR("Device Attached.\r\n"));
144         LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
145 }
146
147 /** Event handler for the USB_DeviceUnattached event. This indicates that a device has been removed from the host, and
148  *  stops the library USB task management process.
149  */
150 void EVENT_USB_Host_DeviceUnattached(void)
151 {
152         puts_P(PSTR("\r\nDevice Unattached.\r\n"));
153         LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
154 }
155
156 /** Event handler for the USB_DeviceEnumerationComplete event. This indicates that a device has been successfully
157  *  enumerated by the host and is now ready to be used by the application.
158  */
159 void EVENT_USB_Host_DeviceEnumerationComplete(void)
160 {
161         LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
162
163         uint16_t ConfigDescriptorSize;
164         uint8_t  ConfigDescriptorData[512];
165
166         if (USB_Host_GetDeviceConfigDescriptor(1, &ConfigDescriptorSize, ConfigDescriptorData,
167                                                sizeof(ConfigDescriptorData)) != HOST_GETCONFIG_Successful)
168         {
169                 puts_P(PSTR("Error Retrieving Configuration Descriptor.\r\n"));
170                 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
171                 return;
172         }
173
174         if (Audio_Host_ConfigurePipes(&Speaker_Audio_Interface,
175                                       ConfigDescriptorSize, ConfigDescriptorData) != AUDIO_ENUMERROR_NoError)
176         {
177                 puts_P(PSTR("Attached Device Not a Valid Audio Output Device.\r\n"));
178                 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
179                 return;
180         }
181
182         if (USB_Host_SetDeviceConfiguration(1) != HOST_SENDCONTROL_Successful)
183         {
184                 puts_P(PSTR("Error Setting Device Configuration.\r\n"));
185                 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
186                 return;
187         }
188
189         if (Audio_Host_StartStopStreaming(&Speaker_Audio_Interface, true) != HOST_SENDCONTROL_Successful)
190         {
191                 puts_P(PSTR("Error Enabling Audio Stream.\r\n"));
192                 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
193                 USB_Host_SetDeviceConfiguration(0);
194                 return;
195         }
196
197         USB_Audio_SampleFreq_t SampleRate = AUDIO_SAMPLE_FREQ(48000);
198         if (Audio_Host_GetSetEndpointProperty(&Speaker_Audio_Interface, Speaker_Audio_Interface.Config.DataOUTPipe.Address,
199                                               AUDIO_REQ_SetCurrent, AUDIO_EPCONTROL_SamplingFreq,
200                                               sizeof(SampleRate), &SampleRate) != HOST_SENDCONTROL_Successful)
201         {
202                 puts_P(PSTR("Error Setting Audio Sampling Frequency.\r\n"));
203                 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
204                 USB_Host_SetDeviceConfiguration(0);
205                 return;
206         }
207
208         /* Sample reload timer initialization */
209         TIMSK0  = (1 << OCIE0A);
210         OCR0A   = ((F_CPU / 8 / 48000) - 1);
211         TCCR0A  = (1 << WGM01);  // CTC mode
212         TCCR0B  = (1 << CS01);   // Fcpu/8 speed
213
214         puts_P(PSTR("Audio Device Enumerated.\r\n"));
215         LEDs_SetAllLEDs(LEDMASK_USB_READY);
216 }
217
218 /** Event handler for the USB_HostError event. This indicates that a hardware error occurred while in host mode. */
219 void EVENT_USB_Host_HostError(const uint8_t ErrorCode)
220 {
221         USB_Disable();
222
223         printf_P(PSTR(ESC_FG_RED "Host Mode Error\r\n"
224                                  " -- Error Code %d\r\n" ESC_FG_WHITE), ErrorCode);
225
226         LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
227         for(;;);
228 }
229
230 /** Event handler for the USB_DeviceEnumerationFailed event. This indicates that a problem occurred while
231  *  enumerating an attached USB device.
232  */
233 void EVENT_USB_Host_DeviceEnumerationFailed(const uint8_t ErrorCode,
234                                             const uint8_t SubErrorCode)
235 {
236         printf_P(PSTR(ESC_FG_RED "Dev Enum Error\r\n"
237                                  " -- Error Code %d\r\n"
238                                  " -- Sub Error Code %d\r\n"
239                                  " -- In State %d\r\n" ESC_FG_WHITE), ErrorCode, SubErrorCode, USB_HostState);
240
241         LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
242 }
243