-
Notifications
You must be signed in to change notification settings - Fork 7
/
usb_device.c
3129 lines (2750 loc) · 122 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
// DOM-IGNORE-BEGIN
/*******************************************************************************
Copyright 2015 Microchip Technology Inc. (www.microchip.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
To request to license the code under the MLA license (www.microchip.com/mla_license),
please contact [email protected]
*******************************************************************************/
//DOM-IGNORE-END
/*******************************************************************************
USB Device Layer
Company:
Microchip Technology Inc.
File Name:
usb_device.c
Summary:
Provides basic USB device functionality, including enumeration and USB
chapter 9 required behavior.
Description:
Provides basic USB device functionality, including enumeration and USB
chapter 9 required behavior.
*******************************************************************************/
// *****************************************************************************
// *****************************************************************************
// Section: Included Files
// *****************************************************************************
// *****************************************************************************
#include <xc.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include "usb_config.h"
#include "usb.h"
#include "usb_ch9.h"
#include "usb_device.h"
#include "usb_device_local.h"
#ifndef uintptr_t
#if defined(__XC8__) || defined(__XC16__)
#define uintptr_t uint16_t
#elif defined (__XC32__)
#define uintptr_t uint32_t
#endif
#endif
#if defined(USB_USE_MSD)
#include "usb_device_msd.h"
#endif
// *****************************************************************************
// *****************************************************************************
// Section: File Scope or Global Constants
// *****************************************************************************
// *****************************************************************************
#if !defined(USE_USB_BUS_SENSE_IO)
//Assume the +5V VBUS is always present (like it would be in a bus powered
//only application), unless USE_USB_BUS_SENSE_IO and USB_BUS_SENSE have
//been properly defined elsewhere in the project.
#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
#if !defined(self_power)
//Assume the application is always bus powered, unless self_power has been
//defined elsewhere in the project
#define self_power 0 //0 = bus powered
#endif
#if !defined(USB_MAX_NUM_CONFIG_DSC)
//Assume the application only implements one configuration descriptor,
//unless otherwise specified elsewhere in the project
#define USB_MAX_NUM_CONFIG_DSC 1
#endif
#if defined(__XC8)
//Suppress expected/harmless compiler warning message about unused RAM variables
//and certain function pointer usage.
//Certain variables and function pointers are not used if you don't use all
//of the USB stack APIs. However, these variables should not be
//removed (since they are still used/needed in some applications, and this
//is a common file shared by many projects, some of which rely on the "unused"
//variables/function pointers).
#pragma warning disable 1090
#if __XC8_VERSION > 1300
#pragma warning disable 1471
#endif
#endif
// *****************************************************************************
// *****************************************************************************
// Section: File Scope Data Types
// *****************************************************************************
// *****************************************************************************
typedef union
{
uint8_t Val;
struct __PACKED
{
unsigned b0:1;
unsigned b1:1;
unsigned b2:1;
unsigned b3:1;
unsigned b4:1;
unsigned b5:1;
unsigned b6:1;
unsigned b7:1;
} bits;
} uint8_t_VAL, uint8_t_BITS;
// *****************************************************************************
// *****************************************************************************
// Section: Variables
// *****************************************************************************
// *****************************************************************************
USB_VOLATILE USB_DEVICE_STATE USBDeviceState;
USB_VOLATILE uint8_t USBActiveConfiguration;
USB_VOLATILE uint8_t 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 uint8_t shortPacketStatus;
USB_VOLATILE uint8_t controlTransferState;
USB_VOLATILE IN_PIPE inPipes[1];
USB_VOLATILE OUT_PIPE outPipes[1];
USB_VOLATILE uint8_t *pDst;
USB_VOLATILE bool RemoteWakeup;
USB_VOLATILE bool USBBusIsSuspended;
USB_VOLATILE USTAT_FIELDS USTATcopy;
USB_VOLATILE uint8_t 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 uint8_t USBStatusStageTimeoutCounter;
volatile bool USBDeferStatusStagePacket;
volatile bool USBStatusStageEnabledFlag1;
volatile bool USBStatusStageEnabledFlag2;
volatile bool USBDeferINDataStagePackets;
volatile bool USBDeferOUTDataStagePackets;
USB_VOLATILE uint32_t USB1msTickCount;
USB_VOLATILE uint8_t USBTicksSinceSuspendEnd;
/** USB FIXED LOCATION VARIABLES ***********************************/
#if defined(COMPILER_MPLAB_C18)
#pragma udata USB_BDT=USB_BDT_ADDRESS
#endif
volatile BDT_ENTRY BDT[BDT_NUM_ENTRIES] BDT_BASE_ADDR_TAG;
/********************************************************************
* EP0 Buffer Space
*******************************************************************/
volatile CTRL_TRF_SETUP SetupPkt CTRL_TRF_SETUP_ADDR_TAG;
volatile uint8_t CtrlTrfData[USB_EP0_BUFF_SIZE] CTRL_TRF_DATA_ADDR_TAG;
/********************************************************************
* non-EP0 Buffer Space
*******************************************************************/
#if defined(USB_USE_MSD)
//Check if the MSD application specific USB endpoint buffer placement address
//macros have already been defined or not (ex: in a processor specific header)
//The msd_cbw and msd_csw buffers must be USB module accessible (and therefore
//must be at a certain address range on certain microcontrollers).
#if !defined(MSD_CBW_ADDR_TAG)
//Not previously defined. Assume in this case all microcontroller RAM is
//USB module accessible, and therefore, no specific address tag value is needed.
#define MSD_CBW_ADDR_TAG
#define MSD_CSW_ADDR_TAG
#endif
volatile USB_MSD_CBW msd_cbw MSD_CBW_ADDR_TAG; //Must be located in USB module accessible RAM
volatile USB_MSD_CSW msd_csw MSD_CSW_ADDR_TAG; //Must be located in USB module accessible RAM
#if defined(__18CXX) || defined(__XC8)
volatile char msd_buffer[512] @ MSD_BUFFER_ADDRESS;
#else
volatile char msd_buffer[512];
#endif
#endif
//Depricated in v2.2 - will be removed in a future revision
#if !defined(USB_USER_DEVICE_DESCRIPTOR)
//Device descriptor
extern const USB_DEVICE_DESCRIPTOR device_dsc;
#else
USB_USER_DEVICE_DESCRIPTOR_INCLUDE;
#endif
#if !defined(USB_USER_CONFIG_DESCRIPTOR)
//Array of configuration descriptors
extern const uint8_t *const USB_CD_Ptr[];
#else
USB_USER_CONFIG_DESCRIPTOR_INCLUDE;
#endif
extern const uint8_t *const USB_SD_Ptr[];
// *****************************************************************************
// *****************************************************************************
// Section: Private and External Prototypes
// *****************************************************************************
// *****************************************************************************
extern bool USER_USB_CALLBACK_EVENT_HANDLER(USB_EVENT event, void *pdata, uint16_t size);
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(uint8_t EPNum, uint8_t direction);
static void USBWakeFromSuspend(void);
static void USBSuspend(void);
static void USBStallHandler(void);
// *****************************************************************************
// *****************************************************************************
// Section: Macros or 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)
{
uint8_t i;
USBDisableInterrupts();
//Make sure that if a GPIO output driver exists on VBUS, that it is
//tri-stated to avoid potential contention with the host
USB_HAL_VBUSTristate();
// 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
do
{
USBClearInterruptFlag(USBTransactionCompleteIFReg,USBTransactionCompleteIFBitNum);
//Initialize USB stack software state variables
inPipes[0].info.Val = 0;
outPipes[0].info.Val = 0;
outPipes[0].wCount.Val = 0;
}while(USBTransactionCompleteIF == 1);
//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 < (uint8_t)(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 = _DAT0|_BSTALL;
BDT[EP0_OUT_EVEN].STAT.Val |= _USIE;
// Clear active configuration
USBActiveConfiguration = 0;
USB1msTickCount = 0; //Keeps track of total number of milliseconds since calling USBDeviceInit() when first initializing the USB module/stack code.
USBTicksSinceSuspendEnd = 0; //Keeps track of the number of milliseconds since a suspend condition has ended.
//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 less than 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.
***************************************************************************/
void USBDeviceTasks(void)
{
uint8_t 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)
{
//We recently attached, make sure we are in a clean state
#if defined(__dsPIC33E__) || defined(_PIC24E__) || defined(__PIC32MM__)
U1IR = 0xFFEF; //Preserve IDLEIF info, so we can detect suspend
//during attach de-bounce interval
#else
USBClearInterruptRegister(U1IR);
#endif
#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);
USBClearInterruptFlag(USBIdleIFReg,USBIdleIFBitNum);
#else
USBSuspend();
#endif
}
#if defined(__XC16__) || defined(__C30__) || defined(__XC32__)
//Check if a 1ms interval has elapsed.
if(USBT1MSECIF)
{
USBClearInterruptFlag(USBT1MSECIFReg, USBT1MSECIFBitNum);
USBIncrement1msInternalTimers();
}
#endif
//Start-of-Frame Interrupt
if(USBSOFIF)
{
//Call the user SOF event callback if enabled.
if(USBSOFIE)
{
USB_SOF_HANDLER(EVENT_SOF,0,1);
}
USBClearInterruptFlag(USBSOFIFReg,USBSOFIFBitNum);
#if defined(__XC8__) || defined(__C18__)
USBIncrement1msInternalTimers();
#endif
#if defined(USB_ENABLE_STATUS_STAGE_TIMEOUTS)
//Supporting this feature requires a 1ms time base 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 in a low speed application,
//it is required for the application code to periodically call the
//USBIncrement1msInternalTimers() function at a nominally 1ms rate.
#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, (uint8_t*)&USTATcopy.Val, 0);
}
}//end if(USBTransactionCompleteIF)
else
{
break; //USTAT FIFO must be empty.
}
}//end for()
}//end if(USBTransactionCompleteIE)
USBClearUSBInterrupt();
}//end of USBDeviceTasks()
/*******************************************************************************
Function:
void USBEnableEndpoint(uint8_t ep, uint8_t options)
Summary:
This function will enable the specified endpoint with the specified
options
Description:
This function will enable the specified endpoint with the specified
options.
Typical Usage:
<code>
void USBCBInitEP(void)
{
USBEnableEndpoint(MSD_DATA_IN_EP,USB_IN_ENABLED|USB_OUT_ENABLED|USB_HANDSHAKE_ENABLED|USB_DISALLOW_SETUP);
USBMSDInit();
}
</code>
In the above example endpoint number MSD_DATA_IN_EP is being configured
for both IN and OUT traffic with handshaking enabled. Also since
MSD_DATA_IN_EP is not endpoint 0 (MSD does not allow this), then we can
explicitly disable SETUP packets on this endpoint.
Conditions:
None
Input:
uint8_t ep - the endpoint to be configured
uint8_t options - optional settings for the endpoint. The options should
be ORed together to form a single options string. The
available optional settings for the endpoint. The
options should be ORed together to form a single options
string. The available options are the following\:
* USB_HANDSHAKE_ENABLED enables USB handshaking (ACK,
NAK)
* USB_HANDSHAKE_DISABLED disables USB handshaking (ACK,
NAK)
* USB_OUT_ENABLED enables the out direction
* USB_OUT_DISABLED disables the out direction
* USB_IN_ENABLED enables the in direction
* USB_IN_DISABLED disables the in direction
* USB_ALLOW_SETUP enables control transfers
* USB_DISALLOW_SETUP disables control transfers
* USB_STALL_ENDPOINT STALLs this endpoint
Return:
None
Remarks:
None
*****************************************************************************/
void USBEnableEndpoint(uint8_t ep, uint8_t options)
{
unsigned char* p;
//Use USBConfigureEndpoint() to set up the pBDTEntryIn/Out[ep] pointer and
//starting DTS state in the BDT entry.
if(options & USB_OUT_ENABLED)
{
USBConfigureEndpoint(ep, OUT_FROM_HOST);
}
if(options & USB_IN_ENABLED)
{
USBConfigureEndpoint(ep, IN_TO_HOST);
}
//Update the relevant UEPx register to actually enable the endpoint with
//the specified options (ex: handshaking enabled, control transfers allowed,
//etc.)
#if defined(__C32__)
p = (unsigned char*)(&U1EP0+(4*ep));
#else
p = (unsigned char*)(&U1EP0+ep);
#endif
*p = options;
}
/*************************************************************************
Function:
USB_HANDLE USBTransferOnePacket(uint8_t ep, uint8_t dir, uint8_t* data, uint8_t len)
Summary:
Transfers a single packet (one transaction) of data on the USB bus.
Description:
The USBTransferOnePacket() function prepares a USB endpoint
so that it may send data to the host (an IN transaction), or
receive data from the host (an OUT transaction). The
USBTransferOnePacket() function can be used both to receive and
send data to the host. This function is the primary API function
provided by the USB stack firmware for sending or receiving application
data over the USB port.
The USBTransferOnePacket() is intended for use with all application
endpoints. It is not used for sending or receiving application data
through endpoint 0 by using control transfers. Separate API
functions, such as USBEP0Receive(), USBEP0SendRAMPtr(), and
USBEP0SendROMPtr() are provided for this purpose.
The USBTransferOnePacket() writes to the Buffer Descriptor Table (BDT)
entry associated with an endpoint buffer, and sets the UOWN bit, which
prepares the USB hardware to allow the transaction to complete. The
application firmware can use the USBHandleBusy() macro to check the
status of the transaction, to see if the data has been successfully
transmitted yet.
Typical Usage
<code>
//make sure that the we are in the configured state
if(USBGetDeviceState() == CONFIGURED_STATE)
{
//make sure that the last transaction isn't busy by checking the handle
if(!USBHandleBusy(USBInHandle))
{
//Write the new data that we wish to send to the host to the INPacket[] array
INPacket[0] = USEFUL_APPLICATION_VALUE1;
INPacket[1] = USEFUL_APPLICATION_VALUE2;
//INPacket[2] = ... (fill in the rest of the packet data)
//Send the data contained in the INPacket[] array through endpoint "EP_NUM"
USBInHandle = USBTransferOnePacket(EP_NUM,IN_TO_HOST,(uint8_t*)&INPacket[0],sizeof(INPacket));
}
}
</code>
Conditions:
Before calling USBTransferOnePacket(), the following should be true.
1. The USB stack has already been initialized (USBDeviceInit() was called).
2. A transaction is not already pending on the specified endpoint. This
is done by checking the previous request using the USBHandleBusy()
macro (see the typical usage example).
3. The host has already sent a set configuration request and the
enumeration process is complete.
This can be checked by verifying that the USBGetDeviceState()
macro returns "CONFIGURED_STATE", prior to calling
USBTransferOnePacket().
Input:
uint8_t ep - The endpoint number that the data will be transmitted or
received on
uint8_t dir - The direction of the transfer
This value is either OUT_FROM_HOST or IN_TO_HOST
uint8_t* data - For IN transactions: pointer to the RAM buffer containing
the data to be sent to the host. For OUT transactions: pointer
to the RAM buffer that the received data should get written to.
uint8_t len - Length of the data needing to be sent (for IN transactions).
For OUT transactions, the len parameter should normally be set
to the endpoint size specified in the endpoint descriptor.
Return Values:
USB_HANDLE - handle to the transfer. The handle is a pointer to
the BDT entry associated with this transaction. The
status of the transaction (ex: if it is complete or still
pending) can be checked using the USBHandleBusy() macro
and supplying the USB_HANDLE provided by
USBTransferOnePacket().
Remarks:
If calling the USBTransferOnePacket() function from within the USBCBInitEP()
callback function, the set configuration is still being processed and the
USBDeviceState may not be == CONFIGURED_STATE yet. In this special case,
the USBTransferOnePacket() may still be called, but make sure that the
endpoint has been enabled and initialized by the USBEnableEndpoint()
function first.
*************************************************************************/
USB_HANDLE USBTransferOnePacket(uint8_t ep,uint8_t dir,uint8_t* data,uint8_t len)
{
volatile BDT_ENTRY* handle;
//If the direction is IN
if(dir != 0)