]> git.friedersdorff.com Git - max/tmk_keyboard.git/blob - tmk_core/protocol/lufa/LUFA-git/Demos/Host/LowLevel/AudioInputHost/AudioInputHost.c
Merge commit 'f6d56675f9f981c5464f0ca7a1fbb0162154e8c5'
[max/tmk_keyboard.git] / tmk_core / protocol / lufa / LUFA-git / Demos / Host / LowLevel / AudioInputHost / AudioInputHost.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 AudioInputHost demo. This file contains the main tasks of
34  *  the demo and is responsible for the initial application hardware configuration.
35  */
36
37 #include "AudioInputHost.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 Input Host Demo running.\r\n" ESC_FG_WHITE));
47
48         LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
49         GlobalInterruptEnable();
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 #if (ARCH == ARCH_AVR8)
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 #endif
68
69         /* Hardware Initialization */
70         Serial_Init(9600, false);
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         puts_P(PSTR("Getting Config Data.\r\n"));
102
103         uint8_t ErrorCode;
104
105         /* Get and process the configuration descriptor data */
106         if ((ErrorCode = ProcessConfigurationDescriptor()) != SuccessfulConfigRead)
107         {
108                 if (ErrorCode == ControlError)
109                   puts_P(PSTR(ESC_FG_RED "Control Error (Get Configuration).\r\n"));
110                 else
111                   puts_P(PSTR(ESC_FG_RED "Invalid Device.\r\n"));
112
113                 printf_P(PSTR(" -- Error Code: %d\r\n" ESC_FG_WHITE), ErrorCode);
114
115                 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
116                 return;
117         }
118
119         /* Set the device configuration to the first configuration (rarely do devices use multiple configurations) */
120         if ((ErrorCode = USB_Host_SetDeviceConfiguration(1)) != HOST_SENDCONTROL_Successful)
121         {
122                 printf_P(PSTR(ESC_FG_RED "Control Error (Set Configuration).\r\n"
123                                          " -- Error Code: %d\r\n" ESC_FG_WHITE), ErrorCode);
124
125                 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
126                 return;
127         }
128
129         if ((ErrorCode = USB_Host_SetInterfaceAltSetting(StreamingInterfaceIndex,
130                                                          StreamingInterfaceAltSetting)) != HOST_SENDCONTROL_Successful)
131         {
132                 printf_P(PSTR(ESC_FG_RED "Could not set alternative streaming interface setting.\r\n"
133                                          " -- Error Code: %d\r\n" ESC_FG_WHITE), ErrorCode);
134
135                 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
136                 USB_Host_SetDeviceConfiguration(0);
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                 printf_P(PSTR(ESC_FG_RED "Could not set requested Audio sample rate.\r\n"
158                                          " -- Error Code: %d\r\n" ESC_FG_WHITE), ErrorCode);
159
160                 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
161                 USB_Host_SetDeviceConfiguration(0);
162                 return;
163         }
164
165         /* Sample reload timer initialization */
166         TIMSK0  = (1 << OCIE0A);
167         OCR0A   = ((F_CPU / 8 / 48000) - 1);
168         TCCR0A  = (1 << WGM01);  // CTC mode
169         TCCR0B  = (1 << CS01);   // Fcpu/8 speed
170
171         /* Set speaker as output */
172         DDRC   |= (1 << 6);
173
174         /* PWM speaker timer initialization */
175         TCCR3A  = ((1 << WGM30) | (1 << COM3A1) | (1 << COM3A0)); // Set on match, clear on TOP
176         TCCR3B  = ((1 << WGM32) | (1 << CS30));  // Fast 8-Bit PWM, F_CPU speed
177
178         puts_P(PSTR("Microphone Enumerated.\r\n"));
179         LEDs_SetAllLEDs(LEDMASK_USB_READY);
180 }
181
182 /** Event handler for the USB_HostError event. This indicates that a hardware error occurred while in host mode. */
183 void EVENT_USB_Host_HostError(const uint8_t ErrorCode)
184 {
185         USB_Disable();
186
187         printf_P(PSTR(ESC_FG_RED "Host Mode Error\r\n"
188                                  " -- Error Code %d\r\n" ESC_FG_WHITE), ErrorCode);
189
190         LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
191         for(;;);
192 }
193
194 /** Event handler for the USB_DeviceEnumerationFailed event. This indicates that a problem occurred while
195  *  enumerating an attached USB device.
196  */
197 void EVENT_USB_Host_DeviceEnumerationFailed(const uint8_t ErrorCode,
198                                             const uint8_t SubErrorCode)
199 {
200         printf_P(PSTR(ESC_FG_RED "Dev Enum Error\r\n"
201                                  " -- Error Code %d\r\n"
202                                  " -- Sub Error Code %d\r\n"
203                                  " -- In State %d\r\n" ESC_FG_WHITE), ErrorCode, SubErrorCode, USB_HostState);
204
205         LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
206 }
207
208 /** ISR to handle the reloading of the PWM timer with the next sample. */
209 ISR(TIMER0_COMPA_vect, ISR_BLOCK)
210 {
211         uint8_t PrevPipe = Pipe_GetCurrentPipe();
212
213         Pipe_SelectPipe(AUDIO_DATA_IN_PIPE);
214         Pipe_Unfreeze();
215
216         /* Check if the current pipe can be read from (contains a packet) and the device is sending data */
217         if (Pipe_IsINReceived())
218         {
219                 /* Retrieve the signed 16-bit audio sample, convert to 8-bit */
220                 int8_t Sample_8Bit = (Pipe_Read_16_LE() >> 8);
221
222                 /* Check to see if the bank is now empty */
223                 if (!(Pipe_IsReadWriteAllowed()))
224                 {
225                         /* Acknowledge the packet, clear the bank ready for the next packet */
226                         Pipe_ClearIN();
227                 }
228
229                 /* Load the sample into the PWM timer channel */
230                 OCR3A = (Sample_8Bit ^ (1 << 7));
231
232                 uint8_t LEDMask = LEDS_NO_LEDS;
233
234                 /* Turn on LEDs as the sample amplitude increases */
235                 if (Sample_8Bit > 16)
236                   LEDMask = (LEDS_LED1 | LEDS_LED2 | LEDS_LED3 | LEDS_LED4);
237                 else if (Sample_8Bit > 8)
238                   LEDMask = (LEDS_LED1 | LEDS_LED2 | LEDS_LED3);
239                 else if (Sample_8Bit > 4)
240                   LEDMask = (LEDS_LED1 | LEDS_LED2);
241                 else if (Sample_8Bit > 2)
242                   LEDMask = (LEDS_LED1);
243
244                 LEDs_SetAllLEDs(LEDMask);
245         }
246
247         Pipe_Freeze();
248         Pipe_SelectPipe(PrevPipe);
249 }
250