-
AN1140
INTRODUCTIONUSB has become the standard method for devices
tocommunicate with a PC. From general purposedevices, such as Flash
drives and mice, to special pur-pose devices for specific
applications, this popularstandard has almost totally replaced
other serialcommunication protocols.
Under the USB standard, USB devices may notcommunicate directly
with each other. They may onlycommunicate with a USB host which
controls the buson which one or more devices communicate. The
mostcommon USB host is a PC. With the introduction ofMicrochips
microcontrollers with the USB On-The-Go(OTG) module, it is now
possible for embeddedapplications to utilize the wide range of USB
devices asa USB embedded host.
USB OVERVIEWThere are many excellent references on USB,
includingthe USB 2.0 Specification itself, that provide
detailedinformation on USB operation. This section is intendedonly
to provide a brief definition of the terms referencedin this
application note or required to understand Stackoperation.
USB Hosts and Peripheral DevicesA typical USB system consists of
one host and one ormore peripheral devices, often referred to as
simplydevices. Each device can communicate only with thehost;
devices may not communicate directly with eachother. The host
initiates all communication on the bus. Adevice may send data to
the host only when the hostrequests it, and it must be able to
receive the data thatthe host sends. A device normally uses a
Type-Breceptacle or has a captive cable.
Most USB peripheral devices are divided intocategories, called
classes. Each class has specialrequirements regarding its
communication format. Thehost must be able to recognize a devices
class andmeet the classs requirements or the host cannot
com-municate with the device. Two example classes areHID (Human
Interface Device), such as found on amouse, and Mass Storage, such
as found on a Flashdrive. Client drivers provide application level
supportfor classes. Some USB peripheral devices are vendor-specific
and do not fall into one of the predefinedclasses. Client drivers
must be specifically written forthese devices.
The number of devices that can attach to a host can beexpanded
through the use of hubs. USB is a tiered starnetwork. Typically, a
hub allows four or seven devicesto attach to a single port. A
maximum of five hubs canbe chained together, creating up to five
tiers. Amaximum of 127 devices (including the hubs) can beconnected
on the bus.
A full USB host uses a Type-A receptacle, and must beable to
communicate with any device. This support maybe provided via
special drivers that must be installed onthe host prior to
attaching the device. Hubs must besupported, and each port must be
able to deliver aminimum of 100 mA.
Host vs. Embedded HostA USB embedded host differs from a USB
host inseveral small but important aspects. A USB embeddedhost:
Supports only specific peripheral devices and/or classes of
devices.
Supports only transfer types required by the supported
devices.
Hub support is optional. Has relaxed power requirements.
These restrictions allow an embedded host to beimplemented on a
device with fixed, limited memory.
Author: Kim OttenMicrochip Technology Inc.
USB Embedded Host Stack 2008 Microchip Technology Inc.
DS01140A-page 1
-
AN1140
Host Mode OperationIn a USB system, the host controls all
traffic on the bus.A device may only respond to requests from the
host; itmay not initiate a data transfer. The USB OTG modulemay be
used in either Host or Device mode. The exactmethod of operation
differs between the two modes.
USB transfers can consist of multiple transactions,
andtransactions can consist of multiple packets. Inaddition, a
single transfer can contain multiple datastage transactions. Figure
1 shows the generic formatof a single USB transfer.
FIGURE 1: GENERIC TRANSFER STRUCTUREDS01140A-page 2 2008
Microchip Technology Inc.
-
AN1140Control transfers often require all three transactions.
Acontrol transfer that reads 8 data bytes has thestructure shown in
Figure 2.
FIGURE 2: CONTROL TRANSFER STRUCTURE 2008 Microchip Technology
Inc. DS01140A-page 3
-
AN1140Bulk, interrupt and isochronous transfers do not
utilizethe SETUP token or the status transaction. With
bulktransfers, a maximum of 64 bytes may be transferred in
a single data stage transaction. A bulk transfer that writes128
data bytes requires two data stage transactions, andhas the
structure shown in Figure 3.
FIGURE 3: BULK TRANSFER STRUCTUREThe USB Embedded Host Stack
interfaces with theUSB OTG module in Host mode at the packet
level,with the exception that ACK packets are handled
auto-matically by the module. When the embedded hostissues the bulk
transfer shown in Figure 3, it must
explicitly issue commands to transfer the two OUT andtwo DATA0/1
packets. When the embedded hostissues the control transfer shown in
Figure 2, it mustexplicitly issue commands to transmit all
SETUP,DATA0/1, IN and OUT packets, for a total of 6
packets.DS01140A-page 4 2008 Microchip Technology Inc.
-
AN1140USB EMBEDDED HOST
Targeted Peripheral ListThe Targeted Peripheral List (TPL) is
the list ofperipheral devices that the USB embedded hostsupports.
Entries in the targeted peripheral list may
refer to specific products (using the VID and PID of
theproduct), or may refer to a class of products (usingclass,
subclass and protocol). For example, a TPL foran embedded host that
supports USB Flash drives andMicrochips PICDEM FS USB demonstration
wouldlook like Table 1:
TABLE 1: EMBEDDED HOST TPL
Dual Role Device or On-The-Go?A device can be a dual role device
by supporting bothembedded host and USB device functionality via
tworeceptacles. For example, a digital camera can act asa
peripheral device when downloading pictures to aPC, and act as an
embedded host when transferringpictures to a printer. The camera
would determine itsrole as device or host depending on what cable
wasattached. If a cable was attached to the Type-Areceptacle, the
camera would act as a host. If a cablewas attached to the Type-B
receptacle, the camerawould act as a device. The Type-A and Type-B
recep-tacles must both operate concurrently unless they areonly
accessible one at a time.
A USB On-The-Go device is a device that candynamically change
its role from an embedded host toa peripheral device without
changing cables. OTGdevices use a micro-AB receptacle. The initial
configu-ration is determined by the cable orientation. If
themicro-A plug of the cable is inserted, the device will
initially act as an embedded host. If the micro-B plug ofthe
cable is inserted, the device will initially act as aperipheral
device.
The choice of whether or not to utilize OTG depends onthe need
for the two devices to dynamically switchmodes. In most cases, the
host-peripheral role is con-stant for a pair of communicating
devices. For example,the dual role digital camera described above
wouldnever need to swap roles with the PC, or with theprinter, so
it would not require OTG functionality.
There are also restrictions placed on the TargetedPeripheral
List of an On-The-Go device. The TPL of theOTG device must list
only specific devices; it may notlist supported classes. For
example, an OTG devicecannot generically support USB Flash drives.
An OTGdevice may support a non OTG peripheral, but it mustdo so by
specifying the VID and PID of that device. ATPL for an OTG device
that supports MicrochipsPICDEM FS USB demonstration would look
likeTable 2:
TABLE 2: OTG TPL
Description Class Name Class Code Subclass Code Protocol
Flash Drive Mass Storage 0x08 0x06 0x50
Description Manufacturer Model VID PID
Full-Speed Demo Microchip PICDEM FS USB 0x04D8 0x000C
Description Manufacturer Model VID PID
Full-Speed Demo Microchip PICDEM FS USB 0x04D8 0x000C 2008
Microchip Technology Inc. DS01140A-page 5
-
AN1140USB EMBEDDED HOST STACKMicrochip provides a royalty-free
USB Embedded HostStack for use with Microchip microcontrollers.
ThisStack is designed to run on all Microchip devices thathave the
USB OTG module. Stack operation can beconfigured through the use of
various compile-timeoptions to optimize both speed and size for a
particularapplication.
The Stack is state machine based, and utilizes bothinterrupts
and a polling mechanism. Interrupts are usedfor all time critical
operations, while the pollingmechanism is used to handle operations
that are nottime critical. Both mechanisms must be used to
ensurecorrect operation of the Stack. The Stack can also
beconfigured to provide notification of some systemevents rather
than using the polling mechanism.
Installing the StackUSB support packages are available from
theMicrochip web site (http://www.microchip.com/usb).Download the
desired installation package from theweb site and run the
installation. Note that some USBdemos utilize libraries from other
application notes. Theinstallations for those libraries will also
be executed. Bydefault, the USB Host Stack files will be installed
in thedirectory structure shown in Figure 4.
FIGURE 4: INSTALLATION DIRECTORY STRUCTURE
Local Hard Drive (C:)
Microchip Solutions
Microchip
Common
Include
USB
USB
Documents
USBConfig.exe
USB Data Logger
Project Files
USB Source Files
Generic MicrochipSource Files
USB Header Files
Generic MicrochipHeader Files
+
+
+
+
+
+
+
+
Help+
Help Files
Client DriverDirectoriesDS01140A-page 6 2008 Microchip
Technology Inc.
-
AN1140
Stack ArchitectureThe USB Embedded Host Stack is modular,
non-blocking and RTOS independent. The Stack consists oftwo main
sections:
State machine for background processing, such as device
enumeration
Interrupt handler for time critical processing to utilize the
bus in an efficient manner
The state machine has the structure shown in Figure 5:
FIGURE 5: USB EMBEDDED HOST STATE MACHINE
DETACHEDSTATE
ATTACHEDSTATE
ADDRESSINGSTATE
RUNNINGSTATE
INIT
ValidationSuccessful
AddressAssigned
CONFIGURINGSTATEDevice
Configured
DeviceDeconfigured
DeattachInterrupt
DeattachInterrupt
DeattachInterrupt
DeattachInterrupt
AttachInterrupt
ValidationFailed 2008 Microchip Technology Inc. DS01140A-page
7
-
AN1140
When the device enters the running state, the Stackinforms the
client driver of the newly enumerateddevice by calling the
initialization event handler. Seethe Defining the Event Handlers
section for moreinformation about this event handler. If the client
driversuccessfully initializes, normal communication begins.
The USB bus operates with a 1 ms frame. Within thatframe,
multiple messages can be sent. Therefore,interrupts are used to
respond quickly enough toeffectively control USB traffic. The Stack
uses two keyinterrupts:
Start-Of-Frame (SOF Interrupt) Generated by the USB OTG module
when it is about to begin a new 1 ms frame.
Transaction Complete Interrupt Generated by the USB OTG module
when the last requested transaction is complete.
Upon receiving these interrupts, the Interrupt ServiceRoutine
(ISR) determines the next transaction, if any, tosend on the
bus.
Configuring the StackThe USB Host Stack and its client drivers
can be con-figured for a specific application by using the
configura-tion tool, USBConfig.exe, located in the
directorystructure shown in Figure 4.
As shown in Figure 6, the Device Type and Ping-PongMode first
need to be specified on the Main tab. Afterthe device type is
specified, appropriate configurationparameters are enabled on other
tabs to configure thehost/device and any required client
drivers.
FIGURE 6: USB CONFIGURATION MAINDS01140A-page 8 2008 Microchip
Technology Inc.
-
AN1140
If embedded host, dual role or OTG is specified, Hostmode can be
configured on the Host tab, as shown inFigure 7. The endpoint
support can be tailored to con-serve program memory. The attach
debounce intervalcan be increased from the USB specification value
of100 ms to allow support of slower devices. The name
of the function in the main source file that serves as
theapplication level event handler must be entered. Iftransfer
events are going to be used, the appropriatecheckbox must be
checked. See the Using TransferEvents section for more information
about usingtransfer events.
FIGURE 7: USB CONFIGURATION HOST 2008 Microchip Technology Inc.
DS01140A-page 9
-
AN1140
The TPL can be specified on the TPL tab, as shown inFigure 8.
Either VID/PID or class specification can beused. See the Targeted
Peripheral List section formore information about the TPL.
FIGURE 8: USB CONFIGURATION TPL
Application-specific class support can be configuredwith other
tabs. Refer to the associated USB applica-tion notes for more
information about the classes andtheir client drivers.
PIC24F Device RequirementsThe USB OTG module requires a 48 MHz
clock. Sincethis is beyond the maximum CPU clock speed, there isa
method to provide both the CPU and USB clocksfrom a single
oscillator source.
The oscillator source must operate at a frequency that isa
multiple of 4 MHz. This frequency is divided down to 4MHz by the
USB PLL prescaler. The USB PLL prescalerdoes not automatically
sense the incoming oscillator fre-quency. The user must manually
set the PLL dividerappropriately to generate the required 4 MHz
prescaleroutput, using the PLLDIV2:PLLDIV0 Configuration bits.This
limits the choices for primary oscillator frequency toa total of 8
possibilities, shown in Table 3.
TABLE 3: VALID PRIMARY OSCILLATOR CONFIGURATIONS FOR PIC24F USB
OPERATION
Note: The tolerance of the FRC oscillator isgreater than the USB
specification allows;therefore, FRC is not recommended.
Input Oscillator Frequency Clock Mode PLL Division (PLLDIV)
48 MHz ECPLL 12 (111)40 MHz ECPLL 10 (110)24 MHz HSPLL, ECPLL 6
(101)20 MHz HSPLL, ECPLL 5 (100)16 MHz HSPLL, ECPLL 4 (011)12 MHz
HSPLL, ECPLL 3 (010)8 MHz HSPLL, ECPLL 2 (001)4 MHz HSPLL, ECPLL,
XTPLL 1 (000)DS01140A-page 10 2008 Microchip Technology Inc.
-
AN1140
The USB PLL output is used to drive an on-chip96 MHz PLL
frequency multiplier, which drives twoclock branches. One branch
uses a fixed divide-by-2frequency divider to generate the 48 MHz
USB clock.The other branch uses a fixed divide-by-3
frequencydivider and a configurable PLL prescaler/divider(CLKDIV)
to generate a range of systemclock frequencies. The available
system clock optionsare listed in Table 4. Refer to the
microcontroller datasheet for more information about oscillator
modes.
TABLE 4: SYSTEM CLOCK OPTIONS DURING USB OPERATION
PIC32 RequirementsThe USB OTG module requires a 48 MHz clock.
Thereare three methods for providing this clock:
Use the 8 MHz FRC internal oscillator Provide a 48 MHz
oscillator on the OSC1/OSC2
pins Use the 96 MHz USB PLL from OSC1/OSC2
The USB PLL is enabled via the UPLLEN Configurationbit. The
oscillator source on the OSC1/OSC2 pins mustoperate at a frequency
that is a multiple of 4 MHz. Thisfrequency is divided down to 4 MHz
by the USB PLLprescaler. The USB PLL prescaler does not
automati-cally sense the incoming oscillator frequency. The
usermust manually set the PLL divider appropriately to gen-erate
the required 4 MHz output, using the UPLLIDIVConfiguration bits.
The 96 MHz PLL output is then fedinto a fixed divide-by-2 frequency
divider to generatethe 48 MHz USB clock. The system and peripheral
busclocks are not affected by the use of the USB PLL.
Alternately, the FRC can be used when the USBmodule needs a
clock source upon exit from Suspendmode. The FRC source is selected
by setting theOSCCON bit.
Project RequirementsThe USB Embedded Host Stack stores
informationabout the attached device in dynamic memory. Enoughheap
space must be allocated for the USB peripheralsdevice descriptor,
all configuration descriptors and64 bytes of overhead. Client
drivers may haveadditional dynamic memory requirements. If there
isnot enough dynamic memory to hold the deviceinformation, the
device will fail to enumerate.
Heap size can be specified in the MPLAB IDE projectby selecting
Project>Build Options>Project from theMPLAB IDE main menu.
For 16-bit microcontrollers,select the MPLAB LINK30 tab, and enter
a value in theheap size edit box. Then, click OK.
Using the StackMost applications will not interface directly
with theUSB Embedded Host Stack. Instead, they will use aclient
driver, which in turn will use the Host Stack. Someapplications
have additional layers that interface withthe client driver. For
example, the application describedby AN1145, Using a USB Flash
Drive on an Embed-ded Host has five layers, including the
applicationlayer, as shown by Figure 9.
FIGURE 9: USB FLASH DRIVE DATA LOGGER ARCHITECTURE
The information presented here is primarily intendedfor client
driver developers.
MCU Clock Division(CPUDIV)
Microcontroller Clock Frequency
None (00) 32 MHz2 (01) 16 MHz4 (10) 8 MHz8 (11) 4 MHz
Note: Check the device-specific data sheet forother possible
clocking options orrestrictions.
Note: Check the device-specific data sheet forother possible
clocking options orrestrictions.
Note: For detailed information about the USBEmbedded Host Stack
API, please refer tothe API documentation provided in the
Helpdirectory and AN1141, USB EmbeddedHost Stack Programmer's
Guide.
Application Layer
File System Support
SCSI Command Support
Mass Storage Client Driver
USB Host Driver 2008 Microchip Technology Inc. DS01140A-page
11
-
AN1140
Defining a TPLThe Targeted Peripheral List (TPL) must be defined
sothe Stack knows what USB peripheral devices it cansupport. If the
application is using USB OTG, the TPLmay consist only of specific
VID and PID pairs for thesupported devices. If the application is
using USBembedded host, then the TPL may consist of
supportedclasses as well as specific VID and PID pairs.
The TPL can be defined using the configuration
tool,USBConfig.exe, provided with the Stack. See theConfiguring the
Stack section.
Defining the Event Handlers
CLIENT LEVEL EVENTSThe Stack requires two event handlers in the
clientdriver. The first is the device initialization handler,
whichis called during device enumeration, after the
devicesconfiguration has been set. The device initializationhandler
should be of the type defined by the typedef:
typedef BOOL (*USB_CLIENT_INIT) ( BYTEaddress, DWORD flags
);This function performs device initialization specific to
thedevices class. If initialization occurs with no error,
thisroutine should return TRUE. If errors are encountered,this
routine should return FALSE, and the device will notbe enumerated.
Example 1 shows a sample initializationhandler.
EXAMPLE 1: INITIALIZATION HANDLERBOOL USBHostSampleInitialize(
BYTE address, DWORD flags ){ // This handler supports one attached
device. if (deviceHandle != 0) { return FALSE; // We cannot support
this device. } deviceHandle = address;
// Initialize something based on flags. if (flags & 0x01) {
// Do something } else { // Do something else } return TRUE; //
Device successfully initialized}DS01140A-page 12 2008 Microchip
Technology Inc.
-
AN1140The second event handler is required to handle eventsthat
occur during normal operation. This event handlershould be of the
type defined by the typedef:
typedef BOOL (*USB_CLIENT_EVENT_HANDLER)( BYTE address,
USB_EVENT event, void*data, DWORD size );
For example, one of the events that can occur isEVENT_DETACH.
This occurs when a device hasdetached from the bus. In this case,
the client driver willneed to update its status by doing
operations, such asremoving the device from its list of attached
devicesthat utilize the client driver. Example 2 shows a
sampleevent handler.
EXAMPLE 2: EVENT HANDLERBOOL USBHostSampleEventHandler( BYTE
address, USB_EVENT event, void *data, DWORD size ){ switch (event)
{ case EVENT_DETACH: deviceHandle = 0; return TRUE; break;
// More events handled here } return FALSE; // We did not handle
the event}Several events are provided for OTG operations.
Inaddition, the Stack can be configured to provide trans-fer events
(EVENT_TRANSFER). Refer to the UsingTransfer Events section.See the
API documentation in the Help directory for acomplete list of
events.
The Stack requires a list of all initialization and
eventhandlers for every supported client driver. This listcan be
defined using the configuration tool,USBConfig.exe, provided with
the Stack. See theConfiguring the Stack section. 2008 Microchip
Technology Inc. DS01140A-page 13
-
AN1140
APPLICATION LEVEL EVENTSSome events are intended for the top
level applicationrather than the client driver. The primary example
ofthis type of event is EVENT_REQUEST_POWER. Thisevent is generated
when a device requests power whilein the process of enumerating. If
the application needsto monitor or control how much power is
allocated tothe attached device, it must implement an
application
event handler. This event handler must also be of thetype,
USB_CLIENT_EVENT_HANDLER, shown above.The name of the event handler
must be entered into theName of Application Event Handler field on
the Hosttab of the configuration tool, USBConfig.exe (see
theConfiguring the Stack section). Example 3 shows aminimum event
handler for controlling power.
EXAMPLE 3: APPLICATION LEVEL EVENT HANDLER
If no event handler is implemented, the EmbeddedHost Stack will
respond as if the event handler returnedTRUE.
Stack InitializationUSB embedded host operation is initialized
by a singlefunction:
BYTE USBHostInit( void );This function initializes all internal
variables for Stackoperation. It should only be called once during
theapplications execution. The USB OTG module on themicrocontroller
is not configured in this function.
The USB configuration tool will create a macro,USBInitialize(),
to call all of the initializationroutines required by the USB host
driver and thesupported client drivers.
Normal Stack OperationAfter initialization, USB OTG module
configurationand USB embedded host operation are triggered by
asingle function:
void USBHostTasks( void );
This function implements the state machine required toenumerate
a device. It should be called at regularintervals to ensure timely
enumeration.
The USB configuration tool will create a macro,USBTasks(), to
call all of the task routines required bythe USB host driver and
the supported client drivers.
Communicating with a Peripheral Device
Normal communication with a device is initiated by
twofunctions:
BYTE USBHostRead( BYTE deviceAddress,BYTE endpoint, BYTE *data,
DWORD size );BYTE USBHostWrite( BYTE deviceAddress,BYTE endpoint,
BYTE *data, DWORD size );A return code of USB_SUCCESS (0x00)
indicates thatthe operation was started successfully.
BOOL USB_ApplicationEventHandler( BYTE address, USB_EVENT event,
void *data, DWORD size ){ switch( event ) { case
EVENT_REQUEST_POWER: // data points to a byte that represents the
amount // of power requested in mA, divided by two. if
(*(BYTE*)data > 50) // We will allow up to 100mA { return FALSE;
} break; } return TRUE; // Allow all other events to pass.}
Note: Applications should use theUSBInitialize() macro instead
of thelower level function call.
Note: Applications should use the USBTasks()macro instead of the
lower level functioncall.
Note: This section describes the routinesrequired for a client
driver to communicatewith a peripheral device. Application
levelcode will not call these functions; instead,they will utilize
the appropriate routine(s)in the client driver(s).DS01140A-page 14
2008 Microchip Technology Inc.
-
AN1140
After initiating communication, take care thatUSBTasks()
(USBHostTasks() and any requiredclient tasks) are performed while
waiting for the opera-tion to complete. The status of the operation
can bedetermined by calling the function:
BOOL USBHostTransferIsComplete( BYTEdeviceAddress, BYTE
endpoint, BYTE*errorCode, DWORD *byteCount );
If the function returns FALSE, the transfer is not com-plete,
and the returned error code and byte count arenot valid. If the
function returns TRUE, the returnederror code indicates the status
of the operation, and thereturned byte count indicates how many
bytes weretransferred.
A transfer of data from the host to the device might looklike
Example 4.
EXAMPLE 4: SEND DATA TO A PERIPHERAL DEVICEerror = USBHostWrite(
device, EP1, buffer, sizeof(buffer) );if (error){ // There was a
problem}else{ while (!USBHostTransferIsComplete( device, EP1,
&error, &count )) { USBHostTasks(); } if (error) { // There
was a problem } else { // The data was transferred successfully }}
2008 Microchip Technology Inc. DS01140A-page 15
-
AN1140
Advanced Stack Use
USING TRANSFER EVENTSExample 4 shows a simple method of
transferring data,but it has the disadvantage that execution is
trapped ina loop while waiting for the transfer to complete. Oneway
to avoid this is to utilize transfer events.
All client drivers must have an event handler, sincesome events
must be supported for basic Stack opera-tion. Transfer events,
however, are optional, since theymay not be needed for all
applications and theyincrease required resources.
Transfer events operate differently than other events inthe
system. The completion status of a USB transfer isdetermined in the
USB ISR, when the transaction com-plete interrupt fires. However,
the transfer event is notgenerated at this point. In order to
utilize the busefficiently, USB interrupts must be as short as
possibleto allow as many transactions as possible within oneUSB
frame (1 ms). The client drivers event handlermay be rather large
and require a great deal of time toexecute, and it may generate
another event that mustbe handled by another layer of the
application, resultingin a very long delay. Therefore, a transfer
event queueis used. Transfer events (EVENT_TRANSFER) areenqueued in
the ISR along with a structure of the type,HOST_TRANSFER_DATA, so
the application can deter-mine what transfer completed and whether
or not it wassuccessful. The function, USBHostTasks(),dequeues the
transfer events and sends them to theclient drivers event
handler.
In general, more program and data memory are requiredto support
transfer events due to the transfer eventqueue. The code
architecture is more sophisticated, andthis architecture is more
difficult for a beginning Cprogrammer to design, develop, debug and
maintain.However, transfer events allow the client driver to
mini-mize or even eliminate a background task processingfunction,
utilizing processing bandwidth more efficiently.
TERMINATING TRANSFERSThe Stack has the ability to automatically
terminatetransfers that the device is failing to respond to
bycounting the number of NAKs that the device sends. Ifthe
application requires a different time-outmechanism, it can
terminate a transfer manually bycalling the function:
void USBHostTerminateTransfer( BYTEdeviceAddress, BYTE endpoint
);
ISSUING STANDARD DEVICE REQUESTSAll USB devices respond to
certain requests from thehost. The application may issue USB
standard devicerequests by calling the function:
BYTE USBHostDeviceRequest( BYTEdeviceAddress, BYTE
bmRequestType, BYTEbRequest, WORD wValue, WORD wIndex, WORDwLength,
BYTE *data, BYTE dataDirection);The Stack will then issue the
requested control transferon Endpoint 0. Refer to the USB 2.0
Specification formore information about standard device
requests.
CLEARING ENDPOINT ERRORSIf a transfer is unsuccessful because
too many errorsoccurred, or because the device stalled the
endpoint,the error must be cleared before another transfer canbe
attempted. The error condition may be cleared bycalling the
function:
BYTE USBHostClearEndpointErrors( BYTEdeviceAddress, BYTE
endpoint );If a stall occurred, USBHostClearEndpointErrors()must be
called, plus the stall condition on the devicemust be cleared. This
is done by issuing a CLEARFEATURE device request (as described in
the IssuingStandard Device Requests section) with theENDPOINT HALT
feature selector and the endpointnumber that is currently stalled.
Refer to the USB 2.0Specification for more information about the
CLEARFEATURE device request.
ACCESSING THE DEVICE AND CONFIGURATION DESCRIPTORSDuring
enumeration, the Stack obtains and storesthe device descriptor and
the configurationdescriptors of the device. The client driver
canaccess the device descriptor by using
theUSBHostGetDeviceDescriptor() function. Thisfunction returns a
pointer to the device descriptor.
BYTE * USBHostGetDeviceDescriptor( BYTEdeviceAddress );The
client driver can also access the configurationdescriptor of the
current configuration by using thefunction,
USBHostGetCurrentConfiguration-Descriptor(). This function also
returns a pointerto the descriptor.
BYTE * USBHostGetCurrentConfiguration-Descriptor( BYTE
deviceAddress )DS01140A-page 16 2008 Microchip Technology Inc.
-
AN1140
GETTING STRING DESCRIPTORSA USB peripheral device may contain
one or more stringdescriptors that describe items, such as the
product, themanufacturer and the devices serial number. The indexof
the desired string can be obtained by referencing theappropriate
field in the device descriptor. Then, thedesired string can be
obtained by calling the function:
BYTE USBHostGetStringDescriptor ( BYTEdeviceAddress, BYTE
stringNumber, BYTE*stringDescriptor, BYTE stringLength )
Example 5 shows how to obtain an attached devicesserial
number.
Refer to the USB 2.0 Specification for more informationabout the
device descriptor and string descriptors.
EXAMPLE 5: RETRIEVING A DEVICES SERIAL NUMBERdeviceDescriptor =
USBHostGetDeviceDescriptor( device );snIndex =
deviceDescriptor[16]; //See Device Descriptor spec.
if (snIndex != 0){ if (!USBHostGetStringDescriptor( device,
snIndex, buffer, 50 )) { while(!USBHostTransferIsComplete( device,
0, &error, &count )) { USBHostTasks(); } if (!error) { //
Serial number is in buffer[] in UNICODE } }} 2008 Microchip
Technology Inc. DS01140A-page 17
-
AN1140CONCLUSION The USB Embedded Host Stack for Microchips
16-bitand 32-bit microcontrollers provides a platform forsupporting
various USB classes. With these solutions,applications can now
utilize the wide variety of avail-able USB peripheral devices,
including mass storageand human interface devices. The USB
embeddedhost capability of the USB OTG module, available onselect
16-bit and 32-bit Microchip microcontrollers,opens a whole new
world for embedded applications.
REFERENCES AN1141, USB Embedded Host Stack
Programmers Guide (http://www.microchip.com) AN1142, USB Mass
Storage Class on an
Embedded Host (http://www.microchip.com) AN1143, USB Generic
Client on an Embedded
Host (http://www.microchip.com) AN1144, USB HID Class on an
Embedded Host
(http://www.microchip.com) AN1145, Using a USB Flash Drive on
an
Embedded Host (http://www.microchip.com) Universal Serial Bus
web site (http://www.usb.org) Microchip Technology Inc. web
site
(http://www.microchip.com)DS01140A-page 18 2008 Microchip
Technology Inc.
-
Note the following details of the code protection feature on
Microchip devices: Microchip products meet the specification
contained in their particular Microchip Data Sheet.
Microchip believes that its family of products is one of the
most secure families of its kind on the market today, when used in
the intended manner and under normal conditions.
There are dishonest and possibly illegal methods used to
breachknowledge, require using the Microchip products in a manner
ou
of in
rned
er canle.
mitteay b
workInformation contained in this publication regarding
deviceapplications and the like is provided only for your
convenienceand may be superseded by updates. It is your
responsibility toensure that your application meets with your
specifications.MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF
ANY KIND WHETHER EXPRESS ORIMPLIED, WRITTEN OR ORAL, STATUTORY
OROTHERWISE, RELATED TO THE INFORMATION,INCLUDING BUT NOT LIMITED
TO ITS CONDITION,QUALITY, PERFORMANCE, MERCHANTABILITY ORFITNESS
FOR PURPOSE. Microchip disclaims all liabilityarising from this
information and its use. Use of Microchipdevices in life support
and/or safety applications is entirely atthe buyers risk, and the
buyer agrees to defend, indemnify andhold harmless Microchip from
any and all damages, claims,suits, or expenses resulting from such
use. No licenses are
Sheets. Most likely, the person doing so is engaged in theft
Microchip is willing to work with the customer who is conce
Neither Microchip nor any other semiconductor manufacturmean
that we are guaranteeing the product as unbreakab
Code protection is constantly evolving. We at Microchip are
comproducts. Attempts to break Microchips code protection feature
mallow unauthorized access to your software or other copyrighted
2008 Microchip Technology Inc.
conveyed, implicitly or otherwise, under any
Microchipintellectual property rights.Trademarks
The Microchip name and logo, the Microchip logo, Accuron, dsPIC,
KEELOQ, KEELOQ logo, MPLAB, PIC, PICmicro, PICSTART, PRO MATE,
rfPIC and SmartShunt are registered trademarks of Microchip
Technology Incorporated in the U.S.A. and other countries.
FilterLab, Linear Active Thermistor, MXDEV, MXLAB, SEEVAL,
SmartSensor and The Embedded Control Solutions Company are
registered trademarks of Microchip Technology Incorporated in the
U.S.A.
Analog-for-the-Digital Age, Application Maestro, CodeGuard,
dsPICDEM, dsPICDEM.net, dsPICworks, dsSPEAK, ECAN, ECONOMONITOR,
FanSense, In-Circuit Serial Programming, ICSP, ICEPIC, Mindi, MiWi,
MPASM, MPLAB Certified logo, MPLIB, MPLINK, mTouch, PICkit,
PICDEM,
the code protection feature. All of these methods, to our tside
the operating specifications contained in Microchips Data
tellectual property.
about the integrity of their code.
guarantee the security of their code. Code protection does
not
d to continuously improving the code protection features of oure
a violation of the Digital Millennium Copyright Act. If such acts,
you may have a right to sue for relief under that Act.DS01140A-page
19
PICDEM.net, PICtail, PIC32 logo, PowerCal, PowerInfo, PowerMate,
PowerTool, REAL ICE, rfLAB, Select Mode, Total Endurance, UNI/O,
WiperLock and ZENA are trademarks of Microchip Technology
Incorporated in the U.S.A. and other countries.
SQTP is a service mark of Microchip Technology Incorporated in
the U.S.A.
All other trademarks mentioned herein are property of their
respective companies.
2008, Microchip Technology Incorporated, Printed in the U.S.A.,
All Rights Reserved.
Printed on recycled paper.
Microchip received ISO/TS-16949:2002 certification for its
worldwide headquarters, design and wafer fabrication facilities in
Chandler and Tempe, Arizona; Gresham, Oregon and design centers in
California and India. The Companys quality system processes and
procedures are for its PIC MCUs and dsPIC DSCs, KEELOQ code hopping
devices, Serial EEPROMs, microperipherals, nonvolatile memory and
analog products. In addition, Microchips quality system for the
design and manufacture of development systems is ISO 9001:2000
certified.
-
DS01140A-page 20 2008 Microchip Technology Inc.
AMERICASCorporate Office2355 West Chandler Blvd.Chandler, AZ
85224-6199Tel: 480-792-7200 Fax: 480-792-7277Technical Support:
http://support.microchip.comWeb Address:
www.microchip.comAtlantaDuluth, GA Tel: 678-957-9614 Fax:
678-957-1455BostonWestborough, MA Tel: 774-760-0087 Fax:
774-760-0088ChicagoItasca, IL Tel: 630-285-0071 Fax:
630-285-0075DallasAddison, TX Tel: 972-818-7423 Fax:
972-818-2924DetroitFarmington Hills, MI Tel: 248-538-2250Fax:
248-538-2260KokomoKokomo, IN Tel: 765-864-8360Fax: 765-864-8387Los
AngelesMission Viejo, CA Tel: 949-462-9523 Fax: 949-462-9608Santa
ClaraSanta Clara, CA Tel: 408-961-6444Fax:
408-961-6445TorontoMississauga, Ontario, CanadaTel: 905-673-0699
Fax: 905-673-6509
ASIA/PACIFICAsia Pacific OfficeSuites 3707-14, 37th FloorTower
6, The GatewayHarbour City, KowloonHong KongTel: 852-2401-1200Fax:
852-2401-3431Australia - SydneyTel: 61-2-9868-6733Fax:
61-2-9868-6755China - BeijingTel: 86-10-8528-2100 Fax:
86-10-8528-2104China - ChengduTel: 86-28-8665-5511Fax:
86-28-8665-7889China - Hong Kong SARTel: 852-2401-1200 Fax:
852-2401-3431China - NanjingTel: 86-25-8473-2460Fax:
86-25-8473-2470China - QingdaoTel: 86-532-8502-7355Fax:
86-532-8502-7205China - ShanghaiTel: 86-21-5407-5533 Fax:
86-21-5407-5066China - ShenyangTel: 86-24-2334-2829Fax:
86-24-2334-2393China - ShenzhenTel: 86-755-8203-2660 Fax:
86-755-8203-1760China - WuhanTel: 86-27-5980-5300Fax:
86-27-5980-5118China - XiamenTel: 86-592-2388138 Fax:
86-592-2388130China - XianTel: 86-29-8833-7252Fax:
86-29-8833-7256China - ZhuhaiTel: 86-756-3210040 Fax:
86-756-3210049
ASIA/PACIFICIndia - BangaloreTel: 91-80-4182-8400 Fax:
91-80-4182-8422India - New DelhiTel: 91-11-4160-8631Fax:
91-11-4160-8632India - PuneTel: 91-20-2566-1512Fax:
91-20-2566-1513Japan - YokohamaTel: 81-45-471- 6166 Fax:
81-45-471-6122Korea - DaeguTel: 82-53-744-4301Fax:
82-53-744-4302Korea - SeoulTel: 82-2-554-7200Fax: 82-2-558-5932 or
82-2-558-5934Malaysia - Kuala LumpurTel: 60-3-6201-9857Fax:
60-3-6201-9859Malaysia - PenangTel: 60-4-227-8870Fax:
60-4-227-4068Philippines - ManilaTel: 63-2-634-9065Fax:
63-2-634-9069SingaporeTel: 65-6334-8870Fax: 65-6334-8850Taiwan -
Hsin ChuTel: 886-3-572-9526Fax: 886-3-572-6459Taiwan -
KaohsiungTel: 886-7-536-4818Fax: 886-7-536-4803Taiwan - TaipeiTel:
886-2-2500-6610 Fax: 886-2-2508-0102Thailand - BangkokTel:
66-2-694-1351Fax: 66-2-694-1350
EUROPEAustria - WelsTel: 43-7242-2244-39Fax:
43-7242-2244-393Denmark - CopenhagenTel: 45-4450-2828 Fax:
45-4485-2829France - ParisTel: 33-1-69-53-63-20 Fax:
33-1-69-30-90-79Germany - MunichTel: 49-89-627-144-0 Fax:
49-89-627-144-44Italy - Milan Tel: 39-0331-742611 Fax:
39-0331-466781Netherlands - DrunenTel: 31-416-690399 Fax:
31-416-690340Spain - MadridTel: 34-91-708-08-90Fax:
34-91-708-08-91UK - WokinghamTel: 44-118-921-5869Fax:
44-118-921-5820
WORLDWIDE SALES AND SERVICE
01/02/08
IntroductionUSB OverviewUSB Hosts and Peripheral DevicesHost vs.
Embedded HostHost Mode OperationFIGURE 1: Generic Transfer
StructureFIGURE 2: Control Transfer StructureFIGURE 3: Bulk
Transfer Structure
USB Embedded HostTargeted Peripheral ListTABLE 1: Embedded Host
TPL
Dual Role Device or On-The-Go?TABLE 2: OTG TPL
USB Embedded Host StackInstalling the StackFIGURE 4:
Installation Directory Structure
Stack ArchitectureFIGURE 5: USB Embedded Host State Machine
Configuring the StackFIGURE 6: USB Configuration - MainFIGURE 7:
USB Configuration - HostFIGURE 8: USB Configuration - TPL
PIC24F Device RequirementsTABLE 3: Valid Primary Oscillator
Configurations for PIC24F USB OperationTABLE 4: System Clock
Options During USB Operation
PIC32 RequirementsProject RequirementsUsing the StackFIGURE 9:
USB Flash Drive Data Logger Architecture
Defining a TPLDefining the Event HandlersClient Level
EventsEXAMPLE 1: Initialization HandlerEXAMPLE 2: Event Handler
Application Level EventsEXAMPLE 3: Application Level Event
Handler
Stack InitializationNormal Stack OperationCommunicating with a
Peripheral DeviceEXAMPLE 4: Send Data to a Peripheral Device
Advanced Stack UseUsing Transfer EventsTerminating
TransfersIssuing Standard Device RequestsClearing Endpoint
ErrorsAccessing the Device and Configuration DescriptorsGetting
String DescriptorsEXAMPLE 5: Retrieving a Devices Serial Number
ConclusionReferencesWorldwide Sales and Service
/ColorImageDict > /JPEG2000ColorACSImageDict >
/JPEG2000ColorImageDict > /AntiAliasGrayImages false
/CropGrayImages true /GrayImageMinResolution 300
/GrayImageMinResolutionPolicy /OK /DownsampleGrayImages true
/GrayImageDownsampleType /Bicubic /GrayImageResolution 300
/GrayImageDepth -1 /GrayImageMinDownsampleDepth 2
/GrayImageDownsampleThreshold 1.50000 /EncodeGrayImages true
/GrayImageFilter /DCTEncode /AutoFilterGrayImages true
/GrayImageAutoFilterStrategy /JPEG /GrayACSImageDict >
/GrayImageDict > /JPEG2000GrayACSImageDict >
/JPEG2000GrayImageDict > /AntiAliasMonoImages false
/CropMonoImages true /MonoImageMinResolution 1200
/MonoImageMinResolutionPolicy /OK /DownsampleMonoImages true
/MonoImageDownsampleType /Bicubic /MonoImageResolution 1200
/MonoImageDepth -1 /MonoImageDownsampleThreshold 1.50000
/EncodeMonoImages true /MonoImageFilter /CCITTFaxEncode
/MonoImageDict > /AllowPSXObjects false /CheckCompliance [ /None
] /PDFX1aCheck false /PDFX3Check false /PDFXCompliantPDFOnly false
/PDFXNoTrimBoxError true /PDFXTrimBoxToMediaBoxOffset [ 0.00000
0.00000 0.00000 0.00000 ] /PDFXSetBleedBoxToMediaBox true
/PDFXBleedBoxToTrimBoxOffset [ 0.00000 0.00000 0.00000 0.00000 ]
/PDFXOutputIntentProfile (None) /PDFXOutputConditionIdentifier ()
/PDFXOutputCondition () /PDFXRegistryName () /PDFXTrapped
/False
/Description > /Namespace [ (Adobe) (Common) (1.0) ]
/OtherNamespaces [ > /FormElements false /GenerateStructure
false /IncludeBookmarks false /IncludeHyperlinks false
/IncludeInteractive false /IncludeLayers false /IncludeProfiles
false /MultimediaHandling /UseObjectSettings /Namespace [ (Adobe)
(CreativeSuite) (2.0) ] /PDFXOutputIntentProfileSelector
/DocumentCMYK /PreserveEditing true /UntaggedCMYKHandling
/LeaveUntagged /UntaggedRGBHandling /UseDocumentProfile
/UseDocumentBleed false >> ]>> setdistillerparams>
setpagedevice