Download - USB Made Simple - Part 4
7/31/2019 USB Made Simple - Part 4
http://slidepdf.com/reader/full/usb-made-simple-part-4 1/18
Index
Part 1
Part 2
Part 3
Part 4
Part 5
Part 6
Part 7
Links
Back Part 4 - Protocol Forward
Controlling a
DeviceBefore we go into detail,we need to look at how thehost recognises andinstalls a device when youplug it in. We need to dothis in general termswithout getting boggeddown with the detail.
When you plug a USBdevice in, the hostbecomes aware (becauseof the pullup resistor onone data line), that adevice has been pluggedin.
The host now signals aUSB Reset to the device,in order that it should start
in a known state at the endof the reset. In this statethe device responds to thedefault address 0. Until thedevice has been reset thehost prevents data frombeing sent downstreamfrom the port. It will onlyreset one device at a time,so there is no danger of
Made Simple - Part 4 http://www.usbmadesimple.co.uk/u
18 28/04/2012 0
7/31/2019 USB Made Simple - Part 4
http://slidepdf.com/reader/full/usb-made-simple-part-4 2/18
two devices responding toaddress 0.
The host will now send arequest to endpoint 0 ofdevice address 0 to findout its maximum packet
size. It can discover this byusing the Get Descriptor(Device) command. Thisrequest is one which thedevice must respond toeven on address 0.
Typically (i.e. withWindows) the host willnow reset the deviceagain. It then sends a SetAddress request, with aunique address to thedevice at address 0. Afterthe request is completed,the device assumes thenew address. (And at thispoint the host is now freeto reset other recentlyplugged-in devices.)
Typically the host will nowbegin to quiz the device for
as many details as it feelsit needs. Some requestsinvolved here are:
Get DeviceDescriptorGet ConfigurationDescriptorGet String Descriptor
At the moment the device
is in an addressed butunconfigured state, and isonly allowed to respond tostandard requests.
Once the host feels it hasa clear enough picture ofwhat the device is, it willload a suitable devicedriver.
Made Simple - Part 4 http://www.usbmadesimple.co.uk/u
18 28/04/2012 0
7/31/2019 USB Made Simple - Part 4
http://slidepdf.com/reader/full/usb-made-simple-part-4 3/18
The device driver will thenselect a configuration forthe device, by sending aSet Configuration requestto the device.
The device is now in theconfigured state, and canstart working as the deviceit was designed to be.From now on it mayrespond to device specificrequests, in addition to thestandard requests which itmust continue to support.
We can now see that there
is a set of requests whicha device must respond to,and need to look at thedetailed means by whichthe requests are conveyed.
We saw in the last chapterthat data is transfered in 4different types of transfer:
Control TransfersInterrupt Transfers
Bulk TransfersIsochronousTransfers
The only transfer typeavailable before the devicehas been configured is theControl Transfer. The onlyendpoint available at thistime is the bidirectionalEndpoint 0.
Made Simple - Part 4 http://www.usbmadesimple.co.uk/u
18 28/04/2012 0
7/31/2019 USB Made Simple - Part 4
http://slidepdf.com/reader/full/usb-made-simple-part-4 4/18
Configurations,
Interfaces, and
Endpoints.
The device contains anumber of descriptors (asshown to the right) whichhelp to define what thedevice is capable of. Wewill examine thesedescriptors further downthe page. For the momentwe need to have an ideawhat the configurations,interfaces and endpointsare and how they fittogether.
A device can have more
than one configuration,though only one at a time,and to changeconfiguration the wholedevice would have to stopfunctioning. Differentconfigurations might beused, for example, tospecify different current
requirements, as thecurrent required is definedin the configurationdescriptor.
However it is not commonto have more than oneconfiguration. Windowsstandard drivers willalways select the firstconfiguration so there is
not a lot of point.
A device can have one ormore interfaces. Each
interface can have anumber of endpoints andrepresents a functionalunit belonging to aparticular class.
Made Simple - Part 4 http://www.usbmadesimple.co.uk/u
18 28/04/2012 0
7/31/2019 USB Made Simple - Part 4
http://slidepdf.com/reader/full/usb-made-simple-part-4 5/18
Each endpoint is a sourceor sink of data.
For example a VOIP phonemight have one audioclass interface with 2endpoints for transferringaudio in each direction,plus a HID interface with asingle IN interruptendpoint, for a built inkeypad.
It is also possible to havealternative versions of aninterface, and this is morecommon than multipleconfigurations. In the VOIP
phone example, the audioclass interface might offeran alternative with adifferent audio rate. It ispossible to switch aninterface to an alternatewhile the device remainsconfigured.
The SETUP
Packet
The Standard requests areall conveyed using controltransfers to endpoint 0.Remember that a control
transfer starts with aSETUP transaction whichconveys 8 bytes. These 8bytes define the requestfrom the host.
The structure ofbmRequestType makes iteasy to use it to switch onwhen your firmware is
Offset Field Size Value Description
0 bmRequestType 1 Bitmap
D7 Data direction
0 - Host-to-device1 - Device-to-host
D6:5 Type
0 = Standard1 = Class2 = Vendor3 = Reserved
D4:0 Recipient
0 = Device1 = Interface2 = Endpoint
3 = Other4-31 = Reserved
1 bRequest 1 Value Specific Request
2 wValue 2 Value Use varies according to request
4 wIndex 2Index orOffset
Use varies according to request
6 wLength 2 CountNumber of bytes to transfer if
there is a data stage
The meaning of the 8 bytes of the SETUP
transaction data, which are divided into five named
fields.
Made Simple - Part 4 http://www.usbmadesimple.co.uk/u
18 28/04/2012 0
7/31/2019 USB Made Simple - Part 4
http://slidepdf.com/reader/full/usb-made-simple-part-4 6/18
trying to interpret the setuprequest. Essentially, whenthe SETUP arrives, youneed to branch to thehandler for the particularrequest, so for examplebits 6:5 allow you to
distinguish the mandatorystandard commands, fromany class or vendorcommands you may haveimplemeted for youparticular device.
Switching on bit 7 allowsyou to deal with IN andOUT direction requests inseparate areas of thecode.
Here is a table which contains all the standard requests which a host can send.The first 5 columns are the SETUP transaction fields in order, and the lastcolumn describes any accompanying data stage data which will have the length
wLength .
bmRequestType bRequest wValue wIndex wLength Data
00000000b
00000001b00000010b
CLEAR_FEATURE
(1)
Feature
Selector
Zero
InterfaceEndpoint Zero None
10000000bGET_CONFIGURATION
(8)Zero Zero One
ConfigurationValue
10000000bGET_DESCRIPTOR
(6)
Descriptor Type(H) and
Descriptor Index(L)
Zero orLanguage
ID
DescriptorLength
Descriptor
10000001bGET_INTERFACE
(10)Zero Interface One
AlternateInterface
10000000b10000001b
10000010b
GET_STATUS
(0)Zero
ZeroInterface
Endpoint
Two
Device,Interface or
EndpointStatus
00000000bSET_ADDRESS
(5)Device Address Zero Zero None
00000000bSET_CONFIGURATION
(9)Configuration
ValueZero Zero None
00000000bSET_DESCRIPTOR
(7)
Descriptor Type(H) and
Descriptor Index(L)
Zero orLanguage
ID
DescriptorLength
Descriptor
Made Simple - Part 4 http://www.usbmadesimple.co.uk/u
18 28/04/2012 0
7/31/2019 USB Made Simple - Part 4
http://slidepdf.com/reader/full/usb-made-simple-part-4 7/18
7/31/2019 USB Made Simple - Part 4
http://slidepdf.com/reader/full/usb-made-simple-part-4 8/18
likely be the first onefetched by the host. Weshould point out someimportant features.
bLength and bDescriptorType
All descriptors start with asingle byte specifying thedescriptor's length, andthis is always followed by asingle byte defining thedescriptor type.
bcdUSB
The only valid versionnumbers are 0x0100
(USB1.0), 0x0110(USB1.1) and 0x0200(USB2.0). If you design anew device it should beidentified as USB2.0because that is the currentspecification.
bDeviceClass,
bDeviceSubClass and
bDeviceProtocol
This triplet of values isused to describe the classof the device in variousways as defined in thevarious class specificationdocuments from theUSB-IF.
idVendor, idProduct and
bcdDevice
The combination ofidVendor and idProduct(also known as the VIDand PID) must be uniquefor the device. This meansthat the VID you use mustbe one issued by theUSB-IF and which youhave the right to use. You
2 bcdUSB 2 BCD USB Spec release number
4 bDeviceClass 1 Class
Class code assigned byUSB-IF
00h means each interfacedefines its own class
FFh means vendor-defined c lass
Any other value must be aclass code
5 bDeviceSubClass 1 SubClass SubClass Code assignedby USB-IF
6 bDeviceProtocol 1 Protocol Protocol Code assigned
by USB-IF
7 bMaxPacketSize0 1 NumberMax packet size for
endpoint 0.Must be 8, 16, 32 or 64
8 idVendor 2 IDVendor ID - must be
obtained from USB-IF
10 idProduct 2 IDProduct ID - assigned by
the manufacturer
12 bcdDevice 2 BCDDevice release number in
binary coded decimal
14 iManufacturer 1 IndexIndex of string descriptordescribing manufacturer -
set to 0 if no string
15 iProduct 1 IndexIndex of string descriptor
describing product - set to0 if no string
16 iSerialNumber 1 Index
Index of string descriptordescribing device serialnumber - set to 0 if no
string
17 bNumConfigurations 1 NumberNumber of possible
configurations
Device Descriptor
Made Simple - Part 4 http://www.usbmadesimple.co.uk/u
18 28/04/2012 0
7/31/2019 USB Made Simple - Part 4
http://slidepdf.com/reader/full/usb-made-simple-part-4 9/18
can either buy a VID fromthe USB-IF, or you may beable to acquire the right touse a VID from anothermanufacturer together witha particular PID which theyhave issued to you. If you
use a VID/PID combinationwhich is already in usethen you will probablyhave major problems withyour product in the field.
SET_ADDRESS
After the host hasdetermined the max packetsize for endpoint 0, it is in
a position to begin normalcommunications with thedevice. As mentionedabove, there may be asecond reset from thehost. The host now needsto issue a SET_ADDRESSrequest to the device, sothat each device on thebus has a unique addressto respond to.
SET_ADDRESS is asimple, outward directionrequest in a controltransfer with no datastage. The only usefulinformation carried in theSETUP packet is therequired address.
When implementing this
request in firmware, youshould note the following.All other requests must beactioned before the statusstage in completed. But inthe case ofSET_ADDRESS, youshould not change the
device address until afterthe status stage. The
When are requests valid?
The device can be in one of three states whichdetermine whether a particular request is validat the time.
The states are:
Default
After reset but before receiving Set Address.
In the Default state, the only valid requests areGet Descriptor, and Set Address.
Addressed
After the device has been assigned an addressvia Set Address.
Now the device must recognise the followingadditional requests:
Set Configuration
Get Configuration
Set Feature
Clear Feature
Get Status
Set Descriptor (optional)
Configured
After the host has sent Set Configuration with anon-zero value, to select a configuration. Thedevice is now operational.
In the Configured state, only Set Address is nota valid request. Three further requests arerestricted to Configured state only:
Made Simple - Part 4 http://www.usbmadesimple.co.uk/u
18 28/04/2012 0
7/31/2019 USB Made Simple - Part 4
http://slidepdf.com/reader/full/usb-made-simple-part-4 10/18
status stage will notsucceed unless the deviceis still responding toaddress 0 while it is takingplace. The device then has2ms to get ready torespond to the new
address.
Get Interface
Set Interface
Synch Frame
Note that this was only a brief overview. The specificationgives more detailed information, which you should read
when implementing a USB device.
Other Information
Gathering
Commands
The host is likely to startusing theGET_DESCRIPTORrequest mentioned above,
to fetch other informationdescribing the device. Amajor piece of thisinformation is theconfiguration descriptor.
The actual descriptor which is fetchedby a GET_DESCRIPTOR request isdetermined by the high byte of thewValue word in the SETUP data.
So the request we call here 'GetDescriptor (Configuration)' is simply a
Get Descriptor request with the highbyte of wValue set to 2.
Made Simple - Part 4 http://www.usbmadesimple.co.uk/u
18 28/04/2012 0
7/31/2019 USB Made Simple - Part 4
http://slidepdf.com/reader/full/usb-made-simple-part-4 11/18
Get Descriptor
(Configuration)
The Get Descriptor(Configuration) warrantsspecial explanation,because the request
results in not just aConfiguration Descriptorbeing returned, but alsosome or all of a number ofother descriptors:
Interface DescriptorEndpoint DescriptorOTG DescriptorClass-specificDescriptors
Vendor-specificDescriptors
A Get ConfigurationDescriptor fetches thedescriptors for just oneconfiguration dependingon the descriptor index inwValue of the SETUPpacket. Most devices onlyhave one configuration,because built-in Windowsdrivers always select thefirst configuration.
The diagram oppositeshows a typical set ofDescriptors which isfetched. It starts with theconfiguration descriptor,and the vertical positionshows the correctsequence, with the
interfaces being dealt within turn, each one followedby its own endpoints.
The position of classdescriptors is defined inthe appropriate classspecification, and ofcourse vendors descriptorpositions would be up to
Made Simple - Part 4 http://www.usbmadesimple.co.uk/u
18 28/04/2012 0
7/31/2019 USB Made Simple - Part 4
http://slidepdf.com/reader/full/usb-made-simple-part-4 12/18
the vendor concerned.
An OTG descriptor positionis not defined but typicallyappears immediately afterthe configurationdescriptor.
Configuration Descriptor
The configurationdescriptor format is shownto the right.
The wTotalLegth value isimportant because it tells
the host how many bytesare contained in thisdescriptor and all thedescriptors which follow.
bNumInterfaces describeshow many interfaces thisconfiguration supports.
Offset Field Size Value Description
0 bLength 1 NumberSize of this descriptor inbytes
1 bDescriptorType 1 ConstantCONFIGURATIONdescriptor type (= 2)
2 wTotalLength 2 NumberTotal number of bytes in thisdescriptor and all thefollowing descriptors.
4 bNumInterfaces 1 NumberNumber of interfacessupported by thisconfiguration
5 bConfigurationValue 1 NumberValue used by SetConfiguration to select thisconfiguration
6 iConfiguration 1 Index
Index of string descriptor
describing configuration -set to 0 if no string
7 bmAttributes 1 Bitmap
D7: Must be set to 1D6: Self-poweredD5: Remote WakeupD4...D0: Set to 0
8 bMaxPower 1 mA
Maximum current drawn bydevice in this configuration.In units of 2mA. So 50means 100 mA.
Configuration Descriptor
Interface Descriptor
The interface descriptorformat is shown to theright.
bAlternateSetting needssome explanation. Aninterface can have morethan one variant, andthese variants can be
switched between, whileother interfaces are still inoperation.
For the first (and default)alternativebAlternateSetting is always0.
To have a second interface
Offset Field Size Value Description
0 bLength 1 NumberSize of this descriptor inbytes
1 bDescriptorType 1 ConstantINTERFACE descriptortype (= 4)
2 bInterfaceNumber 1 NumberNumber identifying thisinterface. Zero-basedvalue.
3 bAlternateSetting 1 NumberValue used to select thisalternate setting for thisinterface.
4 bNumEndpoints 1 NumberNumber of endpoints usedby this interface. Doesn'tinclude control endpoint 0.
5 bInterfaceClass 1 Class
Class code assigned byUSB-IF
00h is a reserved valueFFh means vendor-defined c lass
Any other value must be aclass code
6 bInterfaceSubClass 1 SubClassSubClass Code assignedby USB-IF
7 bInterfaceProtocol 1 Protocol Protocol Code assigned by
USB-IF
8 iInterface 1 IndexIndex of string descriptordescribing interface - set to0 if no string
Made Simple - Part 4 http://www.usbmadesimple.co.uk/u
18 28/04/2012 0
7/31/2019 USB Made Simple - Part 4
http://slidepdf.com/reader/full/usb-made-simple-part-4 13/18
variant, the defaultinterface descriptor wouldbe followed by its endpointdescriptors, which wouldthen be followed by thealternative interface
descriptor and then its
endpoint descriptors.
bInterfaceClass,
bInterfaceSubClass and
bInterfaceProtocol
By defining the class,subclass and protocol inthe interface, it is possibleto have interfaces withdifferent classes in the
same device. This isreferred to as a compositedevice.
Interface Descriptor
Endpoint Descriptor
The endpoint descriptorformat is shown to theright.
Offset Field Size Value Description
0 bLength 1 NumberSize of this descriptor inbytes
1 bDescriptorType 1 ConstantENDPOINT descriptor type(= 5)
2 bEndpointAddress 1 Endpoint
The address of thisendpoint within the device.
D7: Direction0 = OUT, 1 = IN
D6-D4: Set to 0
D3-D0: Endpoint number
3 bmAttributes 1 Bitmap
D1:0 Transfer Type
00 = Control01 = Isochronous10 = Bulk11 = Interrupt
The following only apply toisochronous endpoints.Else set to 0.
D3:2 Synchronisation Type
00 = No Synchronisation
01 = Asynchronous10 = Adaptive11 = Synchronous
D5:4 Usage Type
00 = Data endpoint01 = Feedback endpoint10 = Implicit feedback Dataendpoint11 = Reserved
D7:6 Reserved
Set to 0
4 wMaxPacketSize 2 Number
Maximum packet size thisendpoint can send orreceive when thisconfiguration is selected
Made Simple - Part 4 http://www.usbmadesimple.co.uk/u
18 28/04/2012 0
7/31/2019 USB Made Simple - Part 4
http://slidepdf.com/reader/full/usb-made-simple-part-4 14/18
6 bInterval 1 Number
Interval for polling endpointfor data transfers.Expressed in frames (ms)for low/full speed ormicroframes (125us) forhigh speed.
Endpoint Descriptor
Get Descriptor (String)
There are several stringswhich a host may request.The strings defined in thedevice descriptor are:
Manufacturer StringProduct StringSerial Number String
These strings are optional.If not supported, thecorresponding index in thedevice descriptor will be 0.Otherwise the host mayuse the specified index ina Get Descriptor (String)request to fetch thedescriptor.
Get Descriptor (String),with a descriptor index of 0in the low byte of wValue,is used to fetch a specialstring language descriptor.This contains a series of2-byte sized languagespecifiers. In theory, if thelanguage of your choice issupported in this list, youcan use the index to this
language ID to access thestring descriptors in thislanguage by specifyingthis in wIndex of the GetDescriptor (String) request.In practise, with Windows,you will have difficulties ifyou do not ensure that thefirst language specified isEnglish (US).
Offset Field Size Value Description
0 bLength 1 NumberSize of this descriptor in
bytes
1 bDescriptorType 1 ConstantSTRING descriptor type (=
3)
2 wLANGID[0] 2 Number LANGID Code 0
... ... ... ... ...
2 + x*2 wLANGID[x] 2 Number LANGID Code x
String Descriptor Zero(Specifies supported string languages)
Offset Field Size Value Description
0 bLength 1 NumberSize of this descriptor in
bytes
1 bDescriptorType 1 ConstantSTRING descriptor type (=
3)
2 bString 2 Number UNICODE encoded string
String Descriptor
Made Simple - Part 4 http://www.usbmadesimple.co.uk/u
18 28/04/2012 0
7/31/2019 USB Made Simple - Part 4
http://slidepdf.com/reader/full/usb-made-simple-part-4 15/18
SET_CONFIGURATION
When the host has got allthe information it requiresit loads a driver for thedevice based on theVID/PID combination in the
device descriptor, or on thestandard class definedthere or in an interfacedescriptor.
The driver may also ask forthe same or differentinformation using GetDescriptor requests.
Eventually it will decide to
configure the device usingtheSET_CONFIGURATIONrequest. Usually ( whenthere is one configuration)the Set Configurationrequest will have wValueset to 1, which will selectthe first configuration.
Set Configuration can alsobe used, with wValue set
to 0, to deconfigure thedevice.
A Configured Device
Once a device has been configured, it isallowed to respond to other transfer
types than Control transfers.
As we have seen, the other transfertypes are
Interrupt TransfersBulk TransfersIsochronous Transfers
As a result of the information in thedescriptors, the host will now know whatparticular transfers on which particularendpoints the device is prepared tosupport. There may now also be newclass or vendor-specific requests whichmay now be supported on the controlendpoint in addition to the standardrequests.
It is all these additional transfers whichperform the functionality that the devicewas designed for.
GET_CONFIGURATION
This request complimentsSet Configuration, andsimply allows the host todetermine whichconfiguration it previously
set.
SET_FEATURE
CLEAR_FEATURE
This pair of requests isused to control a smallnumber of on-off featureson a device, an interface oran endpoint.
Feature Selector Recipient Value
ENDPOINT_HALT Endpoint 0
DEVICE_REMOTE_WAKEUP Device 1
TEST_MODE Device 2
B_HNP_ENABLE Device 3
A_HNP_SUPPORT Device 4
A_ALT_HNP_SUPPORT Device 5
Made Simple - Part 4 http://www.usbmadesimple.co.uk/u
18 28/04/2012 0
7/31/2019 USB Made Simple - Part 4
http://slidepdf.com/reader/full/usb-made-simple-part-4 16/18
A device has 5 possiblefeatures, an endpoint hasone, and an interfaceactually has none at all.
The greyed out featuresshown in the table onlyapply to OTG devices.
ENDPOINT_HALT
Setting this feature willcause an endpoint toSTALL any IN or OUTtransactions.
DEVICE_REMOTE_WAKEUP
Setting this feature allowsa device which is then
suspended to use resumesignalling to gain thehost's attention.
Table of wValues used in Set Feature and Clear
Feature requests.
GET_STATUS
This request is used tofetch status bits from adevice, an interface or anendpoint. In each case therequest fetches 16 bits (2bytes). The tables to theright show the status bitswhich are currentlyimplemented.
Note that Remote Wakeup
and Halt status bits canboth be controlled by thehost using Set.ClearFeature requests, but theSelf-powered bit is onlycontrolled by the device.
Status Bit Purpose Comment
D0 Self PoweredSet to 1 by the devicewhen it is self-powered
D1RemoteWakeup
Set to 1 if the device has
been enabled to signalremote wakeup.
D2 - D15 reserved Must be set to 0
Device Status Bits
Status Bit Purpose Comment
D0 - D15 reserved Must be set to 0
Interface Status Bits
Status Bit Purpose Comment
D0 HaltSet to 1 when endpoint ishalted
D1 - D15 reserved Must be set to 0
Endpoint Status Bits
Made Simple - Part 4 http://www.usbmadesimple.co.uk/u
18 28/04/2012 0
7/31/2019 USB Made Simple - Part 4
http://slidepdf.com/reader/full/usb-made-simple-part-4 17/18
SET_INTERFACE
GET_INTERFACE
Once a device has beenconfigured the host mayuse Set Interface to selectan alternative interface to a
particular default interface.It can use the GetInterface to determinewhich interface alternativeit previous set for aparticular interface.
SYNCH_FRAME
This is used with someisochronous transfer wherethe transfer size varies withthe frame. See USB 2.0specification for moredetails.
SET_DESCRIPTOR
This Standard request isoptional and not oftenused. It allows the host to
specify a new set of valuesfor a given descriptor. It ishard to imagine when thismight be of value.
Summary
We have looked at the setof standard requests whicha device must support to
become operational.
Coming up...
Next we will examine thecomplete enumeration andstart of operation of aspecific device.
Forward
Made Simple - Part 4 http://www.usbmadesimple.co.uk/u
18 28/04/2012 0
7/31/2019 USB Made Simple - Part 4
http://slidepdf.com/reader/full/usb-made-simple-part-4 18/18
Copyright © 2006-2008 MQP Electronics Ltd
ADVERTISEMENT
Packet-Master USB Bus Analysers and Generators from MQP
Electronics Special Offer
Radically cut
developmenttimeIntuitivegraphicalinterfaceDetailed timinginformationFull analysis ofall standardeventsResults can be
printedOptional classanalysismodules
Click for moreinformation
Made Simple - Part 4 http://www.usbmadesimple.co.uk/u