-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathusb_device.c
3134 lines (2738 loc) · 125 KB
/
usb_device.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/********************************************************************
File Information:
FileName: usb_device.c
Dependencies: See INCLUDES section
Processor: PIC18,PIC24, PIC32 and dsPIC33E USB Microcontrollers
Hardware: This code is natively intended to be used on Mirochip USB
demo boards. See www.microchip.com/usb (Software & Tools
section) for list of available platforms. The firmware may
be modified for use on other USB platforms by editing the
HardwareProfile.h and HardwareProfile - [platform].h files.
Complier: Microchip C18 (for PIC18),C30 (for PIC24 and dsPIC33E)
and C32 (for PIC32)
Company: Microchip Technology, Inc.
Software License Agreement:
The software supplied herewith by Microchip Technology Incorporated
(the "Company") for its PIC(r) Microcontroller is intended and
supplied to you, the Company's customer, for use solely and
exclusively on Microchip PIC Microcontroller products. The
software is owned by the Company and/or its supplier, and is
protected under applicable copyright laws. All rights are reserved.
Any use in violation of the foregoing restrictions may subject the
user to criminal sanctions under applicable laws, as well as to
civil liability for the breach of the terms and conditions of this
license.
THIS SOFTWARE IS PROVIDED IN AN "AS IS" CONDITION. NO WARRANTIES,
WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT NOT LIMITED
TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. THE COMPANY SHALL NOT,
IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.
Summary:
This file contains functions, macros, definitions, variables,
datatypes, etc. that are required for usage with the MCHPFSUSB device
stack. This file should be included in projects that use the device stack.
This file is located in the "\<Install Directory\>\\Microchip\\USB"
directory.
Description:
USB Device Stack File
This file contains functions, macros, definitions, variables,
datatypes, etc. that are required for usage with the MCHPFSUSB device
stack. This file should be included in projects that use the device stack.
This file is located in the "\<Install Directory\>\\Microchip\\USB"
directory.
When including this file in a new project, this file can either be
referenced from the directory in which it was installed or copied
directly into the user application folder. If the first method is
chosen to keep the file located in the folder in which it is installed
then include paths need to be added so that the library and the
application both know where to reference each others files. If the
application folder is located in the same folder as the Microchip
folder (like the current demo folders), then the following include
paths need to be added to the application's project:
.
..\\..\\MicrochipInclude
If a different directory structure is used, modify the paths as
required. An example using absolute paths instead of relative paths
would be the following:
C:\\Microchip Solutions\\Microchip\\Include
C:\\Microchip Solutions\\My Demo Application
********************************************************************
File Description:
Change History:
Rev Description
---- -----------
2.6 Added USBCancelIO() function. Moved and some stack
defintions to be more consistant with the host stack.
2.6a Fixed issue where a SET_CONFIGURATION received could cause
inability to transmit on an endpoint if using ping-pong
and an odd number of packets had been sent on that endpoint
2.7 Fixed error where the USB error interrupt flag was not getting
cleared properly for PIC32 resulting in lots of extra error interrupts.
http://www.microchip.com/forums/tm.aspx?m=479085
Fixed issue with dual role mode when device run in polling
mode. Interrupts were remaining enabled after the host mode
operation was complete. This was incompatible with polling
mode operation.
Changed how the bus sensing works. In previous revisions it
was impossible to use the USBDeviceDetach to detach from the
bus if the bus voltage was still present. This is now
possible. It was also possible to move the device to the
ATTACHED state in interrupt mode even if the bus voltage
wasn't available. This is now prohibited unless VBUS is
present.
Improved error case handling when the host sends more OUT
bytes in a control transfer than the firmware was expecting
to receive (based on the size parameter when calling USBEP0Receive()).
In the USBStdSetCfgHandler(), modified the code so the USBDeviceState
variable only gets updated to the CONFIGURED_STATE at the end of the
function.
2.7a Update to support the PIC18F47J53 A1 and later revision
devices.
Fixed an error on 16-bit and 32-bit processors where a word access
could be performed on a byte pointer resulting in possible address
errors with odd aligned pointers.
2.8 Several changes to the way control transfers get processed,
so as to support the ability to allow application/class specific
handler code to defer the status stage.
Implemented USBCtrlEPAllowStatusStage() API function.
Implemented USBDeferStatusStage() API function (macro).
These changes also greatly relax the USBDeviceTasks() calling frequency
requirement, while allowing USB class handlers more flexibility.
Also implemented the following API functions and macros, for delaying
the data stage of a control transfer (with data stage):
USBDeferINDataStage()
USBDeferOUTDataStage()
USBOUTDataStageDeferred()
USBINDataStageDeferred()
USBCtrlEPAllowDataStage()
Fixed USB reset event handler issue, where the USB stack would
re-initialize global interrupt settings in the interrupt context, on
PIC18 devices with the stack operated in USB_INTERRUPT mode.
Fixed handling of SET/CLEAR FEATURE (endpoint halt) host requests.
Previous implementation would not always initialize endpoints correctly
to DATA0 DTS state after a clear feature endpoint halt request, for
all ping pong mode and usage scenarios.
2.9 Fixed an issue with STALL handling behavior on non-EP0 endpoints, for
PIC24 and PIC32 devices.
Fixed an issue where the ep_data_in[]/ep_data_out[] flags weren't
getting re-initialized coincident with the hardware ping pong pointer
reset during set configuration events.
Implemented USBGetNextHandle() API function (actually a macro, defined
in usb_device.h).
2.9d Added build option for disabling DTS checking
2.9f Adding pragma for PIC18F97J94 Family BDT location.
2.9h Updated to be able to support optional Microsoft OS Descriptors
2.9i Updated to set UCON<SUSPND> bit on PIC16F USB devices during
suspend, so as to save power.
********************************************************************/
/*----------------------------------------------------------------------------------
The USBDeviceTasks() function is responsible for detecting and processing various
USB bus events and host requests, such as those required for USB enumeration, when
the USB cable is first attached to the host. This function is the main dispatcher
routine for the USB stack.
Additional API functions and macros are also provided by the USB stack, which can be
used to send/receive USB data to/from the host, among other things. A full list
of the available implemented functions/macros are provided in the
"MCHPFSUSB Library Help". For normal installations of the MCHPFSUSB Framework,
the USB API documentation can be found from:
Start menu --> (All Programs) --> Microchip --> MCHPFSUSB vX.x --> Documents --> MCHPFSUSB Library Help
Once the help file is opened, the API functions/macros are described in the following section:
Library Interface (API) --> Device/Peripheral --> Device Stack --> Interface Routines
Additional API functions may also be provided depending upon the specific USB device class
implemented, and these functions are also documented in the MCHPFSUSB Library Help.
If the USB stack is operated in "USB_POLLING" mode (user selectable option in
usb_config.h), then the application firmware is reponsible for calling the
USBDeviceTasks() function periodically. If the USB stack is operated in the
"USB_INTERRUPT" mode, then the application firmware does not have to directly
call USBDeviceTasks(), as it will execute only when necessary as an interrupt handler.
In order to properly operate a USB connection, and to correctly process and respond
to control transfers in the maximum time allowed by the USB specifications, the
USBDeviceTasks() function/interrupt handler must be allowed to execute in a timely
fashion.
When the USB module is enabled, the USB cable is attached to the host, the USB bus
is not in the suspend state, and the USB stack is operated in the USB_POLLING mode
with ping pong buffering enabled (at least) on EP0 OUT, then the maximum allowed
time between calls to the USBDeviceTasks() function needs to be:
The faster of:
1. Once per ~1.8ms, when USBDeviceState == ADR_PENDING_STATE
2. Once per ~9.8ms, when USBDeviceState == (any other value other than ADR_PENDING_STATE)
3. Fast enough to ensure the USTAT FIFO can never get full. See additional explanation below.
Additional details of the above timing limits are provided:
Timing item #1: This parameter originates from the 2ms set address "recovery interval"
specification dictated by section "9.2.6.3 Set Address Processing" of the official
USB 2.0 specifications.
Timing item #2: This parameter originates from several "10 ms" criteria in the
USB 2.0 specifications. For example, reset recovery intervals, resume recovery
intervals, suspend to actual current reduction, etc. have timing maximums of 10ms.
Timing item #3: This is not a fixed X.X ms parameter, but depends on the
transaction rate implemented by the application. The USBDeviceTasks() function is
responsible for popping entries off the USTAT FIFO. If the FIFO ever gets full,
then no further USB transactions are allowed to occur, until the firmware pops entries
off the FIFO. In practice, this means the firmware should call USBDeviceTasks() at
a rate at least as fast as once every three times the USBTransferOnePacket() function
is called. This ensures that the rate that USTAT FIFO entries are getting added to
the FIFO is lower than the rate that the entries are getting popped off the FIFO (the
USBDeviceTasks() function will pop up to 4 entries per call), which is a
necessary criteria to ensure the USTAT FIFO entries don't "pile up." Calling
USBDeviceTasks() even more often, ex: >=1 to 1 ratio of USBDeviceTasks() to
USBTransferOnePacket(), adds further protection against the USTAT FIFO getting full,
and is therefore recommended.
When the USB stack is operated in USB_INTERRUPT mode, then the above timing
parameters should be interpreted to be the longest allowed time that the USB
interrupts may be masked/disabled for, before re-enabling the USB interrupts.
Calling USBDeviceTasks() (or allowing USBDeviceTasks() to be called) more often
will still have potential USB data rate speed and processing latency benefits.
It is also beneficial to call USBDeviceTasks() more often than theoretically
required, since it has been observed that not all host/drivers/bios/hubs are
100% consistently compliant with all timing parameters of the USB 2.0 specifications.
Therefore, in a USB_POLLING based application, it is still suggested to call
USBDeviceTasks() as often as there are free CPU cycles. This ensures best
performance, along with best possible compatibility with all existing USB
hosts/hubs (both those that are compliant and [partially] non-compliant).
If ping pong buffering is not enabled on (at least) EP0 OUT, then it is required
to call (or allow to execute) USBDeviceTasks() much more frequently (ex: once
per 100us, or preferrably faster). Therefore, in all applications, it is
normally recommended to select either the USB_PING_PONG__FULL_PING_PONG or
USB_PING_PONG__EP0_OUT_ONLY mode (user option in usb_config.h), as these modes
allow for much more relaxed timing requirements, and therefore greater application
firmware design flexibility.
//----------------------------------------------------------------------------------*/
/** INCLUDES *******************************************************/
#include "./USB/usb.h"
#include "HardwareProfile.h"
#include "usb_device_local.h"
#if defined(USB_USE_MSD)
#include "./USB/usb_function_msd.h"
#endif
#if !defined(USE_USB_BUS_SENSE_IO)
#undef USB_BUS_SENSE
#define USB_BUS_SENSE 1
#endif
#if defined(USB_DEVICE_DISABLE_DTS_CHECKING)
#define _DTS_CHECKING_ENABLED 0
#else
#define _DTS_CHECKING_ENABLED _DTSEN
#endif
/** DEFINITIONS ****************************************************/
/** VARIABLES ******************************************************/
#if defined(__18CXX)
#pragma udata
#endif
USB_VOLATILE USB_DEVICE_STATE USBDeviceState;
USB_VOLATILE BYTE USBActiveConfiguration;
USB_VOLATILE BYTE USBAlternateInterface[USB_MAX_NUM_INT];
volatile BDT_ENTRY *pBDTEntryEP0OutCurrent;
volatile BDT_ENTRY *pBDTEntryEP0OutNext;
volatile BDT_ENTRY *pBDTEntryOut[USB_MAX_EP_NUMBER+1];
volatile BDT_ENTRY *pBDTEntryIn[USB_MAX_EP_NUMBER+1];
USB_VOLATILE BYTE shortPacketStatus;
USB_VOLATILE BYTE controlTransferState;
USB_VOLATILE IN_PIPE inPipes[1];
USB_VOLATILE OUT_PIPE outPipes[1];
USB_VOLATILE BYTE *pDst;
USB_VOLATILE BOOL RemoteWakeup;
USB_VOLATILE BOOL USBBusIsSuspended;
USB_VOLATILE USTAT_FIELDS USTATcopy;
USB_VOLATILE BYTE endpoint_number;
USB_VOLATILE BOOL BothEP0OutUOWNsSet;
USB_VOLATILE EP_STATUS ep_data_in[USB_MAX_EP_NUMBER+1];
USB_VOLATILE EP_STATUS ep_data_out[USB_MAX_EP_NUMBER+1];
USB_VOLATILE BYTE USBStatusStageTimeoutCounter;
volatile BOOL USBDeferStatusStagePacket;
volatile BOOL USBStatusStageEnabledFlag1;
volatile BOOL USBStatusStageEnabledFlag2;
volatile BOOL USBDeferINDataStagePackets;
volatile BOOL USBDeferOUTDataStagePackets;
#if (USB_PING_PONG_MODE == USB_PING_PONG__NO_PING_PONG)
#define BDT_NUM_ENTRIES ((USB_MAX_EP_NUMBER + 1) * 2)
#elif (USB_PING_PONG_MODE == USB_PING_PONG__EP0_OUT_ONLY)
#define BDT_NUM_ENTRIES (((USB_MAX_EP_NUMBER + 1) * 2)+1)
#elif (USB_PING_PONG_MODE == USB_PING_PONG__FULL_PING_PONG)
#define BDT_NUM_ENTRIES ((USB_MAX_EP_NUMBER + 1) * 4)
#elif (USB_PING_PONG_MODE == USB_PING_PONG__ALL_BUT_EP0)
#define BDT_NUM_ENTRIES (((USB_MAX_EP_NUMBER + 1) * 4)-2)
#else
#error "No ping pong mode defined."
#endif
/** USB FIXED LOCATION VARIABLES ***********************************/
#if defined(__18CXX)
#pragma udata USB_BDT=USB_BDT_ADDRESS
#endif
volatile BDT_ENTRY BDT[BDT_NUM_ENTRIES] BDT_BASE_ADDR_TAG;
/********************************************************************
* Section B: EP0 Buffer Space
*******************************************************************/
volatile CTRL_TRF_SETUP SetupPkt CTRL_TRF_SETUP_ADDR_TAG;
volatile BYTE CtrlTrfData[USB_EP0_BUFF_SIZE] CTRL_TRF_DATA_ADDR_TAG;
/********************************************************************
* Section C: non-EP0 Buffer Space
*******************************************************************/
#if defined(USB_USE_MSD)
//volatile far USB_MSD_CBW_CSW msd_cbw_csw;
volatile USB_MSD_CBW msd_cbw;
volatile USB_MSD_CSW msd_csw;
//#pragma udata
#if defined(__18CXX)
#pragma udata myMSD=MSD_BUFFER_ADDRESS
#endif
volatile char msd_buffer[512];
#endif
////Depricated in v2.2 - will be removed in a future revision
#if !defined(USB_USER_DEVICE_DESCRIPTOR)
//Device descriptor
extern ROM USB_DEVICE_DESCRIPTOR device_dsc;
#else
USB_USER_DEVICE_DESCRIPTOR_INCLUDE;
#endif
#if !defined(USB_USER_CONFIG_DESCRIPTOR)
//Array of configuration descriptors
extern ROM BYTE *ROM USB_CD_Ptr[];
#else
USB_USER_CONFIG_DESCRIPTOR_INCLUDE;
#endif
extern ROM BYTE *ROM USB_SD_Ptr[];
/** DECLARATIONS ***************************************************/
#if defined(__18CXX)
#pragma code
#endif
/** Macros *********************************************************/
/** Function Prototypes ********************************************/
//External
//This is the prototype for the required user event handler
BOOL USER_USB_CALLBACK_EVENT_HANDLER(int event, void *pdata, WORD size);
//Internal Functions
static void USBCtrlEPService(void);
static void USBCtrlTrfSetupHandler(void);
static void USBCtrlTrfInHandler(void);
static void USBCheckStdRequest(void);
static void USBStdGetDscHandler(void);
static void USBCtrlEPServiceComplete(void);
static void USBCtrlTrfTxService(void);
static void USBCtrlTrfRxService(void);
static void USBStdSetCfgHandler(void);
static void USBStdGetStatusHandler(void);
static void USBStdFeatureReqHandler(void);
static void USBCtrlTrfOutHandler(void);
static void USBConfigureEndpoint(BYTE EPNum, BYTE direction);
static void USBWakeFromSuspend(void);
static void USBSuspend(void);
static void USBStallHandler(void);
//static BOOL USBIsTxBusy(BYTE EPNumber);
//static void USBPut(BYTE EPNum, BYTE Data);
//static void USBEPService(void);
//static void USBProtocolResetHandler(void);
/******************************************************************************/
/** Function Implementations *************************************************/
/******************************************************************************/
/******************************************************************************/
/** Internal Macros *********************************************************/
/******************************************************************************/
/****************************************************************************
Function:
void USBAdvancePingPongBuffer(BDT_ENTRY** buffer)
Description:
This function will advance the passed pointer to the next buffer based on
the ping pong option setting. This function should be used for EP1-EP15
only. This function is not valid for EP0.
Precondition:
None
Parameters:
BDT_ENTRY** - pointer to the BDT_ENTRY pointer that you want to be advanced
to the next buffer state
Return Values:
None
Remarks:
None
***************************************************************************/
#define USBAdvancePingPongBuffer(buffer) ((BYTE_VAL*)buffer)->Val ^= USB_NEXT_PING_PONG;
#define USBHALPingPongSetToOdd(buffer) {((BYTE_VAL*)buffer)->Val |= USB_NEXT_PING_PONG;}
#define USBHALPingPongSetToEven(buffer) {((BYTE_VAL*)buffer)->Val &= ~USB_NEXT_PING_PONG;}
/******************************************************************************/
/** External API Functions ****************************************************/
/******************************************************************************/
/**************************************************************************
Function:
void USBDeviceInit(void)
Description:
This function initializes the device stack it in the default state. The
USB module will be completely reset including all of the internal
variables, registers, and interrupt flags.
Precondition:
This function must be called before any of the other USB Device
functions can be called, including USBDeviceTasks().
Parameters:
None
Return Values:
None
Remarks:
None
***************************************************************************/
void USBDeviceInit(void)
{
BYTE i;
USBDisableInterrupts();
// Clear all USB error flags
USBClearInterruptRegister(U1EIR);
// Clears all USB interrupts
USBClearInterruptRegister(U1IR);
//Clear all of the endpoint control registers
U1EP0 = 0;
DisableNonZeroEndpoints(USB_MAX_EP_NUMBER);
SetConfigurationOptions();
//power up the module (if not already powered)
USBPowerModule();
//set the address of the BDT (if applicable)
USBSetBDTAddress(BDT);
//Clear all of the BDT entries
for(i=0;i<(sizeof(BDT)/sizeof(BDT_ENTRY));i++)
{
BDT[i].Val = 0x00;
}
// Assert reset request to all of the Ping Pong buffer pointers
USBPingPongBufferReset = 1;
// Reset to default address
U1ADDR = 0x00;
// Make sure packet processing is enabled
USBPacketDisable = 0;
//Stop trying to reset ping pong buffer pointers
USBPingPongBufferReset = 0;
// Flush any pending transactions
while(USBTransactionCompleteIF == 1)
{
USBClearInterruptFlag(USBTransactionCompleteIFReg,USBTransactionCompleteIFBitNum);
//Initialize USB stack software state variables
inPipes[0].info.Val = 0;
outPipes[0].info.Val = 0;
outPipes[0].wCount.Val = 0;
}
//Set flags to TRUE, so the USBCtrlEPAllowStatusStage() function knows not to
//try and arm a status stage, even before the first control transfer starts.
USBStatusStageEnabledFlag1 = TRUE;
USBStatusStageEnabledFlag2 = TRUE;
//Initialize other flags
USBDeferINDataStagePackets = FALSE;
USBDeferOUTDataStagePackets = FALSE;
USBBusIsSuspended = FALSE;
//Initialize all pBDTEntryIn[] and pBDTEntryOut[]
//pointers to NULL, so they don't get used inadvertently.
for(i = 0; i < (BYTE)(USB_MAX_EP_NUMBER+1u); i++)
{
pBDTEntryIn[i] = 0u;
pBDTEntryOut[i] = 0u;
ep_data_in[i].Val = 0u;
ep_data_out[i].Val = 0u;
}
//Get ready for the first packet
pBDTEntryIn[0] = (volatile BDT_ENTRY*)&BDT[EP0_IN_EVEN];
// Initialize EP0 as a Ctrl EP
U1EP0 = EP_CTRL|USB_HANDSHAKE_ENABLED;
//Prepare for the first SETUP on EP0 OUT
BDT[EP0_OUT_EVEN].ADR = ConvertToPhysicalAddress(&SetupPkt);
BDT[EP0_OUT_EVEN].CNT = USB_EP0_BUFF_SIZE;
BDT[EP0_OUT_EVEN].STAT.Val = _USIE|_DAT0|_BSTALL;
// Clear active configuration
USBActiveConfiguration = 0;
//Indicate that we are now in the detached state
USBDeviceState = DETACHED_STATE;
}
/**************************************************************************
Function:
void USBDeviceTasks(void)
Summary:
This function is the main state machine/transaction handler of the USB
device side stack. When the USB stack is operated in "USB_POLLING" mode
(usb_config.h user option) the USBDeviceTasks() function should be called
periodically to receive and transmit packets through the stack. This
function also takes care of control transfers associated with the USB
enumeration process, and detecting various USB events (such as suspend).
This function should be called at least once every 1.8ms during the USB
enumeration process. After the enumeration process is complete (which can
be determined when USBGetDeviceState() returns CONFIGURED_STATE), the
USBDeviceTasks() handler may be called the faster of: either once
every 9.8ms, or as often as needed to make sure that the hardware USTAT
FIFO never gets full. A good rule of thumb is to call USBDeviceTasks() at
a minimum rate of either the frequency that USBTransferOnePacket() gets
called, or, once/1.8ms, whichever is faster. See the inline code comments
near the top of usb_device.c for more details about minimum timing
requirements when calling USBDeviceTasks().
When the USB stack is operated in "USB_INTERRUPT" mode, it is not necessary
to call USBDeviceTasks() from the main loop context. In the USB_INTERRUPT
mode, the USBDeviceTasks() handler only needs to execute when a USB
interrupt occurs, and therefore only needs to be called from the interrupt
context.
Description:
This function is the main state machine/transaction handler of the USB
device side stack. When the USB stack is operated in "USB_POLLING" mode
(usb_config.h user option) the USBDeviceTasks() function should be called
periodically to receive and transmit packets through the stack. This
function also takes care of control transfers associated with the USB
enumeration process, and detecting various USB events (such as suspend).
This function should be called at least once every 1.8ms during the USB
enumeration process. After the enumeration process is complete (which can
be determined when USBGetDeviceState() returns CONFIGURED_STATE), the
USBDeviceTasks() handler may be called the faster of: either once
every 9.8ms, or as often as needed to make sure that the hardware USTAT
FIFO never gets full. A good rule of thumb is to call USBDeviceTasks() at
a minimum rate of either the frequency that USBTransferOnePacket() gets
called, or, once/1.8ms, whichever is faster. See the inline code comments
near the top of usb_device.c for more details about minimum timing
requirements when calling USBDeviceTasks().
When the USB stack is operated in "USB_INTERRUPT" mode, it is not necessary
to call USBDeviceTasks() from the main loop context. In the USB_INTERRUPT
mode, the USBDeviceTasks() handler only needs to execute when a USB
interrupt occurs, and therefore only needs to be called from the interrupt
context.
Typical usage:
<code>
void main(void)
{
USBDeviceInit();
while(1)
{
USBDeviceTasks(); //Takes care of enumeration and other USB events
if((USBGetDeviceState() \< CONFIGURED_STATE) ||
(USBIsDeviceSuspended() == TRUE))
{
//Either the device is not configured or we are suspended,
// so we don't want to execute any USB related application code
continue; //go back to the top of the while loop
}
else
{
//Otherwise we are free to run USB and non-USB related user
//application code.
UserApplication();
}
}
}
</code>
Precondition:
Make sure the USBDeviceInit() function has been called prior to calling
USBDeviceTasks() for the first time.
Remarks:
USBDeviceTasks() does not need to be called while in the USB suspend mode,
if the user application firmware in the USBCBSuspend() callback function
enables the ACTVIF USB interrupt source and put the microcontroller into
sleep mode. If the application firmware decides not to sleep the
microcontroller core during USB suspend (ex: continues running at full
frequency, or clock switches to a lower frequency), then the USBDeviceTasks()
function must still be called periodically, at a rate frequent enough to
ensure the 10ms resume recovery interval USB specification is met. Assuming
a worst case primary oscillator and PLL start up time of <5ms, then
USBDeviceTasks() should be called once every 5ms in this scenario.
When the USB cable is detached, or the USB host is not actively powering
the VBUS line to +5V nominal, the application firmware does not always have
to call USBDeviceTasks() frequently, as no USB activity will be taking
place. However, if USBDeviceTasks() is not called regularly, some
alternative means of promptly detecting when VBUS is powered (indicating
host attachment), or not powered (host powered down or USB cable unplugged)
is still needed. For self or dual self/bus powered USB applications, see
the USBDeviceAttach() and USBDeviceDetach() API documentation for additional
considerations.
**************************************************************************/
#if defined(USB_INTERRUPT)
#if defined(__18CXX) || defined (_PIC14E)
void USBDeviceTasks(void)
#elif defined(__C30__) || defined __XC16__
void __attribute__((interrupt,auto_psv)) _USB1Interrupt()
#elif defined(__PIC32MX__)
void __attribute__((interrupt(),vector(_USB_1_VECTOR))) _USB1Interrupt( void )
#endif
#else
void USBDeviceTasks(void)
#endif
{
BYTE i;
#ifdef USB_SUPPORT_OTG
//SRP Time Out Check
if (USBOTGSRPIsReady())
{
if (USBT1MSECIF && USBT1MSECIE)
{
if (USBOTGGetSRPTimeOutFlag())
{
if (USBOTGIsSRPTimeOutExpired())
{
USB_OTGEventHandler(0,OTG_EVENT_SRP_FAILED,0,0);
}
}
//Clear Interrupt Flag
USBClearInterruptFlag(USBT1MSECIFReg,USBT1MSECIFBitNum);
}
}
#endif
#if defined(USB_POLLING)
//If the interrupt option is selected then the customer is required
// to notify the stack when the device is attached or removed from the
// bus by calling the USBDeviceAttach() and USBDeviceDetach() functions.
if (USB_BUS_SENSE != 1)
{
// Disable module & detach from bus
U1CON = 0;
// Mask all USB interrupts
U1IE = 0;
//Move to the detached state
USBDeviceState = DETACHED_STATE;
#ifdef USB_SUPPORT_OTG
//Disable D+ Pullup
U1OTGCONbits.DPPULUP = 0;
//Disable HNP
USBOTGDisableHnp();
//Deactivate HNP
USBOTGDeactivateHnp();
//If ID Pin Changed State
if (USBIDIF && USBIDIE)
{
//Re-detect & Initialize
USBOTGInitialize();
//Clear ID Interrupt Flag
USBClearInterruptFlag(USBIDIFReg,USBIDIFBitNum);
}
#endif
#if defined __C30__ || defined __XC16__
//USBClearInterruptFlag(U1OTGIR, 3);
#endif
//return so that we don't go through the rest of
//the state machine
USBClearUSBInterrupt();
return;
}
#ifdef USB_SUPPORT_OTG
//If Session Is Started Then
else
{
//If SRP Is Ready
if (USBOTGSRPIsReady())
{
//Clear SRPReady
USBOTGClearSRPReady();
//Clear SRP Timeout Flag
USBOTGClearSRPTimeOutFlag();
//Indicate Session Started
UART2PrintString( "\r\n***** USB OTG B Event - Session Started *****\r\n" );
}
}
#endif //#ifdef USB_SUPPORT_OTG
//if we are in the detached state
if(USBDeviceState == DETACHED_STATE)
{
//Initialize register to known value
U1CON = 0;
// Mask all USB interrupts
U1IE = 0;
//Enable/set things like: pull ups, full/low-speed mode,
//set the ping pong mode, and set internal transceiver
SetConfigurationOptions();
// Enable module & attach to bus
while(!U1CONbits.USBEN){U1CONbits.USBEN = 1;}
//moved to the attached state
USBDeviceState = ATTACHED_STATE;
#ifdef USB_SUPPORT_OTG
U1OTGCON |= USB_OTG_DPLUS_ENABLE | USB_OTG_ENABLE;
#endif
}
#endif //#if defined(USB_POLLING)
if(USBDeviceState == ATTACHED_STATE)
{
/*
* After enabling the USB module, it takes some time for the
* voltage on the D+ or D- line to rise high enough to get out
* of the SE0 condition. The USB Reset interrupt should not be
* unmasked until the SE0 condition is cleared. This helps
* prevent the firmware from misinterpreting this unique event
* as a USB bus reset from the USB host.
*/
if(!USBSE0Event)
{
USBClearInterruptRegister(U1IR);// Clear all USB interrupts
#if defined(USB_POLLING)
U1IE=0; // Mask all USB interrupts
#endif
USBResetIE = 1; // Unmask RESET interrupt
USBIdleIE = 1; // Unmask IDLE interrupt
USBDeviceState = POWERED_STATE;
}
}
#ifdef USB_SUPPORT_OTG
//If ID Pin Changed State
if (USBIDIF && USBIDIE)
{
//Re-detect & Initialize
USBOTGInitialize();
USBClearInterruptFlag(USBIDIFReg,USBIDIFBitNum);
}
#endif
/*
* Task A: Service USB Activity Interrupt
*/
if(USBActivityIF && USBActivityIE)
{
USBClearInterruptFlag(USBActivityIFReg,USBActivityIFBitNum);
#if defined(USB_SUPPORT_OTG)
U1OTGIR = 0x10;
#else
USBWakeFromSuspend();
#endif
}
/*
* Pointless to continue servicing if the device is in suspend mode.
*/
if(USBSuspendControl==1)
{
USBClearUSBInterrupt();
return;
}
/*
* Task B: Service USB Bus Reset Interrupt.
* When bus reset is received during suspend, ACTVIF will be set first,
* once the UCONbits.SUSPND is clear, then the URSTIF bit will be asserted.
* This is why URSTIF is checked after ACTVIF.
*
* The USB reset flag is masked when the USB state is in
* DETACHED_STATE or ATTACHED_STATE, and therefore cannot
* cause a USB reset event during these two states.
*/
if(USBResetIF && USBResetIE)
{
USBDeviceInit();
//Re-enable the interrupts since the USBDeviceInit() function will
// disable them. This will do nothing in a polling setup
USBUnmaskInterrupts();
USBDeviceState = DEFAULT_STATE;
#ifdef USB_SUPPORT_OTG
//Disable HNP
USBOTGDisableHnp();
//Deactivate HNP
USBOTGDeactivateHnp();
#endif
USBClearInterruptFlag(USBResetIFReg,USBResetIFBitNum);
}
/*
* Task C: Service other USB interrupts
*/
if(USBIdleIF && USBIdleIE)
{
#ifdef USB_SUPPORT_OTG
//If Suspended, Try to switch to Host
USBOTGSelectRole(ROLE_HOST);
#else
USBSuspend();
#endif
USBClearInterruptFlag(USBIdleIFReg,USBIdleIFBitNum);
}
if(USBSOFIF)
{
if(USBSOFIE)
{
USB_SOF_HANDLER(EVENT_SOF,0,1);
}
USBClearInterruptFlag(USBSOFIFReg,USBSOFIFBitNum);
#if defined(USB_ENABLE_STATUS_STAGE_TIMEOUTS)
//Supporting this feature requires a 1ms timebase for keeping track of the timeout interval.
#if(USB_SPEED_OPTION == USB_LOW_SPEED)
#warning "Double click this message. See inline code comments."
//The "USB_ENABLE_STATUS_STAGE_TIMEOUTS" feature is optional and is
//not strictly needed in all applications (ex: those that never call
//USBDeferStatusStage() and don't use host to device (OUT) control
//transfers with data stage).
//However, if this feature is enabled and used, it requires a timer
//(preferrably 1ms) to decrement the USBStatusStageTimeoutCounter.
//In USB Full Speed applications, the host sends Start-of-Frame (SOF)
//packets at a 1ms rate, which generates SOFIF interrupts.
//These interrupts can be used to decrement USBStatusStageTimeoutCounter as shown
//below. However, the host does not send SOF packets to Low Speed devices.
//Therefore, some other method (ex: using a general purpose microcontroller
//timer, such as Timer0) needs to be implemented to call and execute the below code
//at a once/1ms rate, in a low speed USB application.
//Note: Pre-condition to executing the below code: USBDeviceInit() should have
//been called at least once (since the last microcontroller reset/power up),
//prior to executing the below code.
#endif
//Decrement our status stage counter.
if(USBStatusStageTimeoutCounter != 0u)
{
USBStatusStageTimeoutCounter--;
}
//Check if too much time has elapsed since progress was made in
//processing the control transfer, without arming the status stage.
//If so, auto-arm the status stage to ensure that the control
//transfer can [eventually] complete, within the timing limits
//dictated by section 9.2.6 of the official USB 2.0 specifications.
if(USBStatusStageTimeoutCounter == 0)
{
USBCtrlEPAllowStatusStage(); //Does nothing if the status stage was already armed.
}
#endif
}
if(USBStallIF && USBStallIE)
{
USBStallHandler();
}
if(USBErrorIF && USBErrorIE)
{
USB_ERROR_HANDLER(EVENT_BUS_ERROR,0,1);
USBClearInterruptRegister(U1EIR); // This clears UERRIF
//On PIC18, clearing the source of the error will automatically clear
// the interrupt flag. On other devices the interrupt flag must be
// manually cleared.
#if defined(__C32__) || defined(__C30__) || defined __XC16__
USBClearInterruptFlag( USBErrorIFReg, USBErrorIFBitNum );
#endif
}
/*
* Pointless to continue servicing if the host has not sent a bus reset.
* Once bus reset is received, the device transitions into the DEFAULT
* state and is ready for communication.
*/
if(USBDeviceState < DEFAULT_STATE)
{
USBClearUSBInterrupt();
return;
}
/*
* Task D: Servicing USB Transaction Complete Interrupt
*/
if(USBTransactionCompleteIE)
{
for(i = 0; i < 4u; i++) //Drain or deplete the USAT FIFO entries. If the USB FIFO ever gets full, USB bandwidth
{ //utilization can be compromised, and the device won't be able to receive SETUP packets.
if(USBTransactionCompleteIF)
{
//Save and extract USTAT register info. Will use this info later.
USTATcopy.Val = U1STAT;
endpoint_number = USBHALGetLastEndpoint(USTATcopy);
USBClearInterruptFlag(USBTransactionCompleteIFReg,USBTransactionCompleteIFBitNum);
//Keep track of the hardware ping pong state for endpoints other
//than EP0, if ping pong buffering is enabled.
#if (USB_PING_PONG_MODE == USB_PING_PONG__ALL_BUT_EP0) || (USB_PING_PONG_MODE == USB_PING_PONG__FULL_PING_PONG)
if(USBHALGetLastDirection(USTATcopy) == OUT_FROM_HOST)
{
ep_data_out[endpoint_number].bits.ping_pong_state ^= 1;
}
else
{
ep_data_in[endpoint_number].bits.ping_pong_state ^= 1;
}
#endif
//USBCtrlEPService only services transactions over EP0.
//It ignores all other EP transactions.
if(endpoint_number == 0)
{
USBCtrlEPService();
}
else
{
USB_TRANSFER_COMPLETE_HANDLER(EVENT_TRANSFER, (BYTE*)&USTATcopy.Val, 0);
}
}//end if(USBTransactionCompleteIF)
else
break; //USTAT FIFO must be empty.
}//end for()