Added new LEDs_ToggleLEDs() function to the Board LEDs driver.
[pub/USBasp.git] / Demos / Device / LowLevel / CDC / CDC.c
1 /*
2 LUFA Library
3 Copyright (C) Dean Camera, 2009.
4
5 dean [at] fourwalledcubicle [dot] com
6 www.fourwalledcubicle.com
7 */
8
9 /*
10 Copyright 2009 Dean Camera (dean [at] fourwalledcubicle [dot] com)
11
12 Permission to use, copy, modify, and distribute this software
13 and its documentation for any purpose and without fee is hereby
14 granted, provided that the above copyright notice appear in all
15 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 CDC demo. This file contains the main tasks of the demo and
34 * is responsible for the initial application hardware configuration.
35 */
36
37 #include "CDC.h"
38
39 /* Globals: */
40 /** Contains the current baud rate and other settings of the virtual serial port. While this demo does not use
41 * the physical USART and thus does not use these settings, they must still be retained and returned to the host
42 * upon request or the host will assume the device is non-functional.
43 *
44 * These values are set by the host via a class-specific request, however they are not required to be used accurately.
45 * It is possible to completely ignore these value or use other settings as the host is completely unaware of the physical
46 * serial link characteristics and instead sends and receives data in endpoint streams.
47 */
48 CDC_Line_Coding_t LineCoding = { .BaudRateBPS = 9600,
49 .CharFormat = OneStopBit,
50 .ParityType = Parity_None,
51 .DataBits = 8 };
52
53 #if 0
54 /* NOTE: Here you can set up a standard stream using the created virtual serial port, so that the standard stream functions in
55 * <stdio.h> can be used on the virtual serial port (e.g. fprintf(&USBSerial, "Test"); to print a string).
56 */
57
58 static int CDC_putchar (char c, FILE *stream)
59 {
60 Endpoint_SelectEndpoint(CDC_TX_EPNUM);
61
62 while (!(Endpoint_IsReadWriteAllowed()))
63 {
64 if (USB_DeviceState != DEVICE_STATE_Configured)
65 return -1;
66 }
67
68 Endpoint_Write_Byte(c);
69 Endpoint_ClearIN();
70
71 return 0;
72 }
73
74 static int CDC_getchar (FILE *stream)
75 {
76 int c;
77
78 Endpoint_SelectEndpoint(CDC_RX_EPNUM);
79
80 for (;;)
81 {
82 while (!(Endpoint_IsReadWriteAllowed()))
83 {
84 if (USB_DeviceState != DEVICE_STATE_Configured)
85 return -1;
86 }
87
88 if (!(Endpoint_BytesInEndpoint()))
89 {
90 Endpoint_ClearOUT();
91 }
92 else
93 {
94 c = Endpoint_Read_Byte();
95 break;
96 }
97 }
98
99 return c;
100 }
101
102 static FILE USBSerial = FDEV_SETUP_STREAM(CDC_putchar, CDC_getchar, _FDEV_SETUP_RW);
103 #endif
104
105 /** Main program entry point. This routine contains the overall program flow, including initial
106 * setup of all components and the main program loop.
107 */
108 int main(void)
109 {
110 SetupHardware();
111
112 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
113
114 for (;;)
115 {
116 CDC_Task();
117 USB_USBTask();
118 }
119 }
120
121 /** Configures the board hardware and chip peripherals for the demo's functionality. */
122 void SetupHardware(void)
123 {
124 /* Disable watchdog if enabled by bootloader/fuses */
125 MCUSR &= ~(1 << WDRF);
126 wdt_disable();
127
128 /* Disable clock division */
129 clock_prescale_set(clock_div_1);
130
131 /* Hardware Initialization */
132 Joystick_Init();
133 LEDs_Init();
134 USB_Init();
135 }
136
137 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs and
138 * starts the library USB task to begin the enumeration and USB management process.
139 */
140 void EVENT_USB_Connect(void)
141 {
142 /* Indicate USB enumerating */
143 LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
144 }
145
146 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
147 * the status LEDs and stops the USB management and CDC management tasks.
148 */
149 void EVENT_USB_Disconnect(void)
150 {
151 /* Indicate USB not ready */
152 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
153 }
154
155 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host set the current configuration
156 * of the USB device after enumeration - the device endpoints are configured and the CDC management task started.
157 */
158 void EVENT_USB_ConfigurationChanged(void)
159 {
160 /* Indicate USB connected and ready */
161 LEDs_SetAllLEDs(LEDMASK_USB_READY);
162
163 /* Setup CDC Notification, Rx and Tx Endpoints */
164 if (!(Endpoint_ConfigureEndpoint(CDC_NOTIFICATION_EPNUM, EP_TYPE_INTERRUPT,
165 ENDPOINT_DIR_IN, CDC_NOTIFICATION_EPSIZE,
166 ENDPOINT_BANK_SINGLE)))
167 {
168 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
169 }
170
171 if (!(Endpoint_ConfigureEndpoint(CDC_TX_EPNUM, EP_TYPE_BULK,
172 ENDPOINT_DIR_IN, CDC_TXRX_EPSIZE,
173 ENDPOINT_BANK_SINGLE)))
174 {
175 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
176 }
177
178 if (!(Endpoint_ConfigureEndpoint(CDC_RX_EPNUM, EP_TYPE_BULK,
179 ENDPOINT_DIR_OUT, CDC_TXRX_EPSIZE,
180 ENDPOINT_BANK_SINGLE)))
181 {
182 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
183 }
184 }
185
186 /** Event handler for the USB_UnhandledControlPacket event. This is used to catch standard and class specific
187 * control requests that are not handled internally by the USB library (including the CDC control commands,
188 * which are all issued via the control endpoint), so that they can be handled appropriately for the application.
189 */
190 void EVENT_USB_UnhandledControlPacket(void)
191 {
192 uint8_t* LineCodingData = (uint8_t*)&LineCoding;
193
194 /* Process CDC specific control requests */
195 switch (USB_ControlRequest.bRequest)
196 {
197 case REQ_GetLineEncoding:
198 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
199 {
200 /* Acknowledge the SETUP packet, ready for data transfer */
201 Endpoint_ClearSETUP();
202
203 /* Write the line coding data to the control endpoint */
204 Endpoint_Write_Control_Stream_LE(LineCodingData, sizeof(CDC_Line_Coding_t));
205
206 /* Finalize the stream transfer to send the last packet or clear the host abort */
207 Endpoint_ClearOUT();
208 }
209
210 break;
211 case REQ_SetLineEncoding:
212 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
213 {
214 /* Acknowledge the SETUP packet, ready for data transfer */
215 Endpoint_ClearSETUP();
216
217 /* Read the line coding data in from the host into the global struct */
218 Endpoint_Read_Control_Stream_LE(LineCodingData, sizeof(CDC_Line_Coding_t));
219
220 /* Finalize the stream transfer to clear the last packet from the host */
221 Endpoint_ClearIN();
222 }
223
224 break;
225 case REQ_SetControlLineState:
226 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
227 {
228 /* Acknowledge the SETUP packet, ready for data transfer */
229 Endpoint_ClearSETUP();
230
231 /* NOTE: Here you can read in the line state mask from the host, to get the current state of the output handshake
232 lines. The mask is read in from the wValue parameter in USB_ControlRequest, and can be masked against the
233 CONTROL_LINE_OUT_* masks to determine the RTS and DTR line states using the following code:
234 */
235
236 Endpoint_ClearStatusStage();
237 }
238
239 break;
240 }
241 }
242
243 /** Function to manage CDC data transmission and reception to and from the host. */
244 void CDC_Task(void)
245 {
246 char* ReportString = NULL;
247 uint8_t JoyStatus_LCL = Joystick_GetStatus();
248 static bool ActionSent = false;
249 char* JoystickStrings[] =
250 {
251 "Joystick Up\r\n",
252 "Joystick Down\r\n",
253 "Joystick Left\r\n",
254 "Joystick Right\r\n",
255 "Joystick Pressed\r\n",
256 };
257
258 /* Device must be connected and configured for the task to run */
259 if (USB_DeviceState != DEVICE_STATE_Configured)
260 return;
261
262 #if 0
263 /* NOTE: Here you can use the notification endpoint to send back line state changes to the host, for the special RS-232
264 * handshake signal lines (and some error states), via the CONTROL_LINE_IN_* masks and the following code:
265 */
266 USB_Notification_Header_t Notification = (USB_Notification_Header_t)
267 {
268 .NotificationType = (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE),
269 .Notification = NOTIF_SerialState,
270 .wValue = 0,
271 .wIndex = 0,
272 .wLength = sizeof(uint16_t),
273 };
274
275 uint16_t LineStateMask;
276
277 // Set LineStateMask here to a mask of CONTROL_LINE_IN_* masks to set the input handshake line states to send to the host
278
279 Endpoint_SelectEndpoint(CDC_NOTIFICATION_EPNUM);
280 Endpoint_Write_Stream_LE(&Notification, sizeof(Notification));
281 Endpoint_Write_Stream_LE(&LineStateMask, sizeof(LineStateMask));
282 Endpoint_ClearIN();
283 #endif
284
285 /* Determine if a joystick action has occurred */
286 if (JoyStatus_LCL & JOY_UP)
287 ReportString = JoystickStrings[0];
288 else if (JoyStatus_LCL & JOY_DOWN)
289 ReportString = JoystickStrings[1];
290 else if (JoyStatus_LCL & JOY_LEFT)
291 ReportString = JoystickStrings[2];
292 else if (JoyStatus_LCL & JOY_RIGHT)
293 ReportString = JoystickStrings[3];
294 else if (JoyStatus_LCL & JOY_PRESS)
295 ReportString = JoystickStrings[4];
296
297 /* Flag management - Only allow one string to be sent per action */
298 if (ReportString == NULL)
299 {
300 ActionSent = false;
301 }
302 else if (ActionSent == false)
303 {
304 ActionSent = true;
305
306 /* Select the Serial Tx Endpoint */
307 Endpoint_SelectEndpoint(CDC_TX_EPNUM);
308
309 /* Write the String to the Endpoint */
310 Endpoint_Write_Stream_LE(ReportString, strlen(ReportString));
311
312 /* Remember if the packet to send completely fills the endpoint */
313 bool IsFull = (Endpoint_BytesInEndpoint() == CDC_TXRX_EPSIZE);
314
315 /* Finalize the stream transfer to send the last packet */
316 Endpoint_ClearIN();
317
318 /* If the last packet filled the endpoint, send an empty packet to release the buffer on
319 * the receiver (otherwise all data will be cached until a non-full packet is received) */
320 if (IsFull)
321 {
322 /* Wait until the endpoint is ready for another packet */
323 while (!(Endpoint_IsINReady()))
324 {
325 if (USB_DeviceState == DEVICE_STATE_Unattached)
326 return;
327 }
328
329 /* Send an empty packet to ensure that the host does not buffer data sent to it */
330 Endpoint_ClearIN();
331 }
332 }
333
334 /* Select the Serial Rx Endpoint */
335 Endpoint_SelectEndpoint(CDC_RX_EPNUM);
336
337 /* Throw away any received data from the host */
338 if (Endpoint_IsOUTReceived())
339 Endpoint_ClearOUT();
340 }