Home
µC/USB-Device User`s Manual
Contents
1. cesceeseeeeeeeeeeeeeeeeeeeeeeeneeeeneeeeeeeenees 135 Chemie seed ERENNERT 136 eet ege eege 136 e e 142 eu UU TE de DE 143 General Configuration cccccceessenceeeeeseeeeeeeseeeeeeeeeseeeneeeeeseeneeeesseeeneeeenss 143 Class Instance Configuration NEEN EEN 144 Class Instance COMMUNICATION ccceceeeeeeseeeeee eee eeee eee eeeeeeeseeeneeees 150 Synchronous COMMUNICATION 2 ecccceeeseeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeenneeeeees 150 Asynchronous Communication ecceeceeeeeeeeeeeeeeeeeneneeeeeeeeenens 152 Using the Demo Application ccscesseeeeeee cece REENEN 154 Configuring PC and Device Applications REENEN 154 Running the Demo Application een 156 Porting the HID Class to a RTOS ecssceseeeeeeeeeeeeeeeeeeeesneeeeeeeeeeeenens 160 Periodic Input Reports Task c cceccessesseeeeeeeeeeeeeeeeeeeeeeenseaeeeeeeeeeenees 161 Mass Storage Class cccccccesseenceeeeseeeeeeeeesneeeeeeeeeeeeeeeeeseeeseeeeeseaeseeeeeenes 165 COVEN ET erg EEN 166 Mass Storage Class Protocol ccecccccsesenceeeeseeeeeeeeeeeeeeeeeseseeneeeeeeeeees 166 lee e 167 Mass Storage Class Requests esse seeeeeeeeeeeeeeeeeeeeeeessnaneeeeeeeeeeees 167 Small Computer System Interface SCSI een 168 ere 169 MSC Archit Gture ease taaa aaar aa Eae outta ed deere 169 SCSI Command EE 170 Storage Layer and Storage Medium ceceeeeeeeeeeeeeeeeeeeeeeeeeeeeeeees 171 RTOS Layer asasinii aiaa aaaea nana aa aE AAEN RR
2. cfg_fs_nbr USBD_CfgAdd dev_nbr 4 USBD_DEV_ATTRIB SELF POWERED 100u USBD_DEV_SPD_ FULL FS configuration amp err if err USBD ERR NONE Handle error return DEF_FAIL if APP_CFG USBD_XXXX_EN DEF_ENABLED 5 ok App USBD_XXXX_Init dev_nbr cfg_hs_nbr cfg_fs_nbr if ok DEF_OK Handle error return DEF_FAIL endif if APP_CFG USBD VON EN DEF ENABLED 5 endif USBD_DevStart dev_nbr amp err 6 void ok return DEF_OK Listing 2 5 App_USBD_Init Function 41 Chapter 2 L2 5 1 L2 5 2 L2 5 3 L2 5 4 L2 5 5 L2 5 6 42 USBD_ Init initializes the USB device stack This must be the first USB function called by your application s initialization code If wC USB Device is used with pC OS II or III OSInit must be called prior to USBD_Init in order to intialize the kernel services USBD_DevAdd creates and adds a USB device instance A given USB device instance is associated with a single USB device controller wC USB Device can support multiple USB device controllers concurrently If your target supports multiple controllers you can create multiple USB device instances for them The function USBD_DevAdd returns a device instance number this number is used as a parameter for all subsequent operations Create and add a high speed configuration to your device USBD_CfgAdd creates and adds a configur
3. eecccceeeceeeeeceeeseeeeeeeeeeseaeeeeeeeeeseseeeesneeeeeeenes 485 USBD_Vendor_WrASYIC cceeccecceseeeeeeeeeeeeeeeeeeeneeseeeeseeeeeeeeseeneeeeeseeaes 487 USBD_Vendor_IntrRd c cccccesseeeceeeeseeeeeeeeeeaeeeeeeseaeeeeenseaaeeeeeeeeees 489 USBD_Vendor_IntrW 2 ecceeceeeceeeeeeeeeeeeeeeeeeeeeeeeeeeeesseaeneeeeeeeenees 491 USBD_Vendor_IntrROASYINC eccceeeceeeseeeeeeeeeeeeeeeeeeeeeeseseeeeseeeeeeeenes 493 USBD_Vendor_IntrWrASyinC ccecceseeeeeeeeeeeceeeeeeeeeeeeeeesseaeeeeeeeeeenees 495 USBDev API FUNCTIONS aa aaa aeae EENENE Eege ENEE 497 USBDev_GetNbrDev 0 00 cccccceeceseeeeceeeeseeeeeeeesseaeeeeeeseaaeeesnseeaeeeeeneees 497 USBDevi Open siennes niee iae AAA Ee 499 USBDevV Close ease nananahan aaa aaaea aaa aaia 500 USBDev_GetNbrAltSetting ceceeecceceseeeeeeeeeeeeeeeesseeeeeeeesseenseeeesenes 501 USBDev_GetNbrAssociatedlF 2 seeseeeceeeeeeeeeeeeeeesseeeeeeeeeeeeeees 503 USBDev_SetAltSetting ceseeccccceseeeeceeeeeeeeeeeeeeseeneeeeeseeeeeeeesseeeeeeeeeeees 504 USBDev_GetCurAltSetting csssccccsccceseeeeseeeeessseeseeeeeeeeseesesneeeeeeeees 506 USBDev_ISHighSpeed 2 cccccceeceseeeeeeeeeeeceeeeeeeeeeeeeeeseneeeeeeeeeeeeens 508 USBDev_BulkIn_Open ccccececeeeeeeeeeeeeeeeeeeeeeeeseseeessnaeeeeeeeeeenens 509 USBDev_BulkOut_Open ccccceeceeeeeeeeeseeeeeeeeeeeeeseeeeeseeeaneeeeeeeeeees 510 USBDev_Intrin_Open eceeccceces
4. Host Operating Systems The major host operating systems OS such as Microsoft Windows Apple Mac OS and Linux recognize a wide range of USB devices belonging to standard classes defined by the USB Implementers Forum Upon connection of the USB device any host operating systems perform the following general steps 1 Enumerating the USB device to learn about its characteristics 2 Loading a proper driver according to its characteristics analysis in order to manage the device 3 Communicating with the device Step 2 where a driver is loaded to handle the device is performed differently by each major host operating system Usually a native driver provided by the operating system manages a device complying to a standard class for instance Audio HID MSC Video etc In this case the native driver loading is transparent to you In general the OS won t ask you for specific actions during the driver loading process On the other hand a vendor specific device requires a vendor specific driver provided by the device manufacturer Vendor specific devices don t fit into any standard class or don t use the standard protocols for an existing standard class In this situation the OS may explicitly ask your intervention during the driver loading process During step 3 your application may have to find the USB device attached to the OS before communication with it Each major OS uses a different method to allow you to find a specific
5. Initializes MSC OS interface This function will create both signals semaphores for communication and enumeration processes Furthermore this function will create the MSC task used for the MSC protocol USBD_MSC_OS_CommSignalPost Posts a semaphore used for MSC communication USBD_MSC_OS_CommSignalPend Waits on a semaphore to become available for MSC communication USBD_MSC_OS_CommSignalDel Deletes a semaphore if no tasks are waiting for it for MSC communication USBD_MSC_OS EnumSignalPost Posts a semaphore used for MSC enumeration process USBD_MSC_OS EnumSignalPend Waits for a semaphore to become available for MSC enumeration process Table 10 11 RTOS API Functions 181 Chapter 10 182 Chapter 17 Personal Healthcare Device Class This section describes the Personal Healthcare Device Class PHDC supported by pEC USB Device The implementation offered refers to the following USB IF specification E USB Device Class Definition for Personal Healthcare Devices release 1 0 Nov 8 2007 PHDC allows you to build USB devices that are meant to be used to monitor and improve personal healthcare Lots of modern personal healthcare devices have arrived on the market in recent years Glucose meter pulse oximeter and blood pressure monitor are some examples A characteristic of these devices is that they can be connected to a computer for playback live monitoring or configuration
6. Set or enable a specific feature Set the device address for all future device accesses Return the specified descriptor if the descriptor exists Update existing descriptors or new descriptors may be added Return the current device configuration value Set the device configuration Return the selected alternate setting for the specified interface Select an alternate setting for the specified interface Set and then report an endpoint s synchronization frame Variable representing wValue of setup packet Variable representing wIndex of setup packet Pointer to transmit or receive buffer for data phase of control transfer Length of transmit or receive buffer p err Pointer to variable that will receive the return error code from this function ERROR_SUCCESS ERROR INVALID HANDLE ERROR HOT ENOUGH MEMORY ERROR_GEN FATLURE RETURNED VALUE None CALLERS Application NOTES WARNINGS The value of w_value and w_index arguments vary according to the specific request defined by b request argument The following code shows an example using USBDev_CtrlReq to send SET_INTERFACE request DWORD erry L USBDev_CtrlReq dev_handle USB_DIR_HOST_TO DEVICE SET_INTERFACE il ifs 0 ifs 0 fe 0 amp err if err ERROR SUCCESS Select alternate setting 1 for default interface USB_REQUEST_TYPE STD USB_RECIPIENT_IF Alternate setting 1 Interface 0 inside active config
7. 443 Appendix F p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_ALLOC RETURNED VALUE Class instance number if NO error s USBD_CLASS NBR_NONE otherwise CALLERS Application NOTES WARNINGS None 444 F 1 3 USBD_PHDC_CfgAdd Add a PHDC instance into the specified configuration The PHDC instance was previously created by the function USBD_PHDC_Add FILES usbd_phdc h usbd_phdc c PROTOTYPE void USBD_PHDC CfgAdd CPU_INTO8U class _nbr CPU_INTO8U dev_nbr CPU_INTO8U cfg_nbr USBD_ERR p err ARGUMENTS class_nbr PHDC instance number dev_nbr Device number cfg_nbr Configuration index to add PHDC instance to p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_INVALID ARG USBD_ERR_ALLOC USBD_ERR NULL PTR USBD_ERR_ DEV INVALID NBR USBD_ERR DEV INVALID STATE USBD_ERR CFG INVALID NBR USBD_ERR_IF ALLOC USBD_ERR_IF ALT ALLOC USBD_ERR_IF INVALID NBR USBD_ERR_EP NONE AVAIL USBD_ERR_EP ALLOC 445 Appendix F RETURNED VALUE None CALLERS Application NOTES WARNINGS USBD_PHDC CfgAdd basically adds an Interface descriptor and its associated Endpoint descriptor s to the Configuration descriptor One call to USBD_PHDC_CfgAdd builds the Configuration descriptor corresponding to a PHDC device with the following format Configuration Descriptor
8. 8 gt Periodic input reports task 3 P 4 Update idle duration count Input Report or 5 Send input report data Internal data buffer 6 Application task New Input Report Figure 9 7 Periodic Input Reports Task The device receives a SET_IDLE request This request specifies an idle duration for a given report ID Refer to Device Class Definition for Human Interface Devices HID Version 1 11 section 7 2 4 for more details about the SET_IDLE request A report ID allows you to distinguish among the different types of reports sent over the same endpoint A report ID structure allocated during the HID class initialization phase is updated with the idle duration An idle duration counter is initialized with the idle duration value Then the report ID structure is inserted at the end of a linked list containing input reports ID structures The idle duration value is expressed in 4 ms unit which gives a range of 4 to 1020 ms If the idle duration is less than the interrupt IN endpoint polling interval the reports are generated at the polling interval Every 4 ms the periodic input report task browses the input reports ID list For each input report ID the task performs one of two possible operations The task period matches the 4 ms unit used for the idle duration If no SET_IDLE F9 7 4 F9 7 5 F9 7 6 Periodic Input Reports Task requests have been sent
9. ARGUMENTS class_nbr isoc_en protocol CDC instance number Data interface isochronous enable DEF _ ENABLED DEF DISABLED Data interface protocol code USBD_CDC_DATA PROTOCOL NONE USBD_CDC_DATA PROTOCOL NTB USBD_CDC_DATA PROTOCOL PHY USBD_CDC_DATA PROTOCOL HDLC USBD_CDC_DATA PROTOCOL TRANS USBD_CDC_DATA PROTOCOL _0921M USBD_CDC_ DATA PROTOCOL Q921 USBD_CDC_DATA PROTOCOL Q921T USBD_CDC_DATA PROTOCOL COMPRESS USBD_CDC_DATA PROTOCOL 09131 Data interface uses isochronous endpoints Data interface uses bulk endpoints No class specific protocol required Network Transfer Block Physical interface protocol for ISDN BRI HDLC Transparent Management protocol for Q 921 data link protocol Data link protocol for Q 921 TEI multiplexor for Q 921 data link protocol Data compression procedures Euro ISDN protocol control 361 Appendix C USBD_CDC_DATA PROTOCOL V24 V 24 rate adaptation to ISDN USBD_CDC_DATA PROTOCOL CAPI CAPI Commands USBD_CDC_DATA PROTOCOL HOST Host based driver USBD_CDC_DATA PROTOCOL CDC The protocol s are described using a Protocol Unit Function Communication Class Interface USBD_CDC_DATA PROTOCOL VENDOR Vendor specific CDC data interface class protocol codes are defined in the Universal Serial Bus Class Definitions for Communication Devices Revision 2 1 Table 7 p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_
10. ARGUMENTS class_nbr Class instance number p_ but buf_len async _fnct p async arg p err Pointer to receive buffer Receive buffer length in octets Receive callback Additional argument provided by application for receive callback Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_ NULL PTR USBD_ERR_INVALID ARG USBD_ERR_ INVALID CLASS STATE USBD_ERR_ DEV INVALID NBR USBD_ERR_EP INVALID NBR 485 Appendix G USBD_ERR DEV INVALID STATE USBD_ERR_EP INVALID TYPE USBD_ERR_ EP INVALID STATE RETURNED VALUE None CALLERS Application NOTES WARNINGS None 486 G 1 8 USBD_ Vendor_WrAsync Send data to host through Bulk IN endpoint This function is non blocking It returns immediately after transfer preparation Upon transfer completion a callback provided by the application will be called to finalize the transfer FILES usbd_vendor c PROTOTYPE void USBD Vendor WrAsync CPU_INT08U class_nbr void p buf CPU_INT32U buf_len USBD_VENDOR_ASYNC_FNCT async _fnct void p async_arg CPU_BOOLEAN end USBD_ERR p err ARGUMENTS class nr Class instance number p_buf Pointer to transmit buffer buf_len Transmit buffer length in octets async _fnct Transmit callback p_async_arg Additional argument provided by application for transmit callback end End of transfer flag p_err Pointer to variable that will receive the retur
11. Building the Sample Application APP_CFG USBD_EN enables or disables the USB application initialization code These defines relate to the pC USB Device OS port The pC USB Device core requires only one task to manage control requests and asynchronous transfers and a second optional task to output trace events Gf trace capability is enabled To properly set the priority of the core and debug tasks refer to section 5 2 1 Task Priorities on page 69 This define enables the USB class specific demo The token XXXX in the constant APP_CFG_USBD_XXXX_EN is the name of the class and can be replaced by CDC HID MSC PHDC or VENDOR Configure the desired size of the heap memory Heap memory is only used for uC USB Device drivers that use internal buffers and DMA descriptors which are allocated at run time Refer to the pC LIB documentation for more details on the other pC LIB constants Most Micrium examples contain application trace macros to output human readable debugging information Two levels of tracing are enabled INFO and DBG INFO traces high level operations and DBG traces high level operations and return errors Application level tracing is different from uC USB Device tracing refer to Chapter 13 Debug and Trace on page 231 for more details Define the application trace level Specify which function should be used to redirect the output of human readable application tracing You can select the standard output via
12. CALLERS Application NOTES WARNINGS This function is non blocking and returns immediately after transfer preparation Upon transfer completion the callback provided is called to notify the application 401 Appendix D D 2 HID OS FUNCTIONS D 2 1 USBD_HID_OS Init Initialize HID OS interface FILES usbd_hid_os c PROTOTYPE void USBD HID OS Init USBD ERR p err ARGUMENTS p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE OS error code s relevant to failure s CALLERS USBD HID Init IMPLEMENTATION GUIDELINES The USBD_HID Init function is called only once by the HID class It usually performs the following operations E For each class instance up to the maximum number of HID class instances defined by the constant USBD_HID CFG MAX NBR DEV create all the required semaphores If the any semaphore creation fails set p err to USBD_ERR_OS SIGNAL CREATE and return E Create a task used to manage periodic Input reports If the task creation fails set p_err to USBD_ERR_OS INIT FAIL and return E Set p_err to USBD_ERR_NONE if the initialization proceeded as expected 402 D 2 2 USBD_HID_OS InputLock Lock class input report FILES usbd_hid_os c PROTOTYPE void USBD HID OS InputLock CPU_INTO8U class_nbr USBD_ERR p err ARGUMENTS class nbr_ Class instance number p err Pointer to variable that will receive the return err
13. CPU_LINTO8U ep ix CPU_LINT16U timeout ms USBD_ERR p err ARGUMENTS dev_nbr Device number ep_ix Endpoint index timeout_ms Timeout in milliseconds p err Pointer to variable that will receive the return error code from this function RETURNED VALUE None CALLERS Endpoints Rx Tx functions IMPLEMENTATION GUIDELINES A call to this function should pend on the signal semaphore associated to the specified endpoint Table A 1 describes the error codes that should be assigned to p_err depending on the operation result 305 Appendix A Operation result Error code No error USBD_ERR_NONE Pend timeout USBD_ERR_OS_TIMEOUT Pend aborted USBD_ERR_OS_ABORT Pend failed for any other reason USBD_ERR_OS FAIL Table A 1 p_err assignment in function of operation result 306 A 5 7 USBD_OS EP _SignalAbort Aborts any wait operation on signal semaphore FILES usbd_internal h usbd_os c PROTOTYPE void USBD_OS EP SignalAbort CPU_INTO8U dev_nbr CPU_LINTO8U ep ix USBD_ERR p err ARGUMENTS dev_nbr Device number ep_ix Endpoint index p err Pointer to variable that will receive the return error code from this function RETURNED VALUE None CALLERS Endpoints abort functions IMPLEMENTATION GUIDELINES This function should abort all pend operations performed on the signal semaphore associated to the specified endpoint If any error happen USBD_ERR_OS FAIL should be ass
14. DEF_NO otherwise CALLERS Application NOTES WARNINGS This API may be called several times This allows to create multiple instances of the HID class into different USB device configurations 392 D 1 4 USBD_HID_IsConn This function returns the HID class connection state FILES usbd_hid c PROTOTYPE CPU_BOOLEAN USBD HID IsConn CPU_INTO8U class _nbr ARGUMENTS class nbr_ Class instance number RETURNED VALUE DEF_YES if class is connected DEF MO otherwise CALLERS Application NOTES WARNINGS The class connected state also implies the USB device is in configured state 393 Appendix D D 1 5 USBD_HID_Rd This function receives data from the host through an interrupt OUT endpoint FILES usbd_hid c PROTOTYPE CPU_INT32U USBD_HID Rd CPU_INTO8U class_nbr void p buf CPU_INT32U buf_len CPU_INT16U timeout USBD_ERR p err ARGUMENTS class nr Class instance number p buf Pointer to receive buffer buf len Receive buffer length in octets timeout Timeout in milliseconds p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_NULL PTR USBD_ERR_INVALID ARG USBD_ERR_ INVALID CLASS STATE USBD_ERR_ DEV INVALID NBR USBD_ERR_ EP INVALID NBR USBD_ERR DEV INVALID STATE USBD_ERR_EP INVALID TYPE 394 RETURNED VALUE Number of octets received if NO error s 0 otherwise CALLERS Application NOTES WAR
15. Data Stall _ a N Bulk IN Stall Cleared BULK INSTALL H ___ lt a Transfer Valid y S 4 N Ly CSW E La K y Receive Next CBW SD Figure 10 3 MSC State Machine Upon detecting that the MSC device is connected the device will enter an infinite loop waiting to receive the first CBW from the host Depending on the command received the device will either enter the data phase or transmit CSW phase In the event of any stall conditions in the data phase the host must clear the respective endpoint before transitioning to the CSW phase If an invalid CBW is received from the host the device shall enter reset recovery state where both endpoints are stalled to complete the full reset with the host issuing the Bulk Only Mass Storage Reset Class Request After a successful CSW phase or a reset recovery the task will return to receive the next CBW command If at any stage the device is disconnected from the host the state machine will transition to the None state 172 Configuration 10 4 CONFIGURATION 10 4 1 GENERAL CONFIGURATION There are various configuration constants necessary to customize the MSC device These constants are located in the usbd_cfg h file Table 10 4 shows a description of each constant Constant Description USBD_MSC_CFG MAX NBR_DEV Configures the maximum number of class instances Unless you plan having multiple configuration or interfaces using different class instances this
16. USBD_ERR p err ARGUMENTS line _state_interval Polling interval in frames or microframes for line state notification p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_ALLOC USBD_ERR_INVALID ARG RETURNED VALUE CDC ACM serial emulation subclass instance number if no errors USBD_ACM SERIAL NBR_NONE otherwise CALLERS Application NOTES WARNINGS None 370 C 2 3 USBD_ACM_ SerialCfgAdd Add CDC ACM subclass instance to USB device configuration FILES usbd_acm_serial h usbd_acm_serial c PROTOTYPE CPU_BOOLEAN USBD ACM SerialCfgAdd CPU_INTO8U subclass _nbr CPU_INTO8U dev_nbr CPU_INTO8U cfg_nbr USBD_ERR p err ARGUMENTS subclass nbr CDC ACM serial emulation subclass instance number dev_nbr Device number cfg_nbr Configuration number p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_INVALID ARG USBD_ERR_ALLOC USBD_ERR_ INVALID CLASS STATE USBD_ERR_ DEV INVALID NBR USBD_ERR CFG INVALID NBR USBD_ERR_IF ALLOC USBD_ERR_IF ALT ALLOC USBD_ERR_EP NONE AVAIL USBD_ERR_EP ALLOC 371 Appendix C RETURNED VALUE DEF_OK If CDC ACM serial emulation subclass instance was added to device configuration successfully DEF_FAIL Otherwise CALLERS Application NOTES WARNINGS None 372 C 2 4 USBD_ACM_ SeriallsConn Determine if CDC ACM serial emulat
17. USBD_ERR err CPU_INT08U class_nbr USBD_Vemdor_Init amp err 2 if err USBD_ERR_NONE Handle the error ii 3 class_nbr USBD_Vendor_Add DEF_FALSE Ou App_USBD_Vendor_VendorReq 1 amp err if err USBD_ERR_NONE Handle the error if cfg_hs USBD_CFG_NBR_NONE USBD_Vendor_CfgAdd class_nbr dev_nbr cfg_hs amp err 4 if err USBD_ERR_NONE Handle the error if cfg_fs USBD_CFG_NBR_NONE USBD_Vendor_CfgAdd class_nbr dev_nbr cfg fs amp err 5 if err USBD_ERR_NONE Handle the error Listing 12 1 Vendor Class Initialization Example 112 101 Provide an application callback for vendor requests decoding L12 1 2 Initialize Vendor internal structures variables 209 Chapter 12 L12 1 3 Create a new Vendor class instance In this example DEF_FALSE indicates that no interrupt endpoints are used Hence the polling interval is set to 0 The callback App USBD Vendor VendorRegq is passed to the function L12 1 4 Check if the high speed configuration is active and proceed to add the Vendor instance previously created to this configuration 112 16 Check if the full speed configuration is active and proceed to add the Vendor instance to this configuration Code Listing 12 1 also illustrates an example of multiple configurations The functions USBD Vendor Add and USBD Vendor _CfgAdd allow you to create multiple c
18. br Computer welt Search Computer D Organize v AutoPlay Eject Properties System properties Uninstall or change a program Map network drive SR EN gt 3 Favorites 4 Hard Disk Drives 2 gt a Libraries Go Ke a H ACER C DATA D b lomegroup 4 Devices with Removable Storage 2 gt pli Computer b Ga Network DVDRW Removable Drive E Disk L Removable Disk L Space used ___ Total size 1 2 MB Removable Disk Space free 1 2MB File system FAT32 Figure 10 5 MSC Device on Windows 7 Explorer 179 Chapter 10 When you open the removable disk if it is the first time the MSC device is connected to the PC and is not formatted Windows will ask to format it to handle files on the mass storage When formatting choose the File System you want In embedded systems the most widespread file system is the FAT If the mass storage device is a volatile memory such as a SDRAM every time the target board is switched off the data of the memory is lost and so is the file system data information Hence the next time the target is switched on the SDRAM is blank and reconnecting the mass storage to the PC you will have to format again the mass storage device Once the device is correctly formatted you are ready to test the MSC demo Below are a few examples of what you can do E You can create one or more text files E You can write data in these files E You can open them to read the content of the fil
19. cfg_nbr EE if_alt_nbr dir_in max _pkt_len p err if_alt_nbr Interface alternate setting number dir mn Endpoint direction DEF_YES DEF_NO IN direction OUT direction max pkt_len Endpoint maximum packet length see Note 1 265 Appendix A p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_INVALID ARG USBD_ERR_ DEV INVALID NBR USBD_ERR CFG INVALID NBR USBD_ERR_IF INVALID NBR USBD_ERR_EP NONE AVAIL USBD_ERR_EP ALLOC RETURNED VALUE Endpoint address if no error s USBD_EP ADDR NONE otherwise CALLERS USB device class drivers NOTES WARNINGS If the max_pkt_len argument is 0 the stack will allocate the first available bulk endpoint regardless its maximum packet size 266 A 4 4 USBD_BulkRx Receives data on bulk OUT endpoint FILES usbd_core h usbd_ep c PROTOTYPE CPU_INT32U USBD_BulkRx CPU_INTO8U dev_nbr CPU _INT08U ep addr void p buf CPU_INT32U buf len CPU_INT16U timeout ms USBD_ERR p err ARGUMENTS dev_nbr Device number ep_addr Endpoint address p buf Pointer to destination buffer to receive data buf len Number of octets to receive timeout ms Timeout in milliseconds p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_DEV_INVALID NBR USBD_ERR_DEVINVALID STATE USBD_ERR_ EP INVALID ADDR USBD_ERR_EP INVALID STATE USBD_ERR_
20. 127 385 USBD_ACM_SerialRX A 128 374 USBD_ACM_SerialTx cecceeeceseeeeeeeeeeeeeeeeeteees 128 376 usbd bep controllerz C A 58 USBD BSP Conn ere dereen 351 USBD_BSP_DisConn inisiasie eaaa 352 USBD BSP lait EENS 350 USBD TT E 265 USBD_BUIKRX 89 90 267 USBD_BulkRxAsync ceceeceeeeeeeeeeeeeeeeeeeeeaes 91 269 USBDBUIKTX shectecddecanscsincauevstavenreaaccnccsccectececieagues USBD_BulkTxAsync USBD CDC AQA TE USBD_CDC_CfgAdd A 358 USBD_CDC_CFG_MAX_NBR_CFG eee 76 120 USBD_CDC_CFG_MAX_NBR_DATA_IF aeee 120 USBD_CDC_CFG_MAX_NBR_DEV 76 120 123 USBD_CDC_DatalF_Add ccecceeeeeseeeeeeeeeeeeeeeeeeeee 361 USBD_CDC_DataRX AA 363 USBD_CDC_DataTx USBD CDG Inte USBD_CDC_IsConn USBD_CDC_Notify i USDA re EE usbd_cfg h eee USBD ee EE USBD_CFG_DBG_TRACE_EN A 68 232 USBD_CFG_DBG_TRACE_NBR_EVENTS 68 232 234 USBD_CFG_MAX_NBR_CFG eee 66 72 74 76 USPBD CEG MAN NR D N AAA 66 USBD_CFG_MAX_NBR_EP_DESC 67 72 74 76 USBD_CFG_MAX_NBR_EP_OPEN 67 72 74 76 USBD_CFG_MAX_NBR IEN 66 72 74 76 USBD_CFG_MAX_NBR_IF_ALT USBD_CFG_MAX_NBR_IF_GRP 67 72 74 76 67 72 74 76 USBD_CFG_MAX_NBR_STR 67 USBD_CFG_OPTIMIZE_SPD 0 eee eee 66 USBD_CfgOtherSpeed AAA 104 USBD_CLASS_DRV 0 0 ect eee teeeeeeeenee 111 Index usbd_core c usbd_core h USBD_CoreTaskHandler USBD_CtrlIR
21. A default value can be 256 Table 12 6 Device Application Constants Configuration APP CFG USBD_ VENDOR ECHO SYNC EN and APP CFG USBD VENDOR ECHO ASYNC EN can be set to DEF_ENABLED at the same time The vendor device created will be a composite device formed with two vendor interfaces One will represent the Echo Sync demo and the other the Echo Async demo On the Windows side the demo application file app vendor _echo c is part of a Visual Studio solution located in this folder Micrium Software uC USB Device V4 App Host 0S Windows Vendor Visual Studio 2010 app vendor _echo c allows you to test E One single device That is Echo Sync or Async demo is enabled on the device side E One composite device That is Echo Sync and Async demos are both enabled on the device side P Multiple devices single or composite devices 221 Chapter 12 app _vendor_echo c contains some constants to customize the demo Constant Description APP_CFG RX ASYNC_EN Enables or disables the use of the asynchronous API for IN pipe The possible values are TRUE or FALSE APP MAN NBR_VENDOR_DEV Defines the maximum number of connected vendor devices supported by the demo Table 12 7 Windows Application Constants Configuration The constants configuration for the Windows application are independent from the device application constants configuration presented in Table 12 6 12 4 2 EDITING AN INF FILE An INF file contains directives
22. Add a logical unit number to the MSC interface by specifying the type and volume Note that in this example the lt device_driver_name gt string is ram and lt ogical_unit_number gt string is 0 10 5 USING THE DEMO APPLICATION The MSC demo consists of two parts E Any file explorer application Windows Linux Mac from a USB host For instance in Windows mass storage devices appear as drives in My Computer From Windows Explorer users can copy move and delete files in the devices E The USB Device application on the target board which responds to the request of the host 176 Using the Demo Application uC USB Device allows the explorer application to access a MSC device such as a NAND NOR Flash memory RAM disk Compact Flash Secure Digital etc Once the device is configured for MSC and is connected to the PC host the operating system will try to load the necessary drivers to manage the communication with the MSC device For example Windows loads the built in drivers disk sys and PartMgrsys You will be able to interact with the device through the explorer application to validate the device stack with MSC 10 5 1 USB DEVICE APPLICATION On the target side the user configures the application through the app_cfg nh file Table 10 7 lists a few preprocessor constants that must be defined Preprocessor Constants Description Default Value APP_CFG USBD_EN Enables uC USB Device in the DEF_ENABL
23. B 2 2 USBD_BSP_Conn Enable USB controller connection dependencies FILES Every device driver s usbd_bsp c PROTOTYPE static void USBD_BSP_Conn void ARGUMENTS None RETURNED VALUE None CALLERS USBD_DrvStart NOTES WARNINGS None 351 Appendix B B 2 3 USBD_BSP_Disconn Disable USB controller connection dependencies FILES Every device driver s usbd_bsp c PROTOTYPE static void USBD_BSP_Disconn void ARGUMENTS None RETURNED VALUE None CALLERS USBD_DrvStop NOTES WARNINGS None 352 Appendix CDC API Reference This appendix provides a reference to the pC USB Device Communications Device Class CDC API and Abstract Control Model ACM subclass API The following information is provided for each of the services A brief description The function prototype The filename of the source code A description of the arguments passed to the function A description of returned value s Specific notes and warnings regarding use of the service 353 Appendix C C 1 CDC FUNCTIONS C 1 1 USBD_ CDC Init This function initializes all the internal variables and modules used by the CDC The initialization function is called by the application exactly once FILES usbd_cde h usbd_cde c PROTOTYPE static void USBD_CDC Init USBD_ERR p err ARGUMENTS p err Pointer to variable that will receive the return error code from this function US
24. E Micrium Software uC USB Device V4 App Host 0S Windows HID Visual Studio 2010 The solution HID s1n contains two projects Em HID Control tests the Input and Output reports transferred through the control endpoints The class specific requests GET_REPORT and SET_REPORT allows the host to receive Input reports and send Output reports respectively P HID Interrupt tests the Input and Output reports transferred through the interrupt IN and OUT endpoints 155 Chapter 9 An HID device is defined by a Vendor ID VID and Product ID PID The VID and PID will be retrieved by the host during the enumeration to build a string identifying the HID device The HID Control and HID Interrupt projects contain both a file named app hid _common c This file declares the following local constant static const TCHAR App DevPathStr _TEXT hid vid_fffe amp pid_1234 1 Listing 9 5 Windows Application and String to Detect a Specific HID Device L9 5 1 This constant allows the application to detect a specified HID device connected to the host The VID and PID given in App DevPathStr variable must match with device side values The device side VID and PID are defined in the USBD_DEV_CFG structure in the file usbd_dev_cfg c Refer to the section Modify Device Configuration on page 34 for more details about the USBD_DEV_CFG structure In this example VID fffe and PID 1234 in hexadecimal format 9 4 2 RUNN
25. E 3 5 Appendix F F 1 F 1 1 F 1 2 F 1 3 F 1 4 F 1 5 F 1 6 F 1 7 F 1 8 F 1 9 12 USBD_HID_OS_OutputDataPost c eceeceee eee eeeeeenseeeeeeeeeeeeees 414 USBD HID OS TXLOCK corinne aaier naanin ae cessvecessiceeeeeceedeceensxeceeevuneee 415 USBD_HID_OS_TXUNIOCK cceeeeeeeeeceeeeeeeeeeeeeeeeeeeeeeeeeeseeeeeeeeeeeeeeeees 416 USBD_HID_OS_TmmrTask cssecesseessseesesseeeessaeeeeseeeeeeseeseneneeensnees 417 MSG API Reference cccccccscssceccestecienetecveeuecestintieadceeresdcentenntnnuesecneeeeeess 419 Mass Storage Class Functions ee REENEN 420 USBD MSC IMU sissies dike deed gedet 420 USBD MSC Add geess ee Een orn icles Eeer 421 USBD MSC CIGAdd isi iie aa aee a a i aas 422 USBD_MSC_LUNA ccesecceeseeeeeeeeeeeeeeeeeeeeeeseseeeseeeeeseeeseeseeeeeeenees 424 USBD__MSG_ISCONMN itis cciscccesiceseseacesanceessetectenteesecdereseaesentandesdectenseces 426 USBD_MSC_TaskHandler ccccceseesseeeeeeeeeeeeeeeeeeeeeeessaeeeeeeeeeenens 427 MSG OS FUNCtIONS aeaaea deie cect eege EEN EEE den 428 USBD2MSGC OS Wait ees decisis eege EES dene cctes lectins dee eennaes 428 USBD_MSC_OS_CommSignalPost cccccceseeeeeseeeeeeeeeeeeeeeeeeees 429 USBD_MSC_OS_CommSignalPend cccccesseecceeeeeeeeseeeeseeeeeeeeeseeees 430 USBD_MSC_OS_CommSignalDel ccccceeceeseeeeeeeeeeeeeeeeeeeeees 431 USBD_MSC_OS_EnumSignalPost cccccssseeeeesseeeeeeeeeeeeeeeeeneseees 432 US
26. RETURNED VALUE DEF_OK if NO error s DEF_FAIL otherwise CALLERS USBD_URB Abort via Ip drv_api gt EP_Abort NOTES WARNINGS None 347 Appendix B B 1 18 USBD_DrvEP_Stall Set or clear stall condition on endpoint FILES Every device driver s usbd_drv c PROTOTYPE static CPU_BOOLEAN USBD_DrvEP_Stall USBD_DRV p dru CPU_INTO8U ep_addr CPU_BOOLEAN state ARGUMENTS p drv Pointer to USB device driver structure ep_addr Endpoint address state Endpoint stall state RETURNED VALUE DEF_OK if NO error s DEF_FAIL otherwise CALLERS E USBD_EP Stall via p drv_api gt EP_Stall E USBD CtrlStall NOTES WARNINGS None 348 B 1 19 USBD_DrviSR_Handler USB device Interrupt Service Routine CSR handler FILES Every device driver s usbd_drv c PROTOTYPE static void USBD DrvISR_Handler USBD_DRV p drv ARGUMENTS p drv Pointer to USB device driver structure RETURNED VALUE None CALLERS Processor level kernel aware interrupt handler NOTES WARNINGS None 349 Appendix B B 2 DEVICE DRIVER BSP FUNCTIONS B 2 1 USBD_BSP_Init Initialize board specific USB controller dependencies FILES Every device driver s usbd_bsp c PROTOTYPE static void USBD BSP Init USBD Du ap drei ARGUMENTS p drv Pointer to USB device driver structure RETURNED VALUE None CALLERS USBD_DrvInit NOTES WARNINGS None 350
27. RETURNED VALUE None CALLERS USB core debug task handler NOTES WARNINGS None 321 Appendix A 322 Appendix Device Controller Driver API Reference This appendix provides a reference to the Device Controller Driver API Each user accessible service is presented in alphabetical order The following information is provided for each of the services A brief description The function prototype The filename of the source code A description of the arguments passed to the function A description of returned value s Specific notes and warnings regarding use of the service 323 Appendix B B 1 DEVICE DRIVER FUNCTIONS B 1 1 USBD_Drvinit The first function within the Device Driver API is the device driver initialization Init function This function is called by USBD_DevStart exactly once for each specific device added by the application If multiple instances of the same device are present on the development board then this function is called for each instance of the device However applications should not try to add the same specific device more than once If a device fails to initialize it is recommend debugging to find and correct the cause of failure Note This function relies heavily on the implementation of several device board support package BSP functions See section B 2 Device Driver BSP Functions on page 350 for more information on device BSP functions FILES Every de
28. SET_REPORT GET_PROTOCOL and SET PROTOCOL Refer to Device Class Definition for Human Interface Devices HID Version 1 11 section 7 2 for more details about these class specific requests L9 1 4 Check if the high speed configuration is active and proceed to add the HID instance previously created to this configuration L9 165 Check if the full speed configuration is active and proceed to add the HID instance to this configuration Listing 9 1 also illustrates an example of multiple configurations The functions USBD_HID Add and USBD_HID CfgAdd allow you to create multiple configurations and multiple instances architecture Refer to section Table 7 1 Constants and Functions Related to the Concept of Multiple Class Instances on page 99 for more details about multiple class instances Listing 9 2 presents an example of table declaration defining a Report descriptor corresponding to a mouse The example matches the mouse report descriptor viewed by the host HID parser in Figure 9 1 The mouse report represents an Input report Refer to section 9 1 1 Report on page 136 for more details about the Report descriptor format The items inside a collection are intentionally indented for code clarity 147 Chapter 9 static CPU_INTO8U App USBD_ HID ReportDesc 1 USBD_HID GLOBAL USAGE PAGE 1 USBD_HID USAGE PAGE GENERIC_DESKTOP_CONTROLS 2 USBD_HID LOCAL USAGE 1 U
29. The Communication interface will be linked to a callback structure The Data interfaces may be linked to another callback structure common to all Data interfaces The class callbacks are called by the core task when receiving a request from the host sent over control endpoints refer to section 4 2 Task Model on page 58 for more details on the core task Table 7 2 indicates which callbacks are mandatory and optional and upon reception of which request the core task calls a specific callback 112 Class and Core Layers Interaction through Callbacks Request type Callback Request Mandatory Note Standard Conn SET_CONFIGURATION Yes Host selects a non null configuration number Standard Disconn SET_CONFIGURATION Yes Host resets the current configuration or device physically detached from host Standard UpdateAltSetting SET INTERFACE No Callback skipped if no alternate settings are defined for one or more interfaces Standard UpdateEPState SET FEATURE No Callback skipped if the state of the CLEAR_FEATURE endpoint is not used Standard IFDesc GET_DESCRIPTOR No Callback skipped if no class specific descriptors for one or more interfaces Standard IFDescGetSize GET_DESCRIPTOR No Callback skipped if no class specific descriptors for one or more interfaces Standard EPDesc GET_DESCRIPTOR No Callback skipped if no class specific descriptors for one or more en
30. USB device controller drivers ISR NOTES WARNINGS None 317 Appendix A A 6 6 USBD_EventHS This function notifies the stack that a host is high speed capable FILES usbd_core h usbd_core c PROTOTYPE void USBD_EventHS USBD_DRV ap drv ARGUMENTS p drv Pointer to device driver structure RETURNED VALUE None CALLERS USB device controller drivers ISR NOTES WARNINGS None 318 A 6 7 USBD_EventSuspend Notifies the stack a suspend event in the bus FILES usbd_core h usbd_core c PROTOTYPE void USBD_EventSuspend USBD_DRV p drv ARGUMENTS p drv Pointer to device driver structure RETURNED VALUE None CALLERS USB device controller drivers ISR NOTES WARNINGS None 319 Appendix A A 6 8 USBD_EventResume Notifies the stack a resume event in the bus FILES usbd_core h usbd_core c PROTOTYPE void USBD_EventResume USBD_DRV p drv ARGUMENTS p drv Pointer to device driver structure RETURNED VALUE None CALLERS USB device controller drivers ISR NOTES WARNINGS None 320 A 7 TRACE FUNCTIONS A 7 1 USBD_Trace Outputs debug information from the core Users must implement this function if trace functionality is enabled USBD_CFG_DBG_TRACE is defined to DEF_ENABLED FILES usbd_core h PROTOTYPE void USBD Trace const CPU_CHAR p str ARGUMENTS p_drv Pointer to the string containing debug information
31. USBD_DrvISR_Handler Depending on the platform architecture that is the way the kernel handles interrupts and the USB device controller interrupt vectors the device driver interrupt handler implementation may follow the models below 6 4 1 SINGLE USB ISR VECTOR WITH ISR HANDLER ARGUMENT If the platform architecture allows parameters to be passed to ISR handlers and the USB device controller has a single interrupt vector for the USB device the first level interrupt handler may be defined as PROTOTYPE void USBD BSP lt controller gt IntHandler void p arg ARGUMENTS p arg Pointer to USB device driver structure that must be typecast to a pointer to USBD_DRV 81 Chapter 6 6 4 2 SINGLE USB ISR VECTOR If the platform architecture does not allow parameters to be passed to ISR handlers and the USB device controller has a single interrupt vector for the USB device the first level interrupt handler may be defined as PROTOTYPE void USBD_BSP lt controller gt IntHandler void ARGUMENTS None NOTES WARNINGS In this configuration the pointer to the USB device driver structure must be stored globally in the driver Since the pointer to the USB device structure is never modified the BSP initialization function USBD_BSP_Init can save its address for later use 6 4 3 MULTIPLE USB ISR VECTORS WITH ISR HANDLER ARGUMENTS If the platform architecture allows parameters to be passed to ISR handlers and the
32. USBDev_API Device and Pipe Management API 215 USBDev_API Device and Pipe Management Example 217 USBDev_API Functions USBDev_API Synchronous Read and Write Example 218 USBDev_Bulkin_Open 215 218 220 509 USBDev_BulkOut_Open osese 215 218 510 USBDev_Close AAA USBDev_CtrlReq c ccccccccsseeesesessesneeseeneenee USBD_EventConm cceecceeeeeeeeeeeeeeeeeeeeneeeneeeeaeees USBD_EventDisconn USBD EventHS eegen sees USBD_EventReset AAA USBD_EventResume USBD_EventSetup USBD_EventSuspend USBDev_GetCurAltSetting AE 506 USBDev_GetNbrAltSetting AE 501 USBDev_GetNbrAssociatedIF AAA 503 USBDev_GetNbrDev AA 215 497 USBDev_IntIn_Open cceeeeesceeeeeeeeeeeteeeeeees 215 217 USBDev_IntOut_Open eeeeeeeeeeeeeeeeeteeeeeees 215 217 USBDev_IntriIn_Open AAA 511 USBDev_IntrOut_Open eeeeeeeeeeeeeeeeeeeeeteeeteeeeeee 512 USBDev_IsHighSpeed AA 508 USBDev_Open 215 499 USBDev_PipeAbort AAA 516 USBDev_PipeClose 215 514 USBDev_PipeGetAddr AAA 513 USBDev_PipeRd AAA 522 USBDev_PipeRdAsyn Au 524 USBDev_PipeStall AA 515 U bDev Pier cece eeeeeseeseensenseeeenneenee 520 USBDev_SetAltSetting A 504 USBD_HID_Add eeceeseeeeeeeeeeteees 144 147 151 389 USBD_HID_CfgAdd A 144 145 147 391 USD HID CEO MAX NR CEO ee 76 143 USBD_HID_CFG_MAX_NBR_DEV ee 76 143 USBD_HID_C
33. a semaphore and a task to manage debug events allocation and debug events processing respectively If any error happen USBD_ERR_OS INIT FAIL should be assigned to p err and the function should return immediately Otherwise USBD_ERR_NONE should be assigned to p_err 299 Appendix A A 5 2 USBD_CoreTaskHandler Process all core events and operations FILES usbd_internal h usbd_core c PROTOTYPE void USBD_CoreTaskHandler void ARGUMENTS None RETURNED VALUE None CALLERS USB RTOS layer IMPLEMENTATION GUIDELINES Typically the RTOS layer should create a shell task for core events The primary purpose of the shell task is to run USBD_CoreTaskHandler 300 A 5 3 USBD_DbgTaskHandler Process all pending debug events generated by the core FILES usbd_internal h usbd_core c PROTOTYPE void USBD_DbgTaskHandler void ARGUMENTS None RETURNED VALUE None CALLERS USB RTOS layer IMPLEMENTATION GUIDELINES E Typically the RTOS layer code should create a shell task to process debug events generated by the core The primary purpose of the USBD_DbgTaskHandler This function is only present in the code if trace option is enabled in the stack shell task is to run 301 Appendix A A 5 4 USBD_OS EP _SignalCreate Creates a signal semaphore for endpoints operations FILES usbd_internal h usbd_os c PROTOTYPE void USBD_OS EP SignalCr
34. and so on os_cfg h is a required file for any wC OS III application See the pC OS III documentation and books for further information app c contains the application code for the example project As with most C programs code execution starts at main At a minimum app c initializes pC OS III and creates a startup task that initializes other Micrium modules 32 Building the Sample Application app_cfg h is a configuration file for your application This file contains defines to configure the priorities and stack sizes of your application and the Micrium modules tasks app_ lt module gt c and app lt module gt h These optional files contain the Micrium modules uC TCP IP uC FS pC USB Host etc initialization code They may or may not be present in the example projects 2 4 2 COPYING AND MODIFYING TEMPLATE FILES Copy the files from the application template and configuration folders into your application as shown in Figure 2 2 A app_usbd lt class gt c Ef EvalBoards Er uc USB Device v4 g L lt manufacturer gt dy App AT lt board name gt A Device AE lt compiler gt A M L os lt project name gt i A app_usbd c uCOS II En An uCOS III SE usbd_cfg h usbd_dev_cfg h dd usbd_dev_cfg c Figure 2 2 Copying Template Files app_usbd is the master template for USB application specific initialization code This file contains t
35. data that can have medium latency QoS priority of 1 Figure 11 3 and Figure 11 4 represent this example without and with a QoS based scheduler respectively Task A OS priority 1 Task Very high latency data Task B OS priority 2 Task Medium latency data Task C OS priority 3 Task High latency data Figure 11 3 Task Execution Order Without QoS Based Scheduling PHDC scheduler Task A my opr pene eae F OS priority 1 Task 6 Task Very high latency data 1 H H H TaskB mm HEES OS priority 2 Task Task Medium latency data a EE Task Ce EE eier eecht OS priority 3 Task Task High latency data t Figure 11 4 Task Execution Order with QoS Based Scheduling F11 4 1 F11 4 2 F11 4 3 A task currently holds the lock on the write bulk endpoint task A B and C are added to the wait list until the lock is released 197 Chapter 11 F11 4 4 The lock has been released The QoS based scheduler s task is resumed and finds the task that should be resumed first according to the QoS of the data it wants to send Task B is resumed F11 4 5 Task B completes its execution and releases the lock on the pipe This resumes the scheduler s task F11 4 6 Again the QoS based scheduler finds the next task
36. if err USBD_ERR_NONE Handle the error Listing 9 3 Synchronous Bulk Read and Write Example L9 3 1 The class instance number created from USBD_HID Add will serve internally for the HID class to route the transfer to the proper interrupt OUT or IN endpoint L9 3 2 The application must ensure that the buffer provided to the function is large enough to accommodate all the data Otherwise synchronization issues might happen Internally the read operation is done either with the control endpoint or with the interrupt endpoint depending on the control read flag set when calling USBD_HID_Add L9 3 3 In order to avoid an infinite blocking situation a timeout expressed in milliseconds can be specified A value of 0 makes the application task wait forever L9 3 4 The application provides the initialized transmit buffer 151 Chapter 9 9 3 5 ASYNCHRONOUS COMMUNICATION Asynchronous communication means that the transfer is non blocking Upon function call the application passes the transfer information to the device stack and does not block Other application processing can be done while the transfer is in progress over the USB bus Once the transfer is completed a callback is called by the device stack to inform the application about the transfer completion Listing 9 4 shows an example of an asynchronous read and write void App_USBD_HID Comm CPU_INT08U class_nbr CPU_INTO8U rx_buf 2 CPU
37. maximum stack usage for interrupts Note that the most stack greedy function path is not necessarily the longest or deepest function path The easiest and best method for calculating the maximum stack usage for any task function should be performed statically by the compiler or by a static analysis tool since these can calculate function task maximum stack usage based on the compiler s actual code generation and optimization settings So for optimal task stack configuration we recommend to invest in a task stack calculator tool compatible with your build toolchain 70 Device and Device Controller Driver Configuration 5 3 DEVICE AND DEVICE CONTROLLER DRIVER CONFIGURATION In order to finalize the configuration of your device you need to declare two structures one will contain information about your device Vendor ID Product ID etc and another that will contain information useful to the device controller driver A reference to both of these structures needs to be passed to the USBD_DevAdd function which allocates a device controller For more information on how to modify device and device controller driver configuration see section 2 4 2 Copying and Modifying Template Files on page 33 5 4 CONFIGURATION EXAMPLES This section provides examples of configuration for uC USB Device stack based on some typical usages This section will only give examples of static stack configuration as the application specific configuration
38. or a mouse The requirements of the USB functions are described in the USB class specification For example keyboards and mice are implemented using the Human Interface Device HID specification USB devices must also respond to requests from the host For example on power up or when a device is connected to the host the host queries the device capabilities during enumeration using standard requests 16 Data Flow Model 1 2 DATA FLOW MODEL This section defines the elements involved in the transmission of data across USB 1 2 1 ENDPOINT Endpoints function as the point of origin or the point of reception for data An endpoint is a logical entity identified using an endpoint address The endpoint address of a device is fixed and is assigned when the device is designed as opposed to the device address which is assigned by the host dynamically during enumeration An endpoint address consists of an endpoint number field 0 to 15 and a direction bit that indicates if the endpoint sends data to the host IN or receives data from the host OUT The maximum number of endpoints allowed on a single device is 32 Endpoints contain configurable characteristics that define the behavior of a USB device Bus access requirements Bandwidth requirement Error handling Maximum packet size that the endpoint is able to send or receive Transfer type Direction in which data is sent and receive from the host ENDPOINT ZERO RE
39. s manufacturer vendor product IDs and release versions by sending a Get Descriptor request to obtain the device descriptor and the maximum packet size of the default pipe control endpoint 0 Once that is done the host assigns a unique address to the device which will tell the device to only answer requests at this unique address Next the host gets the capabilities of the device by a series of Get Descriptor requests The host iterates through all the available configurations to retrieve information about number of interfaces in each configuration interfaces classes and endpoint parameters for each interface and will lastly finish the enumeration process by selecting the most suitable configuration 25 Chapter 7 26 Chapter Getting Started This chapter gives you some insight into how to install and use the wC USB Device stack The following topics are explained in this chapter Prerequisites Downloading the source code files Installing the files Building the sample application Running the sample application After the completion of this chapter you should be able to build and run your first USB application using the uC USB Device stack 27 Chapter 2 2 1 PREREQUISITES Before running your first application you must ensure that you have the minimal set of required tools and components P Toolchain for your specific microcontroller E Development board D wC USB Device stack with the source code of
40. usbd_acm_serial h usbd_acm_serial c PROTOTYPE CPU_INT32U USBD ACM SerialTx CPU_INTO8U subclass_nbr CPU_INTO8U p buf CPU_INT32U buf len CPU_INT16U timeout USBD_ERR whey err ARGUMENTS subclass_nbr Pointer to USB device driver structure p buf Pointer to buffer of data that will be transmitted buf_len Number of octets to receive timeout_ms Timeout in milliseconds p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_INVALID ARG USBD_ERR_ INVALID CLASS STATE USBD_ERR_EP INVALID ADDR USBD_ERR_EP INVALID STATE USBD_ERR_EP INVALID TYPE USBD_ERR_OS TIMEOUT USBD_ERR_OS ABORT USBD_ERR_OS FAIL 376 RETURNED VALUE Number of octets transmitted if NO error s 0 otherwise CALLERS Application NOTES WARNINGS None 377 Appendix C C 2 7 USBD_ACM SerialLineCtriGet Return current control line state FILES usbd_acm_serial h usbd_acm_serial c PROTOTYPE CPU_INTO8U USBD_ACM SerialLineCtrlGet CPU_INTO08U subclass_nbr USBD_ERR p_err ARGUMENTS subclass nbr CDC ACM serial emulation subclass instance number p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_INVALID ARG RETURNED VALUE Bit field with the state of the control line USBD_ACM SERIAL CTRL BREAK Break signal is set USBD_ACM SERIAL CTRL RTS RTS signal is set USBD_ACM SERIAL CTRL DTR DTR signal is set
41. void p buf CPU_INT32U buf_len USBD_VENDOR_ASYNC_FNCT async_fnct void p_async arg USBD_ERR p err ARGUMENTS class nbr_ Class instance number p buf Pointer to receive buffer buf len Receive buffer length in octets async _fnct Receive callback p async org Additional argument provided by application for receive callback p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_ NULL PTR USBD_ERR_INVALID ARG USBD_ERR_ INVALID CLASS STATE USBD_ERR_ DEV INVALID NBR USBD_ERR_EP INVALID NBR 493 Appendix G USBD_ERR DEV INVALID STATE USBD_ERR_EP INVALID TYPE USBD_ERR_ EP INVALID STATE RETURNED VALUE None CALLERS Application NOTES WARNINGS None 494 G 1 12 USBD_Vendor_IntrWrAsync Send data to host through Interrupt IN endpoint This function is non blocking It returns immediately after transfer preparation Upon transfer completion a callback provided by the application will be called to finalize the transfer FILES usbd_vendor c PROTOTYPE void USBD_Vendor_IntrWrAsync CPU_INTO8U class_nbr void p buf CPU_INT32U buf_len USBD_VENDOR_ASYNC_FNCT async_fnct void p_async arg CPU_BOOLEAN end USBD_ERR p err ARGUMENTS class nr Class instance number p_buf Pointer to transmit buffer buf_len Transmit buffer length in octets async _fnct Transmit callback p_async_arg Additional argument provided by application for transm
42. 1 Read from device 2 Write from device and 3 Exit The choice 1 will initiate an interrupt IN transfer to obtain an Input report from the device The content of the Input report will be displayed in the console Choice 2 will initiate an interrupt OUT transfer to send an Output report to the device On the device side the task App USBD_HID ReadTask is used to receive Output reports from the host The synchronous HID read function USBD_HID Rd will receive the Output report data Nothing is done with the received data The Output report has a size of 4 bytes Another task App USBD_HID WriteTask will send Input reports to the host using the synchronous HID write function USBD_HID Wr The Input report has a size of 4 bytes Using the Demo Application Figure 9 5 and Figure 9 6 show screenshot examples corresponding to HID Control exe and HID Interrupt exe respectively Studio 2010 Debug EI es Successfully Opened HID Compliant Device FEET ET i Menu i 1 Send get report 2 Send set report 3 Exit Enter the Choice 1 4 Bytes Received From Device 246 8 FEET ET i Menu i 1 Send get report 2 Send set report 3 Exit Enter the Choice 2 4 Bytes Sent To Device 16 26 36 48 Figure 9 5 HID Control exe Vendor Specific Demo fo 5 C Micrium Software uC USB Device V4 App Host OS Windows HID Visual Studio 2
43. 1 9 G 1 10 G 1 11 G 1 12 G 2 G 2 1 G 2 2 G 2 3 G 2 4 G 2 5 G 2 6 G 2 7 G 2 8 G 2 9 G 2 10 G 2 11 USBD_PHDC_Wrpreamble cccccesseecceeesseeeeeeeesseaeeeeenseaeeeeenenaes 458 USBD PHDG Wri airone ata a eter atv aiden ds eves acc 460 USBD PHDG Reset rescore A 462 PHDC OS Layer Functions ssssssnnssennnnnnnnnnnennnnnnnnnnnnnnnnnnnnnnnn nnmnnn nnan 463 USBD RH OS MI srianan 463 USBD_PHDC_OS_RdLOCK ecesccceceseeeeceeeeeseeeeeeeeseaeeeeeeseaaeeeeeneeees 464 USBD_PHDC_OS_RAUN LOCK cccesseecceeeeseeeeeeeeeseaeeeeenseaaeeeeeeeeees 466 USBD_PHDC_OS_WrlntrLock 00 0 0 ecssscceeeeseeeeeeeeeseeeeeeeeesaeeeeenenees 467 USBD_PHDC_OS_WrlIntrUnLock cccceeeseeeceeeeseeeeeeeeeseeaeeeeeneeees 468 USBD_PHDC_OS_WYrBulkLock cscsecceeeeseeeeeeeeeseeeeeeeeseeeeeeeeeenees 469 USBD_PHDC_OS_WrBulkUN LOCK c cccsesseceeeeeeseeeeeeeeseeeeeeeeeeeees 471 Vendor Class API Reference cececeeeeeeeeeeeeeeeeeeeeseeeeeeeneaneeeeeeeenees 473 Vendor Class FUN Ctions REENEN EEN 474 USBD Vendor Trait e vases ees deeg ee REESEN EE KEEN 474 USBD_Vendor_Add 2 cceceeeeeeeeeeeeeseeaeeeeeeeeeeeseseeeeeesseaeeeeeeeeeeeees 475 USBD_Vendor_CfgAdd cseeccccceeseeeceeeeseeeeeeeeseneeseeeeeseeeseeeeseenseeeeseaes 477 USBD_Vendor_ISCOnn ee REENEN REENEN 479 USBD Vendor Rd use Tess nied eee ee 481 USBD Vendor Wr vue EEN EENS ENEE EEN 483 USBD_Vendor_ROASYIC
44. 4 if err USBD_ERR_NONE Handle the error Listing 7 2 Multiple Class Instances HS FS Device 2 Configurations and 1 Single Interface Code L7 2 1 Initialize the class Any internal variables structures and class RTOS port will be initialized L7 2 2 Create the class instance class_0 The function USBD_XXXX_Add allocates a class control structure associated to class_0 Depending on the class besides the parameter for an error code USBD_XXXX_Add may have additional parameters representing class specific information stored in the class control structure L7 2 3 Add the class instance class_0 to the full speed configuration cfg_0_fs USBD_XXXX_CfgAdd will create the interface 0 and its associated endpoints IN and OUT If the full speed configuration is active any communication done on the interface 0 will use the class instance number class_0 L7 2 4 Add the class instance class_0 to the high speed configuration cfg_0_hs 103 Chapter 7 In the case of the high speed capable device presented in Figure 7 2 in order to enable the use of Device_Qualifier and Other_Speed_Configuration descriptors the function USBD_CfgOtherSpeed should be called during the wC USB Device initialization Listing 2 5 presents the function App USBD Init defined in app usbd c This function shows an example of the pC USB Device initialization sequence USBD_CfgOtherSpeed should be called after the creation o
45. 4 A 4 1 A 4 2 A 4 3 A 4 4 Debug and TACO ic arnore Aa REENEN cede asstecteerssiereeeeesitnedeessunte 231 Using Debug Traces scccccssseeccecessneeceesesseeeeeensneeeeeenssneeeeeensneeeeeensenes 232 Debug Configuration cccseecceccesseeeceeensneeeeeenssneeeeeessneneceeensneeseeenssnes 232 Debug Trace Output c cciteceseeictscecvsiedeceensusetveseseedctececunuedvcdenstcthveresnetes 232 Deb g Format EE 233 Handling Debug Event ccccccceseeeceeeeseeeeeeeeeseeeeeeeeseeeseeeesneeeseeensenes 234 Debug Event Pool araeir Zeg deveveccedeesetieudccegeecieetevevecieteeeveceey 234 DO DUG TASK ee EES EES NEE ENEE EES 234 Debug EL e aaa aaraa aeaaea aa aa aieia aeaaaioii edanan 234 Porting UC USB Device to your RTOS sssssssssssnnennrnnnnnnnnnnnnnnnnnnnnnnnne 237 OVONVIOW eseou EES 238 Porting Modules to a RTOS REENEN En 239 Core Layer RTOS Model sccccceseeeeeeeeeeeeeeeeeeeeeeeeeeeeseeneeeeseeeeneeeneees 240 Synchronous Transfer Completion Signals ssecccsssseeeeeeseeeeeeees 240 Core Events Management cccccessseneeeeeseeeeeeeeeeeeeeeeeseeeneeeenseeeneneens 241 Debug Events Management eseeccccceeseeeceeeeesneeeeeeeseeeeeeeeeseeeseeeeeenes 241 Porting The Core Layer to a RTOS ees ENEE En 242 Gore API R tereneg sesieugecgegieguek eege ue cece Eed e EES een 245 DEVICE FUNCTIONS sinisini Sesesecedececeis sce eniin a eta iaat nein 246 USBD Nit araire scitesatevescttentenaiecatdeavacuieheaedeaduersvac
46. Add an existing MSC instance to the specified configuration and device The MSC instance was previously created by the function USBD_MSC_Add_ FILES usbd_msc h usbd_msc c PROTOTYPE CPU_BOOLEAN USBD_MSC_CfgAdd CPU_INTO8U class_nbr ARGUMENTS class obt dev_nbr cfg_nbr p_err 422 CPU_INTO8U dev_nbr CPU_INTO8U cfg_nbr USBD_ERR p err MSC instance number Device number Configuration index to add MSC instance to Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_INVALID ARG USBD_ERR_ALLOC USBD_ERR NULL PTR USBD_ERR_ DEV INVALID NBR USBD_ERR DEV INVALID STATE USBD_ERR CFG INVALID NBR USBD_ERR_IF ALLOC USBD_ERR_IF ALT ALLOC USBD_ERR_IF INVALID NBR USBD_ERR_EP NONE AVAIL USBD_ERR_EP ALLOC RETURNED VALUE DEF_YES if MSC instance is added to USB device configuration successfully DEF_NO otherwise CALLERS Application NOTES WARNINGS USBD MSC _CfgAdd basically adds an Interface descriptor and its associated Endpoint descriptor s to the Configuration descriptor One call to USBD_MSC_CfgAdd builds the Configuration descriptor corresponding to a MSC device with the following format Configuration Descriptor Interface Descriptor MSC Endpoint Descriptor Bulk OUT Endpoint Descriptor Bulk IN If USBD_MSC_CfgAdd is called several times from the application it allows to create multiple instances and multiple c
47. CALLERS Application NOTES WARNINGS None 378 C 2 8 USBD_ACM SerialLineCtriReg Register line control change notification callback FILES usbd_acm_serial h usbd_acm_serial c PROTOTYPE void USBD_ACM SerialLineCtrlReg CPU_INTO8U subclass_nbr USBD_ACM SERIAL LINE CTRL CHNGD line_ctrl_chngd void p arg USBD_ERR p err ARGUMENTS subclass obt CDC ACM serial emulation subclass instance number line _ctrl_chngd Line control change notification callback see note 1 p arg Pointer to callback argument p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_INVALID ARG RETURNED VALUE None CALLERS Application 379 Appendix C NOTES WARNINGS The callback specified by line _ctrl_chngd argument is used to notify changes in the control signals to the application The line control notification function has the following prototype void AppLineCtrlChngd CPU_INTO8U subclass_nbr CPU_INTO8U events CPU_INTO8U events_chngd void p arg Argument s subclass_nbr CDC ACM serial emulation subclass instance number events Current line state events _chngd Line state flags that have changed events _chngd Pointer to callback argument 380 C 2 9 USBD_ACM_ SerialLineCodingGet Get the current state of the line coding FILES usbd_acm_serial h usbd_acm_serial c PROTOTYPE void USBD_ACM SerialLineCodingGet CPU_INT08U subclas
48. Chapter 8 8 1 8 2 8 3 8 3 1 8 4 8 4 1 Simple Full Speed USB device AER EEN EEE EEN 72 Composite High Speed USB device ee ENEE 73 Complex Composite High Speed USB device see 74 Device Driver Guide 2 eceeceeeeeeeeeeeeeeeeeeceneeseeeeseseseeeesneaneneeeseeeees 77 Device Driver Architecture ccccccecesssesseeeeeeeeeeeeeeeeseeeeenseeaneeeeeeeenees 77 Device Driver Model 2 cceceeeeeeseeeeeeseeeneeceeeeeeseeeeeseaeneaneeseeeeeeees 78 Device Driver APD sccscccicscscevcesccetcecewes EE EE aanta aaa aaa annii eaei niaii 78 interrupt Handling BEE 81 Single USB ISR Vector with ISR Handler Argument ccccessseeeeeees 81 Single USB ISR Vector sccccesseeecceesseeeeeeensseeeeeeenseceeeeeenseceeeeensseceeeeense 82 Multiple USB ISR Vectors with ISR Handler Arguments 00 82 Multiple USB ISR Vectors uk 83 USBD_DrvISR_Handler i inr aeniea saaa daana aseda annann aaiae Faia 83 Device Configuration cceseseeceeseeeeeeeeeeeeeeeeeeeeneeeeeeeeeneeseeseeneeeeeeneeeenees 85 Endpoint Information Table cceccesseeeeeeceeeeeeeeeeeeeeeesseeneaeeeeeeeeeeeens 86 Memory Allocation cecccceeseeeceeeeeeeeeeeeneeneeseeeeeeeeeeeeneeneeseeseeneeeeeeneeeeeees 88 CPU and Board Support ccecceeceeeeeeeeeeeesseeaneeeeeeeeeeeeseeeeeseseeneeees 88 USB Device Driver Functional Model 2 cccccceceeeeeeeeeeeeeneeeeeeeeeees 89 Device Synchronous Receive c ccee
49. GUI 1 and 2 TeraTerm Yes DTR can be set using a macro GUI does NOT allows you to set 1and2 134 clear DTR easily Table 8 10 Serial Terminals and CDC Serial Demo Chapter Human Interface Device Class This chapter describes the Human Interface Device HID class supported by pC USB Device The HID implementation complies with the following specifications E Device Class Definition for Human Interface Devices HID 6 27 01 Version 1 11 E Universal Serial Bus HID Usage Tables 10 28 2004 Version 1 12 The HID class encompasses devices used by humans to control computer operations Keyboards mice pointing devices game devices are some examples of typical HID devices The HID class can also be used in a composite device that contains some controls such as knobs switches buttons and sliders For instance mute and volume controls in an audio headset are controlled by the HID function of the headset The headset also has an audio function HID data can exchange data for any purpose using only control and interrupt transfers The HID class is one of the oldest and most popular USB classes All the major host operating systems provide a native driver to manage HID devices That s why a variety of vendor specific devices work with the HID class This class also includes various types of output directed to the user information e g LEDs on a keyboard 135 Chapter 9 9 1 OVERVIEW A HID device is composed of the followi
50. Interface Descriptor PHDC Endpoint Descriptor Bulk OUT Endpoint Descriptor Bulk IN Endpoint Descriptor Interrupt IN optional The Interrupt IN endpoint is optional It will be added to the Interface descriptor if application specified that it will send low latency data when calling USBD_PHDC WrCfg If USBD_PHDC CfgAdd is called several times from the application it allows to create multiple instances and multiple configurations For instance the following architecture could be created for an high speed device High speed Configuration 0 Interface 0 PHDC 0 Configuration 1 Interface 0 PHDC 0 Interface 1 PHDC 1 In that example there are two instances of PHDC PHDC 0 and PHDC 1 and two possible configurations for the device Configuration 0 and Configuration 1 Configuration 1 is composed of two interfaces Each class instance has an association with one of the interfaces If Configuration 1 is activated by the host it allows the host to access two different functionalities offered by the device 446 F 1 4 USBD_PHDC_IsConn Get PHDC connection state FILES usbd_phdc h usbd_phdc c PROTOTYPE CPU_BOOLEAN USBD_PHDC_IsConn CPU_INTO8U class_nbr ARGUMENTS class_nbr PHDC instance number RETURNED VALUE DEF_YES if PHDC is connected DEF_NO otherwise CALLERS Application NOTES WARNINGS USBD_PHDC_ IsConn is typically used to verify tha
51. One interface for HID Two interfaces for CDC ACM Second configuration One interface for HID Two interfaces for CDC ACM One interface for vendor USBD_CFG MAX NBR_IF ALT 7 No alternate interface needed but this value must at least be equal to USBD_CFG_MAX NBR_IF USBD_CFG MAX NBR_IF_GRP 2 CDC ACM needs to group its communication and data interfaces into a single USB function Since there are two CDC ACM class instances there will be two interface groups USBD_CFG MAX NBR_EP_DESC 9 10 11 One IN and optional OUT interrupt endpoint for HID or 12 Three endpoints for first CDC ACM class instance Three endpoints for second CDC ACM class instance Two bulk plus two optional interrupt endpoints for vendor USBD_CFG MAX NBR_EP_OPEN 8 9 10 In the worst case host enables second configuration or 11 Two control endpoints for device s standard requests One IN and optional OUT interrupt endpoint for HID Three endpoints for second CDC ACM class instance Two bulk plus two optional interrupt endpoints for vendor USBD_HID CFG MAX NBR DEV 1 Only one instance of HID class is needed It will be shared between all the configurations USBD_HID CFG MAX NBR_CFG 4 HID class instance can be used in all of device s configurations USBD_CDC_CFG MAX NBR_DEV 2 Two CDC base class instances are used USBD_CDC_CFG MAX NBR_CFG 2 Each CDC base class instance can be used in one full speed and one high speed configuration USBD_ACM SERIAL CFG MAX NBR DEV 2 Tw
52. RTOS QoS based scheduler cececeeeeeeeeeeeeeeeeeeeeeeeeeensneaeeeeeeeeeeeees 196 Using the Demo Application cceesseeeeeeeceeeeeeeeeeeeeeeeseaeeeeeeeeeenees 200 Setup the Application REENEN EENEG 200 Running the Demo Application een 202 Porting PHDG toa RTOS isana e eege geed age ARAA 203 Vemdor EA F EL e E E E AAE 205 OVEN VIOW AATA T E TA T 206 eu UE e TEE 207 General Configuration rerea araa ae aeaaee a raana aa Teana oaia ae aa aaea 207 Class Instance Configuration NEEN EEN 208 Class Instance COMMUNICATION ccccceeeeeeseeeeeeeeeeeee eee eeeeeesseeeneeees 210 Synchronous COMMUNICATION 2 eecccceeeseeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeseees 211 Asynchronous Communication ecceeceeeeeeeeeeeeeeeeeneeeeeeeeeeeeens 212 USBDev API aaen aaa edd TEE alee ents 214 Device and Pipe Management ccccccsseeccceeeeseeeeeeeeseeeeeeeesneeeeeeeeeees 215 Device COMMUNICATION 2 ecceeeeee eee eeeeeeeeeeeeeeeeeeeeeeseeeeesseaneeeeeeeeenees 218 Using the Demo Application ccceesseeeeeeeeeeeeeeeeeeeeeeeseeeeeeeeeeeenees 220 Configuring PC and Device Applications REENEN 220 Editing an INF OT 222 Running the Demo Application een 224 GUID EE 228 Table of Contents Chapter 13 13 1 13 1 1 13 1 2 13 1 3 13 2 13 2 1 13 2 2 13 2 3 Chapter 14 14 1 14 2 14 3 14 3 1 14 3 2 14 3 3 14 4 Appendix A A 1 A 1 1 A 1 2 A 1 3 A 1 4 A 1 5 A 2 A 2 1 A 3 A 3 1 A 3 2 A 3 3 A
53. SetLineCoding request Application can perform any specific operations USBD_ACM SerialLineCtrl1Get SetControlLineState Application can get the current control line state set by the host with the SetControlLineState request USBD_ACM SerialLineCtr1Reg SetControlLineState Application registers a callback called by the ACM subclass upon reception of the SetControlLineState request Application can perform any specific operations USBD_ACM SerialLineStateSet Serial line state Application can set any line state event s While setting the line state an interrupt IN transfer is sent to the host to inform about it a change in the serial line state USBD_ACM SerialLineStateClr Serial line state Application can clear two events of the line state transmission carrier and receiver carrier detection All the other events are self cleared by the ACM serial emulation subclass Table 8 7 ACM Subclass Functions Related to the Subclass Requests and Notifications Micrium s ACM subclass always uses the interrupt endpoint to notify the host of the serial line state You cannot disable the interrupt endpoint 127 Chapter 8 8 4 5 SUBCLASS INSTANCE COMMUNICATION Micrium s ACM subclass offers the following functions to communicate with the host For more details about the functions parameters refer to section C 2 CDC ACM Subclass Functions on page 369 Function name Operat
54. USB device controller has multiple interrupt vectors for the USB device e g USB events DMA transfers the first level interrupt handler may need to be split into multiple sub handlers Each sub handler would be responsible for managing the status reported to the different vectors For example the first level interrupt handlers for a USB device controller that redirects USB events to one interrupt vector and the status of DMA transfers to a second interrupt vector may be defined as PROTOTYPE void USBD_BSP_ lt controller gt _EventIntHandler void p arg void USBD_BSP_ lt controller gt _DMAIntHandler void p arg ARGUMENTS p arg Pointer to USB device driver structure that must be typecast to a pointer to USBD_DRV 82 Interrupt Handling 6 4 4 MULTIPLE USB ISR VECTORS If the platform architecture does not allow parameters to be passed to ISR handlers and the USB device controller has multiple interrupt vectors for the USB device e g USB events DMA transfers the first level interrupt handler may need to be split into multiple sub handlers Each sub handler would be responsible for managing the status reported to the different vectors For example the first level interrupt handlers for a USB device controller that redirects USB events to one interrupt vector and the status of DMA transfers to a second interrupt vector may be defined as PROTOTYPE void USBD_BSP lt controller gt EventIntHandler void void USBD_BSP lt
55. USB HID IR sctsvcesscsaviecacivsieeveccit naa a a Eege evden Seen 388 D 1 2 USBDEHID2 AC EE 389 D 1 3 USBD IA Bt e EE 391 D 1 4 USBD HID Ieren aeaa er Eare a ra ae eege d A ege eege eg Even 393 D 1 5 USED HID EE 394 D 1 6 USBD HID ROASYINC isis csetscccccecceceneceedessacts EENS CES EE EEeEEeEE Eve 396 D 1 7 USBD HID Wri ege ee eege en 398 D 1 8 USBD HID WNr tevngelt eege ege Edge ai 400 D 2 HID OS FUNCTIONS TA 402 D 2 1 USBD HID OS WAR iiiaae anana aan tanenin aaien nadatnan aidaa aieiaa 402 D 2 2 USBD_HID_OS_lnputLock sssssssssnsssssnnennnnnneennnnnennnnnnnnnnnn nnen nn nanne nne 403 D 2 3 USBD_HID_OS_lnputUnlock 2 2 2 2 ceeceeeeeeeeeeeeeeeeeeeeeeeeeeeeeesneeeeeeeeeees 404 D 2 4 USBD_HID_OS_InputDataPend cceeeeeeeeeeeeeesseeneeeeeeeeenens 405 D 2 5 USBD_HID_OS_InputDataPendADort ccceecceeeseeeeeeeeeseeeeeeeeneeees 407 D 2 6 USBD_HID_OS_InputDataPost c s eeeeeeeeee eee eeeeeesseeeeeeeeeeeeeens 408 D 2 7 USBD_HID_OS_OutputLock use 409 D 2 8 USBD_HID_OS_OutputUnlock ceceeseeeeeeeeeee eee REENEN 410 D 2 9 USBD_HID_OS_OutputDataPend ceeeeeeeeeeeeeeeeeeeeneeeeeeeeeees 411 D 2 10 USBD_HID_OS_OutputDataPendAbort ccccceseseeeeeeseeeeeeeeeeeees 413 Table of Contents D 2 11 D 2 12 D 2 13 D 2 14 Appendix E E 1 E 1 1 E 1 2 E 1 3 E 1 4 E 1 5 E 1 6 E 2 E 2 1 E 2 2 E 2 3 E 2 4 E 2 5 E 2 6 E 3 E 3 1 E 3 2 E 3 3 E 3 4
56. VALUE Current device state If no error s USBD_DEV STATE NONE otherwise CALLERS USBD_EP_BulkRx USBD_EP_BulkRxAsync USBD_EP_BulkTx USBD_EP_BulkTxAsync USBD_EP Ctr1Rx USBD_EP Ctr1RxStatus USBD_EP Ctr1Tx USBD_EP_IntrRx 249 Appendix A USBD_EP_IntrRxAsync USBD_EP_IntrTx USBD_EP_IntrTxAsync NOTES WARNINGS None 250 A 1 5 USBD_DevAdd Adds device to the stack FILES usbd_cde h usbd_cdce c PROTOTYPE CPU_INTO8U USBD DevAdd USBD_DEV_CFG p dev cfg USBD_BUS_FNCTS ap bus fnct USBD_DRV_API ap dru api USBD_DRV_CFG ap drv_cfg USBD_DRV_BSP_ API p bsp api USBD_ERR p err ARGUMENTS p dev cfg Pointer to specific USB device configuration p bus fnct Pointer to specific USB device configuration p drv api Pointer to specific USB device driver API p drv cfg Pointer to specific USB device driver configuration p bsp api Pointer to specific USB device board specific API p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_INVALID ARG USBD_ERR_ NULL PTR USBD_ERR_ DEV ALLOC USBD_ERR_EP NONE AVAIL 251 Appendix A RETURNED VALUE Device number If no error s USBD_DEV_NBR_NONE otherwise CALLERS Application NOTES WARNINGS None 252 A 2 CONFIGURATION FUNCTIONS A 2 1 USBD_CfgAdd Adds a configuration to the device FILES usbd_core h usbd_core c PROTOTYPE CPU_INTO8U USBD
57. a receive transfer The queued receive transfer does not need to satisfy the whole requested transfer length at once If multiple transfers are queued only the last queued transfer must be signaled to the USB device stack This is required since the USB device stack iterates through the receive process until all requested data or a short packet has been received On FIFO based controllers this device driver API is responsible for enabling data to be received into the endpoint FIFO including any related ISRs The call to USBD_EP_Rx returns immediately to the application without blocking while data is being received 91 Chapter 6 FG6 2 2 F6 2 3 F6 2 4 F6 2 5 F6 2 6 92 The USB device controller triggers an interrupt request when it is finished receiving the data This invokes the USB device driver interrupt service routine ASR handler directly or indirectly depending on the architecture Inside the USB device driver ISR handler the type of interrupt request is determined to be a receive interrupt USBD_EP_RxCmpl is called to queue the endpoint that had its transfer completed The core task de queues the endpoint that completed a transfer and invokes USBD_EP Process which internally calls USBD_DrvEP_Rx On DMA based controllers this device driver API is responsible for de queuing the completed receive transfer and returning the amount of data received In case the DMA based controller requires the
58. a category order i e initialization and communication categories The following information is provided for each of the services A brief description The function prototype The filename of the source code A description of the arguments passed to the function A description of returned value s Specific notes and warnings regarding use of the service 473 Appendix G G 1 VENDOR CLASS FUNCTIONS G 1 1 USBD_Vendor _Init Initialize internal structures and local global variables used by the Vendor class FILES usbd_vendor c PROTOTYPE void USBD_Vendor_Init USBD_ERR p err ARGUMENTS p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE RETURNED VALUE None CALLERS Application NOTES WARNINGS The initialization function must be called only once by the application and before calling any other Vendor API 474 G 1 2 USBD_Vendor_Add Create a new instance of the Vendor class FILES usbd_vendor c PROTOTYPE CPU_INTO8U USBD Vendor Add CPU_BOOLEAN intr_en CPU_INT16U interval USBD_VENDOR_ REQ FNCT req callback USBD_ERR p err ARGUMENTS intr_en Interrupt endpoints IN and OUT flag DEF_TRUE Pair of interrupt endpoints added to interface DEF_FALSE Pair of interrupt endpoints not added to interface interval Endpoint interval in frames or microframes req_callback Vendor specific request callback p err Pointer to variable that
59. address if NO error s 0 otherwise CALLERS Application NOTES WARNINGS None 513 Appendix G G 2 14 USBDev_PipeClose Close a pipe FILES usbdev_api c PROTOTYPE void USBDev_PipeClose HANDLE pipe DWORD ap err ARGUMENTS pipe Pipe handle p err Pointer to variable that will receive the return error code from this function ERROR_SUCCESS ERROR INVALID HANDLE RETURNED VALUE None CALLERS Application NOTES WARNINGS None 514 G 2 15 USBDev_PipeStall Stall a pipe or clear the stall condition of a pipe FILES usbdev_api c PROTOTYPE void USBDev PipeStall HANDLE pipe BOOL stall DWORD p err ARGUMENTS pipe Pipe handle stall Indicate which action to do TRUE Stall pipe FALSE Clear stall condition of the pipe p err Pointer to variable that will receive the return error code from this function ERROR_SUCCESS ERROR INVALID HANDLE ERROR HOT ENOUGH MEMORY RETURNED VALUE None CALLERS Application NOTES WARNINGS The SET_FEATURE standard request is sent to the device to stall the pipe The CLEAR_FEATURE standard request is sent to the device to clear the stall condition of the pipe 515 Appendix G G 2 16 USBDev_PipeAbort Aborts all of the pending transfers for a pipe FILES usbdev_api c PROTOTYPE void USBDev_PipeAbort HANDLE pipe DWORD p err ARGUMENTS pipe Pipe handle p err Pointer to variable that will re
60. and WinUSB_composite inf The USBDev_GUID variable will be passed as a parameter to the function USBDev_Open An handle will be returned by USBDev_Open The application uses this handle to access the device 229 Chapter 12 230 Chapter 13 Debug and Trace pC USB Device provides an option to enable debug traces to output transactional activity via an output port of your choice such as the console or serial port Debugging traces allows you to see how the USB device stack behaves and is a useful troubleshooting tool when trying to debug a problem This chapter will show you the debug and trace tools available in the USB device core as well as how to go about using them 231 Chapter 13 13 1 USING DEBUG TRACES 13 1 1 DEBUG CONFIGURATION There are several configuration constants necessary to customize the core level debugging traces These constants are found in usbd_cfg h and are summarized in Table 13 1 Constant Description USBD_CFG _DBG TRACE EN This constant enables core level debugging traces in the program so that transactional activity can be outputted USBD_CFG DBG TRACE NBR EVENTS This constant configures the size of the debug event pool to store debug events Table 13 1 General Configuration Constants 13 1 2 DEBUG TRACE OUTPUT Core level debug traces are outputted from the debug task handler via an application defined trace function USBD_Trace This function is located in app_us
61. and alternate setting number are specified In the example bulk IN and OUT pipes are part of the default interface Opening an interrupt IN and OUT pipes with USBDev_IntIn Open or USBDev_IntOut_Open is similar to bulk IN and OUT pipes Transferring data on the open pipes can take place now The pipe communication is describes in section 12 3 2 Device Communication on page 218 Close a pipe by passing the associated handle The closing operation aborts any transfer in progress for the pipe and frees any allocated resources Close the device by passing the associated handle The operation frees any allocated resources for this device If a pipe has not been closed by the application this function will close any forgotten open pipes 217 Chapter 12 12 3 2 DEVICE COMMUNICATION SYNCHRONOUS COMMUNICATION Synchronous communication means that the transfer is blocking Upon function call the applications blocks until the end of transfer completed with or without an error A timeout can be specified to avoid waiting forever Listing 12 5 presents a read and write example using a bulk IN pipe and a bulk OUT pipe UCHAR rx _buf 2 UCHAR tx_buf 2 DWORD err void USBDev_PipeRd bulk_in_ handle t1 amp rx_buf 0 2 2u 5000u 3 amp err if err ERROR SUCCESS Handle the error void USBDev_PipeWr bulk_out_handle 1 amp tx_buf 0 4 2u 5000u 3 amp err if err ERROR
62. are created Each class instance is associated with a group of interfaces as opposed to Figure 7 1 and Figure 7 2 where the class instance was associated to a single interface 105 Chapter 7 a Endpoint efault interface IN Interface 0 Alternate 0 Endpoint OUT Endpoint Interface 1 Default interface IN Alternate 0 Endpoint OUT Alternate 1 Alternate 2 Class instance 0 aere Configuration 0 Endpoint Interface 2 Default interface IN Alternate 0 Endpoint OUT Endpoint Interface 3 Default interface IN Alternate 0 Endpoint OUT Alternate 1 Alternate 2 Class instance 1 aere FS device Endpoint Interface 0 efault interface IN Alternate 0 Endpoint OUT Endpoint Default interface IN Alternate 0 Endpoint Alternate 1 Our a Alternate 2 Class instance 0 Endpoint Interface 2 Default interface IN Alternate 0 Endpoint OUT Endpoint Default interface IN Alternate 0 Endpoint Alternate 1 oun y Alternate 2 Class instance 1 Figure 7 3 Multiple Class Instances FS Device 2 Configurations and Multiple Interfaces Interface 1 Configuration 1 Interface 3 The code corresponding to Figure 7 3 is shown in Listing 7 4 The error handling is omitted for cla
63. as reset suspend connect and disconnect are processed by the core task Based on the type of bus event the core task sets the state of the device Process USB requests USB requests are sent by the host using the default control endpoint The core task processes all USB requests Some requests are handled by the USB class driver for those requests the core calls the class specific request handler E Process I O asynchronous transfers Asynchronous I O transfers are handled by the core Under completion the core task invokes the respective callback for the transfer Figure 4 2 shows a simplified task model of 1C USB Device along with application tasks 58 Task Model USB Class API Endpoint I O Operation Bus Events Setup Packet 1 0 Events Application Output Function Device Controller Figure 4 2 uC USB Device Task Model 4 2 1 SENDING AND RECEIVING DATA Figure 4 3 shows a simplified task model of pC USB Device when data is transmitted and received through the USB device controller With pC USB Device data can be sent asynchronously or synchronously In a synchronous operation the application blocks execution until the transfer operation completes or an error or a time out has occurred In an asynchronous operation the application does not block The core task notifies the application when the transfer operation has completed through a callback function 59 Chapter 4 F4 3 1 F4 3
64. blocks of data and status and control information such as a device s capacity and readiness to exchange data The pC USB MSC Device supports the following subset of SCSI Primary and Block Commands detailed in Table 10 3 SCSI Command Function INQUIRY Requests the device to return a structure that contains information about itself A structure shall be returned by the device despite of the media s readiness to respond to other commands Refer to SCSI Primary Commands documentation for the full command description TEST UNIT READY Requests the device to return a status to know if the device is ready to use Refer to SCSI Primary Commands documentation for the full command description READ CAPACITY 10 Requests the device to return how many bytes a device can store Refer to SCSI Block Commands documentation for the full command description READ 10 Requests to read a block of data from the device s storage media Please refer to SCSI Block Commands documentation for the full command description WRITE 10 Requests to write a block of data to the device s storage media Refer to SCSI Block Commands documentation for the full command description VERIFY 10 Requests the device to test one or more sectors Refer to SCSI Block Commands documentation for the full command description MODE SENSE 6 and 10 Requests parameters relating to the storage media logical unit or the device itself Refer to SCSI P
65. c PROTOTYPE static CPU_INT32U USBD_DrvEP_Rx USBD_DRV p drv CPU_INTO8U ep addr CPU_INTO8U p buf CPU_INT32U buf_len USBD_ERR p err ARGUMENTS p drv Pointer to USB device driver structure ep_addr Endpoint address p buf Pointer to data buffer buf len Length of the buffer p err Pointer to variable that will receive the return error code from this function RETURNED VALUE Number of octets received if NO error s 0 otherwise CALLERS E USBD_EP Rx via p drv _api gt EP_Rx E USBD_EP Process 339 Appendix B NOTES WARNINGS Typically the receive from endpoint function performs the following operations 340 Check if packet has been received and is ready to be read Determine packet length If packet length is greater than buf _len then copy the first buf len octets into p_buf Otherwise copy the entire packet into p_buf Clear endpoint buffer to allow next packet to be received For some controllers this may not be necessary B 1 13 USBD_DrvEP_RxZLP Receive zero length packet from endpoint FILES Every device driver s usbd_drv c PROTOTYPE static void USBD DrvEP_RxZLP USBD_DRV Sp drv CPU_INTO8U ep addr USBD_ERR p err ARGUMENTS p drv Pointer to USB device driver structure ep_addr Endpoint address p err Pointer to variable that will receive the return error code from this function RETURNED VALUE None CALLERS USBD_EP_RXZLP via p_drv_api gt
66. data_opaque_ buf 2 data opaoue but Len latency rely 3 nbr_xfer 4 0 5 p_err for i 0 i lt nbr xfer i 6 Prepare data to send xfer_len USBD_PHDC Wr class_nbr 1 void p buf 7 buf_len latency rely 3 0 p_err Listing 11 3 PHDC Write Procedure L11 3 1 The class instance number obtained with USBD_PHDC Add will serve internally to the PHDC class to route the data to the proper endpoints L11 3 2 Buffer that contains opaque data L11 363 Latency reliability QoS of the following transfer s L11 3 4 Variable that contains the number of following transfers to which this preamble will apply L11 365 In order to avoid infinite blocking situation a timeout expressed in milliseconds can be specified A value of 0 makes the application task wait forever 111 3 Write all the USB transfers to which the preamble will apply L11 3 7 Buffer that contains the data 195 Chapter 11 11 3 2 COMMUNICATION WITHOUT METADATA PREAMBLE If device does not support metadata preamble or if it supports them but it has not been enabled by the host you should not call USBD_PHDC RdPreamble and USBD_PHDC_WrPreamble 11 4 RTOS QOS BASED SCHEDULER Since it is possible to send data with different QoS using a single bulk endpoint you might want to prioritize the transfers by their QoS latency medium latency transfers processed before high latency transfers for instance This
67. dedicated USB memory region the buffered data must be transferred into the application buffer area On FIFO based controllers this device driver API is responsible for reading the amount of data received by copying it into the application buffer area and returning the data back to its caller The device receive operation iterates through the process until the amount of data received matches the amount requested or a short packet is received USB Device Driver Functional Model 6 8 2 DEVICE ASYNCHRONOUS RECEIVE The device asynchronous receive operation is initiated by the calls USBD_BulkRxAsync and USBD_IntrRxAsync Figure 6 2 shows an overview of the device asynchronous receive operation USBD_EP_Rx ES WS S A ey Core Task H a Geen EP_RxCmpl S USBD_DrvEP_RxStart Wa ER at lt lt 7 E m b 4 A Receive Complete Callback 6 lt Device ISR Handler L USBD_DrvEP_Rx USB Device A A K fp Interrupt s 2 5 N USBD_DrvEP_RxStart K D Figure 6 2 Device Asynchronous Receive Diagram F6 2 1 The upper layer API s USBD_BulkRxAsync and USBD_IntrRxAsync call USBD_EP_Rx passing a receive complete callback function as an argument In USBD_EP_Rx the USBD_DrvEP_RxStart function is invoked in the same way as for the synchronous operation On DMA based controllers this device driver API is responsible for queuing
68. device configuration structure configuration complex composite high speed USB device 76 composite high speed USB device constants constants CDC constants HID class constants MS class constants PHDC constants Vendor class device device application device controller driver driver error codes examples functions HID class interface MS class as PC and device applications simple full speed USB device static stack string USB device a USB device controller driver Vendor class Conni GE constants CDC HID class MS class PHDC Vendor class control transfer stages control exe core events management core layer porting Core OS FUNCTIONS E core OS port API core task CPU layer CPU support D data characteristics cecceceeeeeseeeeeeeeeeeeeeeeeseeeteeeeeeee 184 data flow model eeceeeceeeeeeeeeeeeeeceaeeeaeeeeaeeeaeeeeeeeeeeenaees 17 debug configuration event pool event ee events management format na se 233 processing events sample output trace output traces tracing macros debug macros demo application CDC eegene composite device configuration constants files HID class MS class PHDC single device Vendor class detect a specific HID device A 156 154 200 203 220 129 device application conf
69. device has a device ID for each interface that represents a function A device ID for an interface has the following form USB Vid_xxxx amp Pid_yyyy amp MI_ww 49 Chapter 3 ww is equal to the bInterfaceNumber field in the Interface descriptor refer to the Universal Serial Bus Specification revision 2 0 section 9 6 5 for more details on the Interface descriptor fields You can modify ww to match the position of the interface in the Configuration descriptor If the interface has the position 2 in the Configuration descriptor ww is equals to 02 The Strings section contains a description of your device In Listing 3 1 the strings define the name of the device driver package provider and the device name You can see these device description strings in the Device Manager For instance Figure 3 1 shows a virtual COM port created with the INF file from Listing 3 1 The string Micrium appears under the Driver Provider name in the device properties The string Micrium CDC Device appears under the Ports group and in the device properties dialog box aay Device Manager e BR X File Action View Help C AE P RS 4 RPC a z 1 E Computer Micrium CDC Device COM15 Properties Disk drives CH Ca a E Display adapters General Port Settings Driver Details D x i a CD dimes Micrium CDC Device COM15 Ellisys protocol analyzers s a 05 Human Interface Devices D HI
70. device is plugged again to the host 7 3 CLASS AND CORE LAYERS INTERACTION THROUGH CALLBACKS Upon reception of standard class specific and or vendor requests the Core layer can notify Class and Core Layers Interaction through Callbacks the Class layer about the event associated with the request via the use of class callbacks Each Micrium class must define a class callbacks structure of type USBD_CLASS DRV that contains function pointers Each callback allows the class to perform a specific action if it is required Listing 7 7 shows a generic example of class callback structure In the listing XXXX could be replaced with CDC HID MSC PHDC or Vendor static USBD CLASS DRV USBD_XXXX_ Drv USBD_XXXX_Conn 1 USBD_XXXX_Disconn 2 USBD_XXXX_UpdateAltSetting 3 USBD_XXXX_UpdateEPState 4 USBD_XXXX_IFDesc 5 USBD_XXXX_IFDescGetSize 6 USBD_XXXX_EPDesc 7 USBD_XXXX_EPDescGetSize 8 USBD_XXXX_IFReq 9 USBD_XXXX_ClassReq 10 USBD_XXXX_VendorReq 11 L7 7 1 L7 7 2 L7 7 3 L7 7 4 L7 7 5 L7 7 6 17 77 Listing 7 7 Class Callback Structure Notify the class that a configuration has been activated Notify the class that a configuration has been deactivated Notify the class that an alternate interface setting has been updated Notify the class that an endpoint state has been updated by the host The state is generally stalled or not stalled Ask the class to build th
71. following interfaces E Communications Class Interface CCI E Data Class Interface DCI A CCI is responsible for the device management and optionally the call management The device management enables the general configuration and control of the device and the notification of events to the host The call management enables calls establishment and termination Call management might be multiplexed through a DCI A CCI is mandatory for all CDC devices It identifies the CDC function by specifying the communication model supported by the CDC device The interface s following the CCI can be any defined USB class interface such as Audio or a vendor specific interface The vendor specific interface is represented specifically by a DCI A DCI is responsible for data transmission The data transmitted and or received do not follow a specific format Data could be raw data from a communication line data following a proprietary format etc All the DCIs following the CCI can be seen as subordinate interfaces 116 A CDC device must have at least one CCI and zero or more DCIs One CCI and any subordinate DCI together provide a feature to the host This capability is also referred to as a function In a CDC composite device you could have several functions Hence the device would be composed of several sets of CCI and DCI s as shown in Figure 8 1 Overview CDC Device Function 1 Function 2 Function 3
72. from this function RETURNED VALUE None CALLERS USBD_PHDC Wr USBD_PHDC WrPreamble 469 Appendix F IMPLEMENTATION GUIDELINES Two typical implementations will be possible here The first one consists in pending on a semaphore that locks the write bulk pipe just as we saw previously But since different QoS data can travel using a single bulk IN endpoint you might want to prioritize them in function of the QoS See section 11 4 RTOS QoS based scheduler on page 196 for more details on how a priority manager can be implemented p_err argument should be assigned as described in Table F 1 470 F 2 7 USBD_PHDC_OS WrBulkUnLock Unlock the write bulk pipe FILES usbd_phdc_os h usbd_phdc_os c PROTOTYPE void USBD_PHDC_OS WrBulkUnlock CPU_INTO8U class_nbr ARGUMENTS class_nbr PHDC instance number RETURNED VALUE None CALLERS USBD_PHDC_Wr IMPLEMENTATION GUIDELINES Two typical implementations will be possible here The first one consists in posting the semaphore that locks the write bulk pipe if no priority management is implemented However if priority management has been integrated this call should release the scheduler See Section 11 4 RTOS QoS based scheduler on page 196 471 Appendix F 472 Appendix Vendor Class API Reference This appendix provides a reference to the Vendor class API Each user accessible service is presented following
73. greatly depends on your application Also the device configuration is related to your product s context and the device controller driver configuration depends on the hardware you use The examples of typical usage that will be treated are the following E A simple full speed USB device This device uses Micrium s vendor class E A composite high speed USB device This device uses Micrium s PHDC and MSC classes E A complex composite high speed USB device This device uses an instance of Micrium s HID class in two different configurations plus a different instance of Micrium s CDC ACM class in each configuration This device also uses an instance of Micriym s vendor class in the second configuration 71 Chapter 5 5 4 1 SIMPLE FULL SPEED USB DEVICE Table 5 1 shows the values that should be set for the different configuration constants described earlier if you build a simple full speed USB device using Micripm s vendor class Configuration Value Explanation USBD_CFG MAX NBR_CFG 1 Since device is full speed only one configuration is needed USBD_CFG MAX NBR_IF 1 Since device only uses the vendor class only one interface is needed USBD_CFG MAX NBR_IF ALT 1 No alternate interfaces are needed but this value must at least be equal to USBD_CFG_MAX NBR IF USBD_CFG MAX NBR_IF_ GRP 0 No interface association needed USBD_CFG MAX NBR EP DESC 2or4 Two bulk endpoints and two optional interrupt endpo
74. in the core event queue In asynchronous transfers the core task will call the endpoint layer until the operation is completed F4 3 8 In asynchronous mode after the transfer has completed the core task will call the application completion callback to notify the end of the I O operation 4 2 2 PROCESSING USB REQUESTS AND BUS EVENTS USB requests are processed by the core task Figure 4 4 shows a simplified task diagram of a USB request processing USB bus events such as reset resume connect disconnect and suspend are processed in the same way as the USB requests The core process the USB bus events to modify and update the current state of the device 61 Chapter 4 F4 4 1 F4 4 2 F4 4 3 F4 4 4 F4 4 5 62 5 Standard Request Handler Request Handler Class Request Handler 2 gt T gt Setup Packet ISR J 1 Controller 4 I USB Device Figure 4 4 Processing USB Requests USB requests are sent using control transfers During the setup stage of the control transfer the USB device controller generates an interrupt to notify the driver that a new setup packet has arrived The USB device controller driver ISR notifies the core by pushing the event in the core event queue The core task receives the message from the queue and starts the parsing of the USB request by calling the request handler The request handler analyzes the request type and determines if the request is a stan
75. kind of prioritization is implemented inside PHDC uC OS II and pC OS III RTOS layer Table 11 9 shows the priority value associated with each QoS latency the lowest priority value will be treated first QoS latency QoS based scheduler associated priority Very high latency 3 High latency 2 Medium latency 1 Table 11 9 QoS Based Scheduler Priority Values For instance let s say that your application has 3 tasks Task A has an OS priority of 1 task B has an OS priority of 2 and task C has an OS priority of 3 Note that a low priority number indicates a high priority task Now say that all 3 tasks want to write PHDC data of different QoS latency Task A wants to write data that can have very high latency task B wants to write data that can have medium latency and finally task C wants to write data that can have high latency Table 11 10 shows a summary of the tasks involved in this example Task pris of data to OS priority ld of data to A Very high 1 3 Medium 2 1 C High 3 2 Table 11 10 QoS Based Scheduling Example 196 RTOS QoS based scheduler If no QoS based priority management is implemented the OS will then resume the tasks in the order of their OS priority In this example the task that has the higher OS priority A will be resumed first However that task wants to write data that can have very high latency QoS priority of 3 A better choice would be to resume task B first which wants to send
76. needs to initialize and configure the class to suit its needs Table 11 6 summarizes the initialization functions provided by the PHDC implementation For a complete API reference see section F 1 PHDC Functions on page 442 Function name Operation USBD_PHDC_Init Initializes PHDC internal structures and variables USBD_PHDC_Add Adds a new instance of PHDC USBD_PHDC_RdCfg Configures read communication pipe parameters USBD_PHDC_WrCfg Configures write communication pipe parameters USBD_PHDC_11073 ExtCfg Configures 11073 function extension s USBD_PHDC_CfgAdd Adds PHDC instance into USB device configuration Table 11 6 PHDC Initialization API Summary You need to follow these steps to successfully initialize PHDC 1 Call USBD_PHDC_Init This is the first function you should call and you should do it only once even if you use multiple class instances This function will initialize all internal structures and variables that the class will need It will also initialize the real time operating system RTOS layer Call USBD_PHDC_Add This function will allocate a PHDC instance This call will also let you determine if the PHDC instance is capable of sending receiving metadata message preamble and if it uses vendor defined or ISO IEEE 11073 based data and messaging protocol Another parameter of this function lets you specify a callback function that the class will call when h
77. operations 56 Modules Relationship 4 1 6 REAL TIME OPERATING SYSTEM RTOS ABSTRACTION LAYER uC USB Device assumes the presence of a RTOS and a RTOS abstraction layer allows uC USB Device to be independent of a specific RTOS The RTOS abstraction layer is composed of several RTOS ports a core layer port and some class layer ports CORE LAYER PORT At the very least the RTOS for the core layer E Create at least one task for the core operation and one optional task for the debug trace feature E Provide semaphore management or the equivalent Semaphores are used to signal completion or error in synchronous I O operations and trace events E Provide queue management for I O and bus events pC USB Device is provided with ports for pC OS II and pC OS III If a different RTOS is used you can use the files for uC OS II or pC OS II as template to interface to the RTOS chosen For more information on how to port uC USB Device to a RTOS see Chapter 14 Porting uC USB Device to your RTOS on page 237 CLASS LAYER PORTS Some classes requires a RTOS port G e MSC PHDC and HID Refer to Table 14 2 on page 239 for a list of sections containing more informations on the RTOS port of each of these classes 4 1 7 HARDWARE ABSTRACTION LAYER pC USB Device works with nearly any USB device controller This layer handles the specifics of the hardware e g how to initialize the device how to open and configure endpoints how to
78. p err ARGUMENTS dev General handle to device p err Pointer to variable that will receive the return error code from this function ERROR_SUCCESS ERROR INVALID HANDLE RETURNED VALUE None CALLERS Application NOTES WARNINGS USBDev_Close closes any remaining open pipes The open pipes are usually closed from the application by calling the function USBDev_PipeClose 500 G 2 4 USBDev_GetNbrAltSetting Get number of alternate settings for the specified interface FILES usbdev_api c PROTOTYPE UCHAR USBDev_GetNbrAltSetting HANDLE dev UCHAR if nbr DWORD p err ARGUMENTS dev General handle to device if_nbr Interface number p err Pointer to variable that will receive the return error code from this function ERROR_SUCCESS ERROR INVALID HANDLE ERROR INVALID PARAMETER RETURNED VALUE Number of alternate setting if NO error s 0 otherwise CALLERS Application 501 Appendix G NOTES WARNINGS An interface may include alternate settings that allow the endpoints and or their characteristics to be varied after the device has been configured The default setting for an interface is always alternate setting zero Alternate settings allow a portion of the device configuration to be varied while other interfaces remain in operation The number of alternate settings gotten can be used to open a pipe associated with a certain alternate interface 502 G 2 5 USBDev_GetNbrA
79. s 246 A 1 2 USBD_DevStart Starts device stack This function connects the device to the USB host FILES usbd_core h usbd_core c PROTOTYPE void USBD_DevStart CPU_LINTO08U dev_nbr USBD_ERR p err ARGUMENTS dev_nbr Device number p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_ DEV INVALID NBR USBD_ERR DEV INVALID STATE RETURNED VALUE None CALLERS Application NOTES WARNINGS Device stack can be only started if the device is in either the USBD_DEV_STATE NONE or USB_DEV_ STATE INIT states 247 Appendix A A 1 3 USBD_DevStop Stops device stack This function disconnects the device from the USB host FILES usbd_core h usbd_core c PROTOTYPE void USBD_DevStop CPU_INTO8U dev_nbr USBD_ERR ap err ARGUMENTS dev_nbr Device number p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_ DEV INVALID NBR USBD_ERR DEV INVALID STATE RETURNED VALUE None CALLERS Application NOTES WARNINGS None 248 A 1 4 USBD_DevGetState Gets current device state FILES usbd_core h usbd_core c PROTOTYPE USBD_DEV_STATE USBD DevGetState CPU_INTO08U dev_nbr USBD ERR p err ARGUMENTS dev_nbr Device number p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_ DEV INVALID NBR RETURNED
80. setup class System defined setup class GUIDs are defined in devguid h The device setup class GUID defines the CurrentControlSet Control Class ClassGuid registry key under which to create a new subkey for any particular device of a standard setup class A complete list of system defined device setup classes offered by Microsoft Windows is available on MSDN online documentation http msdn microsoft com en us library windows hardware f 553426 v vs 85 aspx A device interface class GUID provides a mechanism for applications to communicate with a driver assigned to devices in a class A class or device driver can register one or more device interface classes to enable applications to learn about and communicate with devices that use the driver Each device interface class has a device interface GUID Upon a device s first attachment to the PC the Windows I O manager associates the device and the device interface class GUID with a symbolic link name also called a device path The device path is stored in the registry and persists across system reboot An application can retrieve all the connected devices within a device interface class If the application has gotten a device path for a connected device this device path can be passed to a function that will return a handle This handle is passed to other functions in order to communicate with the corresponding device Three of Micrium s USB classes are provided with Visual Studio 2010 proj
81. should be set to 1 USBD_MSC_CFG MAX NBR_CFG Configures the maximum number of configuration in which MSC is used Keep in mind that if you use a high speed device two configurations will be built one for full speed and another for high speed USBD_MSC_CFG MAX LUN Configures the maximum number of logical units This value must be at least 1 USBD_MSC_CFG DATA LEN Configures the read write data length in octets The default value set is 2048 Table 10 4 MSC Configuration Constants Since MSC device relies on a task handler to implement the MSC protocol this OS task s priority and stack size constants need to be configured These constants are summarized in Table 10 5 Constant Description USBD_MSC_OS_CFG_TASK_PRIO MSC task handler s priority level The priority level must be lower higher valued than the start task and core task priorities USBD MSC OS CFG TASK STK SIZE MSC task handler s stack size Default value is set to 256 Table 10 5 MSC OS Task Handler Configuration Constants 173 Chapter 10 10 4 2 CLASS INSTANCE CONFIGURATION Before starting the communication phase your application needs to initialize and configure the class to suit its needs Table 10 6 summarizes the initialization functions provided by the MSC implementation Please refer to section E 1 Mass Storage Class Functions on page 420 for a full listing of the MSC API Function name Operation USBD_MSC_Init
82. subclass instance number line coding chngd Line coding change notification callback see Note 1 p arg Pointer to callback argument p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_INVALID ARG RETURNED VALUE None CALLERS Application 383 Appendix C NOTES WARNINGS E The callback specified by Line coding _chngd argument is used to notify changes in the control signals to the application The line control notification function has the following prototype CPU_BOOLEAN AppLineCodingChngd CPU_INTO8U subclass_nbr p line coding void p_arg Arguments subclass obt CDC ACM serial emulation subclass instance number p_line coding Pointer to line coding structure p arg Pointer to callback argument Returned value DEF OR If line coding is supported by the application DEF_FAIL Otherwise 384 C 2 12 USBD_ ACM SerialLineStateSet Set one or several line state events FILES usbd_acm_serial h usbd_acm_serial c PROTOTYPE CPU_BOOLEAN USBD_ACM SerialLineStateSet CPU_INT08U subclass _nbr CPU_INTO8U events ARGUMENTS subclass nbr CDC ACM serial emulation subclass instance number events Line state event s to set USBD_ACM SERIAL STATE DCD DCD Rx carrier USBD_ACM SERIAL STATE DSR DSR Tx carrier USBD_ACM SERIAL STATE BREAK Break USBD ACM SERIAL STATE RING Ring USBD_ACM SERIAL STATE FRAMINGFraming error USBD_ACM SERIAL S
83. telling to Windows how to install one or several drivers for one or more devices Refer to section 3 1 1 About INF Files on page 46 for more details about INF file use and format The Vendor class includes two INF files located in Micrium Software uC USB Device V4 App Host 0S Windows Vendor INF E WinUSB single inf used if the device presents only one Vendor class interface E WinUSB_composite inf used if the device presents at least one Vendor class interface along with another interface The two INF files allows you to load the WinUSB sys driver provided by Windows WinUSB_single inf defines this default hardware ID string USB VID_FFFES amp PID_ 1003 While WinUSB_composite inf defines this one USB VID_FFFE amp PID 1001 amp MI_00 The hardware ID string contains the Vendor ID VID and Product ID PID In the default strings the VID is FFFE and the PID is either 1003 or 1001 The VID PID values should match the ones from the USB device configuration structure defined in usb dev _cfg c Refer to section Modify Device Configuration on page 34 for more details about the USB 222 Using the Demo Application device configuration structure If you want to define your own VID PID you must modify the previous default hardware ID strings with your VID PID In the case of a composite device formed of several vendor interfaces in order to load WinUSB sys for each vendor interface the manufacturer section in WinUSB_compos
84. that should be resumed Task C is resumed F11 4 7 Task C has completed its execution and releases the lock Scheduler task is resumed and determines that task A is the next one to be resumed The QoS based scheduler is implemented in the RTOS layer Three functions are involved in the execution of the scheduler Function name Called by Operation USBD_PHDC_OS_WrBulkLock USBD_PHDC_Wr or Locks write bulk pipe USBD_PHDC_WrPreamble depending if preambles are enabled or not USBD_PHDC_OS_WrBulkUnlock USBD_PHDC_Wr Unlocks write bulk pipe USBD_PHDC_OS_WrBulkSchedTask N A Determines next task to resume Table 11 11 QoS Based Scheduler API Summary Pseudocode for these three functions are shown in Listing 11 4 Listing 11 5 and Listing 11 6 198 RTOS QoS based scheduler void USBD_PHDC_OS WrBulkLock CPU_INTO8U class_nbr CPU_INTO8U prio CPU_INT16U timeout_ms USBD_ERR p err Increment transfer count of given priority QoS Post scheduler lock semaphore Pend on priority specific semaphore Decrement transfer count of given priority QoS Listing 11 4 Pseudocode of USBD_PHDC_OS_WrBulkLock void USBD_PHDC_OS_WrBulkUnlock CPU_INTO08U class_nbr Post scheduler release semaphore Listing 11 5 Pseudocode of USBD_PHDC_OS_WrBulkUnlock static void USBD_PHDC_OS WrBulkSchedTask void p_arg Pend on scheduler lock semaphore Get next highest QoS ready PostSem Se
85. transfer can take all of the available bus bandwidth Bulk transfers are reliable as error detection and retransmission mechanisms are implemented in hardware to guarantee data integrity However bulk transfers offer no guarantee on timing Printers and mass storage devices are examples of devices that use bulk transfers INTERRUPT TRANSFERS Interrupt transfers are designed to support devices with latency constrains Devices using interrupt transfers can schedule data at any time Devices using interrupt transfer provides a polling interval which determines when the scheduled data is transferred on the bus Interrupt transfers are typically used for event notifications ISOCHRONOUS TRANSFERS Isochronous transfers are used by devices that require data delivery at a constant rate with a certain degree of error tolerance Retransmission is not supported by isochronous transfers Audio and video devices use isochronous transfers USB DATA FLOW MODEL Table 1 2 shows a graphical representation of the data flow model 19 Chapter 7 Physical 1 D Software Hardware Gi I I 1 bt Device control ER and eal I Hardware Q i Software O 1 I 1 Lt S Device standard request Software USB cable Application Software Application EP Ess ae Function B Device Controller Host Software Host controller Device Firmware Figure 1 2 USB data flow F1 2 1 The host software uses standar
86. transfers E Manage core events E Manage debug events optional 14 3 1 SYNCHRONOUS TRANSFER COMPLETION SIGNALS The core layer needs a way to signal the application about the synchronous transfer completion The core will need one signal per endpoint The RTOS resources usually used for this signal is a semaphore Figure 14 2 describes a synchronous transfer completion notification Application task Task 2 Task Synchronous 1 3 transfer Device controller signal transfer completion Figure 14 2 Synchronous transfer completion notification F14 2 1 Application task calls a synchronous transfer function F14 2 2 While the transfer is in progress the application task pends on the transfer completion signal F14 2 3 Once the transfer is completed the core will post the transfer completion signal which will resume the application task 240 Core Layer RTOS Model 14 3 2 CORE EVENTS MANAGEMENT For proper operation the core layer needs an OS task that will manage the core events For more information on the purpose of this task or on what a core event is refer to section 4 2 Task Model on page 58 The core events must be queued in a data structure and be processed by the core This allows the core to process the events in a task context instead of in an ISR context as most of the events will be raised by the device driver s ISR The core task also needs to be
87. transmitting the data This invokes the USB device driver interrupt service routine ISR handler directly or indirectly depending on the architecture Inside the USB device driver ISR handler the type of interrupt request is determined as a transmit interrupt USBD_EP_TxCmpl is called to queue the endpoint that had its transfer completed On DMaA based controllers the transmit transfer is de queued from the list of completed transfers The core task de queues the endpoint that completed a transfer If the overall amount of data transmitted is less than the amount requested USBD_DrvEP_Tx and USBD_DrvEP_TxStart are called to transmit the remaining amount of data The device transmit operation finishes when the amount of data transmitted matches the amount requested The transmit complete callback is invoked to notify the application about the completion of the process USB Device Driver Functional Model 6 8 5 DEVICE SET ADDRESS The device set address operation is performed by the setup transfer handler when a SET ADDRESS request is received Figure 6 5 shows an overview of the device set address operation F6 5 1 F6 5 2 F6 5 3 Setup Transfer Set Address 1 j USBD_DrvAddrSet wi Ss a a Ra etup Transfer Tx SE 3 e USBD_DrvAddrEn A RK Figure 6 5 Device Set Address Diagram Once the arguments of the setup request are validated USBD_DrvAddrSet is
88. usbd_phdc_os h usbd_phdc_os c PROTOTYPE void USBD_PHDC OS WrIntrLock CPU_INTO8U class_nbr CPU_INT16U timeout USBD_ERR p err ARGUMENTS class_nbr PHDC instance number timeout Timeout p err Pointer to variable that will receive the return error code from this function RETURNED VALUE None CALLERS USBD_PHDC Wr IMPLEMENTATION GUIDELINES Typical implementation will consist in pending on a semaphore that locks the write interrupt pipe p err argument should be assigned as described in Table F 1 467 Appendix F F 2 5 USBD_PHDC_OS WrintrUnLock Unlock the write interrupt pipe FILES usbd_phdc_os h usbd_phdc_os c PROTOTYPE void USBD_PHDC_OS WrIntrUnlock CPU_INTO8U class_nbr ARGUMENTS class_nbr PHDC instance number RETURNED VALUE None CALLERS USBD_PHDC_Wr IMPLEMENTATION GUIDELINES Typical implementation will consist in posting a semaphore that locks the write interrupt pipe 468 F 2 6 USBD_PHDC_OS WrBulkLock Lock the write bulk pipe FILES usbd_phdc_os h usbd_phdc_os c PROTOTYPE void USBD_PHDC_OS WrBulkLock CPU_INTO8U class_nbr CPU_INTO8U prio CPU_INT16U timeout USBD ERR p err ARGUMENTS class_nbr PHDC instance number prio Priority of the transfer This value is between 0 and 4 and is computed in function of the transfer s QoS by the caller timeout Timeout p err Pointer to variable that will receive the return error code
89. 010 Debug ully Opened HID Compliant Device i Menu i Read from Device Write to Device Exit Enter the Choice 1 Last 4 Bytes Received From Device 246 8 t ttttttt t i Menu i Read from Device Write to Device Exit Enter the Choice 2 Sent 4 Bytes to Device 16 26 36 40 Figure 9 6 HID Interrupt exe Vendor Specific Demo 159 Chapter 9 9 5 PORTING THE HID CLASS TO A RTOS The HID class uses its own RTOS layer for different purposes E A locking system is used to protect a given Input report A host can get an Input report by sending a GET_REPORT request to the device using the control endpoint or with an interrupt IN transfer GET_REPORT request processing is done by the device stack while the interrupt IN transfer is done by the application When the application executes the interrupt IN transfer the Input report data is stored internally This report data stored will be sent via a control transfer when GET_REPORT is received The locking system ensures the data integrity between the Input report data storage operation done within an application task context and the GET_REPORT request processing done within the device stack s internal task context m A locking system is used to protect the Output report processing between an application task and the device stack s internal task when the control endpoint is used The application provides to the
90. 09 Chapter 7 F7 4 1 F7 4 2 F7 4 110 Figure 7 4 Class State Machine A class instance has been added to a configuration the class instance state transitions to the Init state No data communication on the class endpoint s can occur yet The host has sent the SET CONFIGURATION request to activate a certain configuration The Core layer calls a class callback informing about the completion of the standard enumeration The class instance state transitions to the Cfg state This state indicates that the device has transitioned to the Configured state defined by the Universal Serial Bus Specification revision 2 0 The data communication may begin Some classes such as the MSC class may require that the host sends some class specific requests before the communication on the endpoints really starts The Core layer calls another class callback informing that the host has sent a SET CONFIGURATION request with a new configuration number or with the value 0 indicating a configuration reset or that the device has been physically disconnected from the host In all these cases the current active configuration becomes inactive The class instance state transitions to the Init state Any ongoing transfers on the endpoints managed by the class instance have been aborted by the Core layer No more communication is possible until the host sends a new SET_CONFIGURATION request with a non null value or until the
91. 16U max kt size CPU_LINTO8U transaction frame USBD_ERR p err ARGUMENTS D drv Pointer to USB device driver structure ep_addr Endpoint address ep_type Endpoint type USB_EP TYPE CTRL USB_EP TYPE ISOC USB_EP_ TYPE BULK USB_EP TYPE INTR max Dkt size Maximum packet size transaction frame Endpoint transactions per frame p err Pointer to variable that will receive the return error code from this function RETURNED VALUE None 334 CALLERS E USBD_EP Open via p drv_api gt EP_Open E USBD_CtrlOpen NOTES WARNINGS P Typically the endpoint open function performs the following operations Validate endpoint address type and maximum packet size Configure endpoint information in the device controller This may include not only assigning the type and maximum packet size but also making certain that the endpoint is successfully configured or realized or mapped For some device controllers this may not be necessary E If the endpoint address is valid then the endpoint open function should validate the attributes allowed by the hardware endpoint max pkt_size is the maximum packet size the endpoint can send or receive The endpoint open function should validate the maximum packet size to match hardware capabilities 335 Appendix B B 1 10 USBD_DrvEP Close Close a device endpoint and un initialize clear endpoint configuration in hardware FILES Every device driver s usbd_drv c PROT
92. 16U timeout USBD_ERR p err ARGUMENTS class_nbr CDC instance number data _if_nbr CDC data interface number p_buf buf_len timeout_ms p_err Pointer to buffer of data that will be transmitted Number of octets to transmit Timeout in milliseconds Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_INVALID ARG USBD_ ERR INVALID CLASS STATE USBD_ERR_ DEV INVALID NBR USBD_ERR_ DEV INVALID STATE USBD_ERR_ EP INVALID ADDR USBD_ERR_EP INVALID STATE USBD_ERR_ EP INVALID TYPE 365 Appendix C USBD_ERR_OS TIMEOUT USBD_ERR_OS ABORT USBD_ERR_OS FAIL RETURNED VALUE Numbers of octets transmitted if no errors 0 otherwise CALLERS CDC Subclass drivers NOTES WARNINGS None 366 C 1 8 USBD CDC Notify Send communication interface class notification to the host FILES usbd_cde h usbd_cdce c PROTOTYPE CPU_BOOLEAN USBD_CDC Notify CPU_INT08U class_nbr CPU_LINTO8U notification CPU_INT16U value CPU_INTO8U p buf CPU_INT16U data_len USBD_ERR p err ARGUMENTS class nbr CDC instance number notification Notification code see Note 1 value Notification value see Note 1 p_buf Pointer to notification buffer see Note 2 data_len Notification s data section length p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_INVALID ARG USBD_ ERR INV
93. 2 F4 3 3 60 App Task 7 EE Application Callback USB Events Queue 5 Transfer Ready Semaphore Steeg Asynchronous UO e Datapath Synchronous UO Datapath Universal Serial Bus Figure 4 3 Sending and Receiving a Packet An application task that wants to receive or send data interfaces with pC USB Device through the USB classes API The USB classes API interface with the core API and the core interfaces with the endpoint layer API The endpoint layer API prepares the data depending on the endpoint characteristics When the USB device controller is ready the driver prepares the transmission or the reception Task Model F4 3 4 Once the transfer has completed the USB device controller generates an interrupt Depending of the operation transmission or reception the USB device controller s driver ISR invokes the transmit complete or receive complete function from the core F4 3 5 If the operation is synchronous the transmit or receive complete function will signal the transfer ready counting semaphore If the operation is asynchronous the transmit or receive complete function will put a message in the USB core event queue for deferred processing by the USB core task F4 3 6 If the operation is synchronous the endpoint layer will wait on the counting semaphore The operation repeats steps 2 to 5 until the whole transfer has completed F4 3 7 The core task waits on events to be put
94. 2U buf len USBD_ERR p err ARGUMENTS p drv Pointer to USB device driver structure ep_addr Endpoint address p buf Pointer to data buffer buf len Length of the buffer p err Pointer to variable that will receive the return error code from this function RETURNED VALUE Number of octets transmitted if NO error s 0 otherwise 344 CALLERS E USBD EP Tx via p drv_api gt EP_TxStart E USBD_EP Process NOTES WARNINGS Typically the function to configure the endpoint receive transaction performs the following operations E Trigger packet transmission 345 Appendix B B 1 16 USBD_DrvEP_TxZLP Transmit zero length packet to endpoint FILES Every device driver s usbd_drv c PROTOTYPE static void USBD DrvEP_TxZLP USBD_DRV p dru CPU_INTO8U ep addr USBD_ERR p err ARGUMENTS p drv Pointer to USB device driver structure ep_addr Endpoint address p err Pointer to variable that will receive the return error code from this function RETURNED VALUE None CALLERS E USBD_EP Tx via p drv _api gt EP_TXZLP E USBD_ EP TXZLP E PD EP Process NOTES WARNINGS None 346 B 1 17 USBD_DrvEP_Abort Abort any pending transfer on endpoint FILES Every device driver s usbd_drv c PROTOTYPE static CPU_BOOLEAN USBD DrvEP Abort USBD Du p drv CPU_INTO8U ep addr ARGUMENTS p drv Pointer to USB device driver structure ep_addr Endpoint Address
95. 479 Appendix G NOTES WARNINGS USBD_ Vendor IsConn is typically used to verify that the device is in configured state and that the vendor class instance is ready for communication The following code illustrates a typical example CPU_BOOLEAN conn conn USBD_Vendor_IsConn class_nbr while conn DEF YES OSTimeDlyHMSM 0 0 0 250 conn USBD_Vendor_IsConn class_nbr Once the connected status is DEF_YES the communication using the Bulk endpoints can start 480 G 1 5 USBD Vendor Rd Receive data from host through Bulk OUT endpoint This function is blocking FILES usbd_vendor c PROTOTYPE CPU_INT32U USBD Vendor Rd CPU_INTO8U class nr void p buf CPU_INT32U buf len CPU_INT16U timeout USBD_ERR p err ARGUMENTS class_nbr p_ but buf_len timeout p err Class instance number Pointer to receive buffer Receive buffer length in octets Timeout in milliseconds Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_NULL PTR USBD_ERR_INVALID ARG USBD_ERR_ INVALID CLASS STATE USBD_ERR_ DEV INVALID NBR USBD_ERR_ EP INVALID NBR USBD_ERR DEV INVALID STATE USBD_ERR_EP INVALID TYPE 481 Appendix G RETURNED VALUE Number of octets received if NO error s 0 otherwise CALLERS Application NOTES WARNINGS None 482 G 1 6 USBD_Vendor_Wr Send data to host through Bulk IN endp
96. 6 1 7 L6 1 8 L6 1 9 L6 1 10 L6 1 11 L6 1 12 16 113 LO 1 14 L6 1 15 L6 1 16 16 117 L6 1 18 L6 1 19 Device Driver API Device initialization add Device start Device stop Assign device address Enable device address Set device configuration Clear device configuration Retrieve frame number Open device endpoint Close device endpoint Configure device endpoint to receive data Receive from device endpoint Receive zero length packet from device endpoint Configure device endpoint to transmit data Transmit to device endpoint Transmit zero length packet to device endpoint Abort device endpoint transfer Stall device endpoint Device interrupt service routine GSR handler 79 Chapter 6 The details of each device driver API function are described in Appendix B Device Controller Driver API Reference on page 323 Note pC USB Device device driver API function names may not be unique Name clashes between device drivers are avoided by never globally prototyping device driver functions and ensuring that all references to functions within the driver are obtained by pointers within the API structure The developer may arbitrarily name the functions within the source file so long as the API structure is properly declared The user application should never need to call API functions Unless special care is taken calling device driver functions may lead to unpredictable results due t
97. 6 4 3 Device release number L6 4 4 Pointer to manufacturer string L6 4 5 Pointer to product string L6 4 6 Pointer to serial number ID L6 4 7 Language ID 6 5 1 ENDPOINT INFORMATION TABLE The endpoint information table provides the hardware endpoint characteristics to the USB device stack When an endpoint is opened the USB device stack s core iterates through the endpoint information table entries until the endpoint type and direction match the requested endpoint characteristics The matching entry provides the physical endpoint number and maximum packet size information to the USB device stack The entries on the endpoint information table are organized as follows 86 Device Configuration typedef const struct usbd_drv_ep info CPU_LINTO8U Attrib 1 CPU_INTO8U Nbr 2 CPU_INT16U MaxPktSize 3 USBD_DRV_EP_INFO L6 5 1 L6 5 2 L6 5 3 Listing 6 5 Endpoint Information Table Entry The endpoint Attrib is a combination of the endpoint type USBD_EP INFO TYPE and endpoint direction USBD_EP INFO DIR attributes The endpoint type can be defined as USBD_EP_INFO TYPE CTRL USBD EP INFO TYPE INTR USBD EP INFO TYPE BULK or USBD EP INFO TYPE ISOC The endpoint direction can be defined as either USBD_EP_INFO DIR IN or USBD_EP INFO DIR OUT The endpoint Nbr is the physical endpoint number used by the USB device controller The endpoint MaxPktSize defines the maximum packet size supported by hardware The maxim
98. 9 Chapter 9 9 3 3 CLASS INSTANCE COMMUNICATION The HID class offers the following functions to communicate with the host For more details about the functions parameters refer to Appendix D HID API Reference on page 387 Function name Operation USBD_HID Rd Receives data from host through interrupt OUT endpoint This function is blocking USBD_HID Wr Sends data to host through interrupt IN endpoint This function is blocking USBD_HID RdAsync Receives data from host through interrupt OUT endpoint This function is non blocking USBD_HID WrAsync Sends data to host through interrupt IN endpoint This function is non blocking Table 9 7 HID Communication API Summary 9 3 4 SYNCHRONOUS COMMUNICATION Synchronous communication means that the transfer is blocking Upon function call the applications blocks until the transfer completion with or without an error A timeout can be specified to avoid waiting forever Listing 9 3 presents a read and write example to receive data from the host using the interrupt OUT endpoint and to send data to the host using the interrupt IN endpoint 150 Configuration CPU_INTO8U rx _buf 2 CPU_INTO8U tx_buf 2 USBD_ERR err void USBD_HID_Rd Class nbr 1 void amp rx_buf 0 2 2u 0u 3 amp err if err USBD_ERR NONE Handle the error void USBD HID Wr class_nbr 1 void amp tx_buf 0 4 2u 0u 3 gerr
99. 92 CALLERS USBD_EP Close USBD_StdReqEP USB device class drivers NOTES WARNINGS None 293 Appendix A A 4 17 USBD_EP_IsStalled Gets stall status of non control endpoint FILES usbd_core h usbd_ep c PROTOTYPE CPU_BOOLEAN USBD_EP IsStalled CPU_INTO8U dev_nbr CPU_INT08U ep addr USBD_ERR p_err ARGUMENTS dev_nbr Device number ep addr Pointer to the structure where the current line coding will be stored p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_DEV_INVALID_ARG USBD_ERR_ EP INVALID ADDR RETURNED VALUE DEF_TRUE if endpoint is stalled DEF_FALSE otherwise CALLERS USBD_StdRegEP USB device class drivers Application NOTES WARNINGS None 294 A 4 18 USBD_EP_GetMaxPktSize Retrieves endpoint s maximum packet size FILES usbd_core h usbd_ep c PROTOTYPE CPU_INT16U USBD_EP_GetMaxPktSize CPU_INTO8U dev_nbr CPU_INTO8U ep addr USBD_ERR p err ARGUMENTS dev_nbr Device number ep_addr Endpoint address p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_ DEV INVALID NBR USBD_ERR_ EP INVALID ADDR USBD_ERR_ EP INVALID STATE RETURNED VALUE Maximum packet size If no error s 0 otherwise CALLERS Application NOTES WARNINGS None 295 Appendix A A 4 19 USBD_EP_GetMaxPhyNbr Get the maximum physic
100. ALID CLASS STATE USBD_ERR_ DEV INVALID NBR USBD_ERR_ DEV INVALID STATE USBD_ERR_ EP INVALID ADDR USBD_ERR_EP INVALID STATE USBD_ERR_ EP INVALID TYPE 367 Appendix C USBD_ERR_OS TIMEOUT USBD_ERR_OS ABORT USBD_ERR_OS FAIL RETURNED VALUE None CALLERS CDC Subclass drivers NOTES WARNINGS 1 The following table show the relationship between CDC request and the parameters passed in the USBD_CDC_Notify function The bmRequestType and windex fields are calculated internally in the CDC module bmRequestType bNotificationCode wValue windex wLength Data 1010001b notification value Interface data_len p_buf 7 to p_buf data_len 1 2 The notification buffer size must contain space for the notification header 8 bytes and the variable length data portion 368 C 2 CDC ACM SUBCLASS FUNCTIONS C 2 1 USBD_ACM Serialinit Initialize CDC ACM serial emulation subclass FILES usbd_acm_serial h usbd_acm_serial c PROTOTYPE void USBD_ACM SerialInit USBD_ERR p err ARGUMENTS p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE RETURNED VALUE None CALLERS Application NOTES WARNINGS None 369 Appendix C C 2 2 USBD_ACM SerialAdd Add a new CDC ACM serial emulation instance FILES usbd_acm_serial h usbd_acm_serial c PROTOTYPE CPU_INTO8U USBD ACM SerialAdd CPU_INT16U line state_interval
101. AMETER RETURNED VALUE TRUE if device is high speed FALSE otherwise CALLERS Application NOTES WARNINGS None 508 G 2 9 USBDev_Bulkin_Open Open a Bulk IN pipe FILES usbdev_api c PROTOTYPE HANDLE USBDev_BulkIn Open HANDLE dev UCHAR EE UCHAR alt_set DWORD p err ARGUMENTS dev General handle to device if_nbr Interface number alt_set Alternate setting number for specified interface p err Pointer to variable that will receive the return error code from this function ERROR_SUCCESS ERROR INVALID HANDLE ERROR HO MORE ITEMS RETURNED VALUE Handle to Bulk IN pipe if NO error s INVALID HANDLE VALUE otherwise CALLERS Application NOTES WARNINGS None 509 Appendix G G 2 10 USBDev_BulkOut_Open Open a Bulk OUT pipe FILES usbdev_api c PROTOTYPE HANDLE USBDev_BulkOut_Open HANDLE dev UCHAR if_nbr UCHAR alt_set DWORD p err ARGUMENTS dev General handle to device if_nbr Interface number alt_set Alternate setting number for specified interface p err Pointer to variable that will receive the return error code from this function ERROR_SUCCESS ERROR INVALID HANDLE ERROR HO MORE ITEMS RETURNED VALUE Handle to Bulk OUT pipe if NO error s INVALID HANDLE VALUE otherwise CALLERS Application NOTES WARNINGS None 510 G 2 11 USBDev_Intrin_Open Open a Interrupt IN pipe FILES usbdev_api c PROTOTYPE H
102. ANDLE USBDev_IntrIn_Open HANDLE dev UCHAR EE UCHAR alt_set DWORD p err ARGUMENTS dev General handle to device if_nbr Interface number alt_set Alternate setting number for specified interface p err Pointer to variable that will receive the return error code from this function ERROR_SUCCESS ERROR INVALID HANDLE ERROR_NO MORE ITEMS RETURNED VALUE Handle to Interrupt IN pipe if NO error s INVALID HANDLE VALUE otherwise CALLERS Application NOTES WARNINGS None 511 Appendix G G 2 12 USBDev_IntrOut_Open Open a Interrupt OUT pipe FILES usbdev_api c PROTOTYPE HANDLE USBDev_IntrOut_Open HANDLE dev UCHAR if_nbr UCHAR alt_set DWORD p err ARGUMENTS dev General handle to device if_nbr Interface number alt_set Alternate setting number for specified interface p err Pointer to variable that will receive the return error code from this function ERROR_SUCCESS ERROR INVALID HANDLE ERROR_NO MORE ITEMS RETURNED VALUE Handle to Interrupt OUT pipe if NO error s INVALID HANDLE VALUE otherwise CALLERS Application NOTES WARNINGS None 512 G 2 13 USBDev_PipeGetAddr Get pipe address FILES usbdev_api c PROTOTYPE UCHAR USBDev PipeGetAddr HANDLE pipe DWORD ap err ARGUMENTS pipe Pipe handle p err Pointer to variable that will receive the return error code from this function ERROR_SUCCESS ERROR INVALID HANDLE RETURNED VALUE Pipe
103. App USBD MSC _Init section 10 4 2 Class Instance Configuration on page 174 PHDC App USBD_PHDC_Init section 11 2 2 Class instance configuration on page 189 Vendor App_USBD_ Vendor Init section 12 2 2 Class Instance Configuration on page 208 Table 2 2 List of Sections to Refer to for Class Demos Information After building and downloading the application into your target you should be able to successfully connect your target to a host PC through USB Once the USB sample application is running the host detects the connection of a new device and starts the enumeration process If you are using a Windows PC it will load a driver which will manage your device If no driver is found for your device Windows will display found new hardware wizard so that you can specify which driver to load Once the driver is loaded your device is ready for communication Table 2 3 lists the different section s you should refer to for more details on each class demo Class Refer to CDC ACM section 8 4 6 Using the Demo Application on page 129 HID section 9 4 Using the Demo Application on page 154 MSC section 10 5 Using the Demo Application on page 176 PHDC section 11 5 Using the Demo Application on page 200 Vendor section 12 4 Using the Demo Application on page 220 Table 2 3 List of Sections to Refer to for Class Demos Information 43 Chapter 2 44 Chapter
104. BD_EP_IsSStalled 0 2 2 cccccceeceseeeceeeeseeeeeeeeesneaeeeeeeseaeeeeenseaaeeeeeneeaes 294 USBD_EP_GetMaxPKtSize 2 ccccesceesseeseeeceeeeeeeeeeeeeeeeeeeeneeeeeeeeeees 295 USBD_EP_GetMaxPhyNbrr cecceseesseeeeeeeceeeeeeeeeseeeeesseaeeeeeeeeeenees 296 USBD_EP_GetMaxNbrOpen ecsse seeeeeeeeeeeeeeeeseeeeeesseaneeeeeeeeenens 297 Gore OS FUNCHIONS 2 eugeuegdeedEeEde Suedel 298 WSBD2OS SIRI 2 2 seess 298 USBD_CoreTaskHandcler ccccecceeeeeseeeseeeceeeeeeeeeseeeeeeeeeeneeeeeeeeeees 300 USBD_DbgTaskHandler ccccccceseeeeeeeseeeeceeeseeeeeeeeeeseeeseeeeseeeeeeneeaes 301 USBD_OS_EP_SignalCreate scesseeeeeeeeeeeeeeeeeeeeeeessaneeeeeeeeenens 302 USBD_OS_EP_SignalDel cscseeeeeeeeeeeeeeeeeeeeneeeneeeeeeeeeeeeenees 304 USBD_OS_EP_SignalPend sesssesseeeeeeeeeeeeeeeeeeeeeeesseeneeeeeeeeenens 305 USBD_OS_EP_SignalAbDoOrt ccccessseccceeeseeeeeeeeseeaeeeeeeseeaeeeeeeeaaes 307 USBD_OS_EP_SignalPost RRE REENEN 308 USBD_OS_CoreEventPut ccseccccssseeeceeeeeseeeeeeeeseeeeeeeenseaeeeeenenees 309 USBD_OS_CoreEventGet ccccccceceseeeceeeeeseeeeeeeeseeeeeeeenseaeeeeenenees 310 USBD_OS_DbgEventRdy cecceceeeeeeeeeeeeeeeeeeeeeeeseeeeeeeseaneeeeeeeeenens 311 USBD_OS_DbgEventWaAit REENEN REENEN 312 Device Drivers Callbacks Functions REENEN 313 USBD ER Batman ee eege 313 USBD ER Temple cess tege thee tege deeg A 314 USB
105. BD_ERR_NONE RETURNED VALUE None CALLERS Application NOTES WARNINGS None 354 C 1 2 USBD_CDC Add This function creates a CDC instance FILES usbd_cde h usbd_cdce c PROTOTYPE CPU_INTO8U USBD_CDC_Add CPU_INTO8U USBD_CDC_SUBCLASS DRV subclass p subclass dru void CPU_INTO8U CPU_BOOLEAN CPU_INT16U USBD_ERR ARGUMENTS subclass CDC subclass code USBD_CDC_ SUBCLASS RSVD epp CC SUBCLASS DCH USBD_CDC_SUBCLASS ACM USBD_CDC_ SUBCLASS TCM USBD_CDC_SUBCLASS MCC USBD_CDC_ SUBCLASS CAPICM USBD_CDC_SUBCLASS WHCM USBD_CDC_SUBCLASS DEV MGMT USBD_CDC_SUBCLASS MDIM USBD_CDC_ SUBCLASS OBEX USBD_CDC_SUBCLASS EEM USBD_CDC_SUBCLASS HOH USBD_CDC_SUBCLASS VENDOR p subclass arg protocol notify en notify interval p err Reserved value Direct Line Control Model Abstract Control Model Telephone Control Model Multi Channel Control Model CAPI Control Model Wireless Handset Control Model Device Management Device Management Obex Ethernet Emulation Model Network Control Model Vendor specific CDC subclass codes are defined in the Universal Serial Bus Class Definitions for Communication Devices Revision 2 1 Table 4 355 Appendix C p _ subclass dru Pointer to CDC subclass driver p_subclass arg Pointer to CDC subclass driver argument protocol CDC protocol code USBD_CDC_COMM PROTOCOL NONE USBD_CDC_COMM PROTOCOL AT V250 USBD_CDC_COMM PROTOCOL AT PCCA 101 USBD_CDC_COMM PROT
106. BD_HID OS CFG TMR TASK STK SIZE Configures the stack size of the HID periodic input reports task Table 9 5 HID Internal Task s Configuration Constants 143 Chapter 9 9 3 2 CLASS INSTANCE CONFIGURATION Before starting the communication phase your application needs to initialize and configure the class to suit its needs Table 9 6 summarizes the initialization functions provided by the HID class For more details about the functions parameters refer to Appendix D HID API Reference on page 387 Function name Operation USBD_HID Init Initializes HID class internal structures variables and the OS layer USBD_HID_ Addi Creates a new instance of HID class USBD_HID_CfgAdd Adds an existing HID instance to the specified device configuration Table 9 6 HID Class Initialization API Summary You need to call these functions in the order shown below to successfully initialize the HID class 1 Call USBD_HID Init This is the first function you should call and you should do it only once even if you use multiple class instances This function initializes all internal structures and variables that the class needs and also the HID OS layer 2 Call USBD HID Add This function allocates an HID class instance It also allows you to specify the following instance characteristics E The country code of the localized HID hardware E The Report descriptor content and size P The Physical descriptor conte
107. BD_MSC_OS_EnumSignalPend cccccccesseeeeeeeeeeseeeeeeeeeeeeeees 433 MSC Storage Layer FUNCtIONS cccccceseeeeeeeseeeeeeeeeeeseeeeeeeeseeneeneneeeee 434 USBD_Storagelnit cccccceeseeeceeeeseeeeeeeeseeeseeseseeeeseeeeseeeseeeeseeeeeeeeeesees 434 USBD_StorageCapacityGet ceeccccsseeeeeeeeeeeeeeeeeesseeeseeeeseeeeeeeeseees 435 USBD StorageRd si Reese deeg ege 436 USBD Storage Wr rsrsr cee cesctes ccdeeceessetevtesceacs EENEG ERR EEEEEERE ENN 437 USBD_StorageStatuSGet ccccccceeeeecceesseeeeeeeeeseeeeeeeeseeeseeeeseeeeseeeeesees 439 PHDC API Reference is css sacccccccenei eae EENS ER reenvenvanstenteasteneueevees 441 PHDG Fun Ctl oo icc ee d e ee Eegen 442 USBD PHDGInit cicada widened ial ie 442 USBD PHDGC Addi se ee aia kk eee ES 443 USBD _PHDG _CIG Add scccisccissceccsecccssecesecenentenceencedcreseatsentereestententenes 445 USB RRE IsConin ss iiiwsandina See ie inlaw dia Kee 447 USBD PHDO ROGIG 2 ugegeueedet e er gegbegek tvcess scsi aiana EAA EEA 448 USBD PHDG Wrefgl eege geEaee e iaaa EE Skeet evens eevee 450 USBD_PHDC_11073_ExtCfg cceseeceesseeeeeeeeessseeeeeeeeeseseeeeeneeeesenes 452 USBD_PHDC_RdPreamble cccsecccseeeeeeeeeeseseeeeeneeeeseseeeseeeeeneenees 454 USBD PHDG Rd tistics cece keen aio atin Retin ates cee 456 F 1 10 F 1 11 F 1 12 F 2 F 2 1 F 2 2 F 2 3 F 2 4 F 2 5 F 2 6 F 2 7 Appendix G G 1 G 1 1 G 1 2 G 1 3 G 1 4 G 1 5 G 1 6 G 1 7 G 1 8 G
108. CCl CCl CCl DCI DCI Audio DCI Figure 8 1 CDC Composite Device A CDC device is likely to use the following combination of endpoints E A pair of control IN and OUT endpoints called the default endpoint E An optional bulk or interrupt IN endpoint A pair of bulk or isochronous IN and OUT endpoints Table 8 1 indicates the usage of the different endpoints and by which interface of the CDC they are used Endpoint Direction Interface Usage Control IN Device to host CCl Standard requests for enumeration class specific requests device management and optionally call management Control OUT Host to device CCl Standard requests for enumeration class specific requests device management and optionally call management Interrupt or bulk IN Device to host CCl Events notification such as ring detect serial line status network status Bulk or isochronous IN Device to host DCI Raw or formatted data communication Bulk or isochronous OUT Host to device DCI Raw or formatted data communication Table 8 1 CDC Endpoint Usage 117 Chapter 8 Most communication devices use an interrupt endpoint to notify the host of events Isochronous endpoints should not be used for data transmission when a proprietary protocol relies on data retransmission in case of USB protocol errors Isochronous communication can inherently loose data since it has no re
109. D Event opp icccicicccecteccesceetecssecevas sated ccdceetedeneensaasnincccsdentaeteets 315 USBD EVentDISCOnn serge VEENENEESEE assteciteeeceveeseensebenestecseereaieeres 316 USBD_EventReset ceecceeceeeeeeeeeeeeeeeeaneeeeeeeeeeeeseeeseeaneeeeeeeenees 317 USBD Event S EE 318 USBD_EventSuspend cccceceeeeeeeeeeeenceeeeeeeeeeeeseseeeesaneeeeeeeeenees 319 Table of Contents A 6 8 A 7 A 7 1 Appendix B B 1 B 1 1 B 1 2 B 1 3 B 1 4 B 1 5 B 1 6 B 1 7 B 1 8 B 1 9 B 1 10 B 1 11 B 1 12 B 1 13 B 1 14 B 1 15 B 1 16 B 1 17 B 1 18 B 1 19 B 2 B 2 1 B 2 2 B 2 3 Appendix C C 1 C 1 1 C 1 2 C 1 3 C 1 4 C 1 5 C 1 6 10 USBD_EventReSume ek REENEN EEN 320 Trace FUNCTIONS lt i Geekgeeegese SE ois araa eana oar ei is ee es 321 USBD Trace eiiean dnain aaa aiaa a aa aaa aa aa aAa aria aaia 321 Device Controller Driver API Reference sssssssssssneneseennenenennennnnnnnnnn 323 Device Driver FUNCTIONS ccccccceeeeeeeeeeeeeeeeesseseseeeeeaeaeeeeessseeeeeeenees 324 USBD DAAI eege e e tears det eege 324 USBDiDWVStart ccssedcccdeces hess cstisesdesetietins destin eege Gel ai 326 USBD DIvStop E E TEA ge EEN 328 USBD DivAddrSet er a a e aaae eaaa aa hie hee 329 VSBD Drv ddrtnt earar aaea a e r aana ameba p erea eio a Eae anaiai inaari iaai 330 USBD DrvGtgSet eraan aa aaaea aa a aeaa eegen 331 HR HEEM irirna cee eee eet dee 332 USBD_DrvGetFrameNbr ccccceccesee
110. D VALUE None CALLERS USB device controller drivers ISR NOTES WARNINGS None 313 Appendix A A 6 2 USBD_EP_TxCmpl Notifies the stack that an IN transfer is completed FILES usbd_core h usbd_ep c PROTOTYPE void USBD_EP_RxCmpl USBD_DRV p_drv CPU_INTO8U ep _log_nbr ARGUMENTS p drv Pointer to device driver structure ep_log_nbr Endpoint logical number RETURNED VALUE None CALLERS USB device controller drivers ISR NOTES WARNINGS None 314 A 6 3 USBD_EventConn Notifies the stack the device is connected to the host FILES usbd_core h usbd_core c PROTOTYPE void USBD_EventConn USBD_DRV p drv ARGUMENTS p drv Pointer to device driver structure RETURNED VALUE None CALLERS USB device controller drivers ISR NOTES WARNINGS None 315 Appendix A A 6 4 USBD_EventDisconn Notifies the stack the device is disconnect from the host FILES usbd_core h usbd_core c PROTOTYPE void USBD_EventDisconn USBD_DRV p drv ARGUMENTS p drv Pointer to device driver structure RETURNED VALUE None CALLERS USB device controller drivers ISR NOTES WARNINGS None 316 A 6 5 USBD _ EventReset Notifies the stack a reset event in the bus FILES usbd_core h usbd_core c PROTOTYPE void USBD_EventReset USBD_DRV ap drei ARGUMENTS p drv Pointer to device driver structure RETURNED VALUE None CALLERS
111. D and Device Release Number For development purposes you can use the default values but once you decide to release your product you must contact USB IF in order to get valid IDs USB IF maintains all USB Vendor ID and Product ID numbers L2 1 3 Specify human readable Vendor ID Product ID and Device Release Number strings L2 1 4 A USB device can store strings in multiple languages Specify the language used in your strings The defines for the other languages are defined in the file usbd_core h in the section Language Identifiers 34 Building the Sample Application MODIFY DRIVER CONFIGURATION Modify the driver configuration usbd_dev_cfg c as needed for your controller See Listing 2 2 below for details USBD_DRV_CFG USBD_DrvCfg Template 1 0x00000000 2 0x00000000 3 Ou USBD_DEV_SPD_FULL 4 USBD_DrvEP_InfoTbl_Template 5 H Listing 2 2 Driver Configuration Template L2 2 1 Give your driver configuration a meaningful name by replacing the word L2 2 2 L2 2 3 L2 2 4 L2 2 5 Template Specify the base address of your USB device controller If your target has dedicated memory for the USB controller you can specify its base address and size here Depending on the USB controller dedicated memory can be used to allocate driver buffers or DMA descriptors Specify the USB device controller speed USBD_DEV_SPD_HIGH if your controller supports high speed or USBD_DEV_SPD_FULL if your co
112. D compliant consumer control device Driver Provider Micrium 5 USB Input Device Driver Date 15 10 2009 DS USB Input Device Driver Version 1 0 0 0 Hz USB Input Device ca IDE ATA ATAPI controllers Digtal Signer Not digtaly signed Imaging devices Keyboards Driver Details To view details about the driver files A Mice and other pointing devices E Monitors Update Driver To update the driver software for this device ES Network adapters KR Portable Devices Roll Back Driver erir e his roll IF Ports COM amp LPT YP Micrium CDC Device COM15 Sr Y USB Serial Port COM7 DI Processors amp Sound video and game controllers JE System devices 8 Universal Serial Bus controllers OK Cancel Disables the selected device To uninstall the driver Advanced Uninstall Figure 3 1 Windows Device Manager Example for a CDC Device 50 Microsoft Windows 3 1 2 USING GUIDS A Globally Unique IDentifier GUID is a 128 bit value that uniquely identifies a class or other entity Windows uses GUIDs for identifying two types of device classes E Device setup class E Device interface class A device setup GUID encompasses devices that Windows installs in the same way and using the same class installer and co installers Class installers and co installers are DLLs that provide functions related to device installation There is a GUID associated with each device
113. D_ACM SerialLineCtrlReg This function allows you to register a callback used by the ACM subclass to notify the application about a change in the serial line state that is carrier control and a flag indicating that data equipment terminal is present or not Call USBD_ACM SerialCfgAdd Finally once the ACM subclass instance has been created you must add it to a specific configuration ACM Subclass Listing 8 2 illustrates the use of the previous functions for initializing the ACM subclass Note that the error handling has been omitted for clarity 4 static void App_USBD_CDC_SerialLineCtrl CPU_INTO8U subclass_nbr CPU_INTO8U events CPU_INTO8U events_chngd void p arg 5 static CPU BOOLEAN App USBD_CDC_SerialLineCoding CPU_INT08U subclass_nbr USBD_ACM SERIAL LINE CODING p line coding void p arg CPU_BOOLEAN App USBD_CDC Init CPU_INTO8U dev_nbr CPU_INTO8U cfg_hs CPU_INTO8U cfg fs USBD_ERR efr CPU_INTO8U subclass_nbr USBD_CDC_Init amp err 1 USBD_ACM SerialInit amp err 2 subclass _nbr USBD_ACM SerialAdd 100u amp err ES 4 USBD_ACM SerialLineCodingReg subclass_nbr App_USBD_CDC_SerialLineCoding void 0 amp err 5 USBD_ACM_SerialLineCtrl1Reg subclass_nbr App_USBD_CDC_SerialLineCtrl void 0 amp err if cfg_hs USBD_CFG_NBR_NONE USBD_ACM SerialCfgAdd subclass_nbr dev_nbr cfg_hs amp err 6 if cfg_fs USBD_CFG_NBR_NONE USBD_ACM SerialCfgA
114. D_ERR_NONE USBD_ERR_ DEV INVALID NBR USBD_ERR CFG INVALID NBR USBD_ERR_IF INVALID NBR USBD_ERR_IF GRP NBR_IN USE USBD_ERR_IF GRP ALLOC RETURNED VALUE Interface group number if no errors USBD_IF GRP NBR NONE otherwise CALLERS USB class drivers NOTES WARNINGS None 260 A 4 ENDPOINTS FUNCTIONS A 4 1 USBD_CtriTx Sends data on control IN endpoint FILES usbd_core h usbd_ep c PROTOTYPE CPU_INT32U USBD_Ctr1Tx CPU_INTO8U dev_nbr void p buf CPU_INT32U buf_len CPU_INT16U timeout_ms CPU_BOOLEAN end USBD_ERR p err ARGUMENTS dev_nbr Device number p buf Pointer to buffer of data that will be sent buf len Number of octets to transmit timeout_ms end p_err Timeout in milliseconds End of transfer flag see Note 1 Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_INVALID ARG USBD_ERR DEV INVALID NBR USBD_ERR DEV INVALID STATE USBD_ERR_ EP INVALID ADDR USBD_ERR_ EP INVALID STATE 261 Appendix A USBD_ERR_EP INVALID TYPE USBD_ERR_OS TIMEOUT USBD_ERR_OS ABORT USBD_ERR_OS FAIL RETURNED VALUE Number of octets transmitted if no errors 0 otherwise CALLERS USBD_DescWrReq USBD_DescWrStop USBD_StdReqDev USBD_StdReqEP USBD_StdReqIF USB device class drivers NOTES WARNINGS E If end of transfer is set and transfer length is multiple of maximum packet size a zero length packet is tra
115. D_HID CfgAdd class _nbr dev_nbr cfg_hs amp err 4 if err USBD_ERR_NONE Handle the error if cfg_fs USBD_CFG NBR NONE USBD_HID CfgAdd class_nbr dev_nbr cfg fs amp err 5 if err USBD_ERR_NONE Handle the error D Listing 9 1 HID Class Initialization Example L9 1 1 Initialize HID internal structures variables and OS layer L9 1 2 Create a new HID class instance In this example the subclass is Boot the protocol is Mouse and the country code is unknown A table App USBD HID ReportDesc representing the Report descriptor is passed to the function refer to Listing 9 2 for an example of Report descriptor content and section 9 1 1 Report on page 136 for more details about the Report descriptor format No Physical descriptor is provided by the application The interrupt IN endpoint is used and has a 2 frames or microframes polling interval The use of the control endpoint to receive Output reports is enabled The interrupt OUT endpoint will not be used Hence the interrupt OUT polling 146 Configuration interval of 2 is ignored by the class The structure App _USBD_HID Callback is also passed and references 4 application callbacks which will be called by the HID class upon processing of the class specific requests 19 16 There are 4 application callbacks for class specific requests processing There is one callback for each of the following requests GET_REPORT
116. Drv Drv Drv Drv Drv Drv Drv Drv EP DMA EP DMA EP DMA EP DMA ISR Rx pkt ISR Rx ISR Rx Open Open Close Close Open Open Fast Cmpl Fast Fast descriptor Device EP FIFO Tx Len 18 EP FIFO Tx Start Len 18 ISR Rx ISR Tx ISR Rx ISR Rx Fast Cmpl Fast Cmpl Fast Fast EP FIFO RxZLP ISR Rx Fast Listing 13 2 Sample Debug Output 233 Chapter 13 13 2 HANDLING DEBUG EVENTS 13 2 1 DEBUG EVENT POOL A pool is used to keep track of debugging events This pool is made up of debug event structures where the size of the pool is specified by USBD_CFG_DBG_ TRACE NBR_EVENTS in the application configuration Within the core each time a new debug standard request is received the message s details will be set into a debug event structure and queued into the pool Once the debug event is properly queued a ready signal is invoked to notify the debug task handler that an event is ready to be processed 13 2 2 DEBUG TASK An OS dependent task is used to process debug events The debug task handler simply pends until an event ready signal is received and obtains a pointer to the first debug event structure from the pool The details of the debug event structure is then formatted and outputted via the application trace function At the end of the output the debug event structure is then subsequently freed and the debug task will pend and process the next debug event structure ready Refer to se
117. E OS error code s relevant to failure s CALLERS USBD HID Wr IMPLEMENTATION GUIDELINES The wait operation typically consists in pending on a semaphore When the input report transfer has completed the task is waken up by the Core layer internal task responsible for asynchronous communication p err argument should be assigned as described in Table D 2 405 Appendix D Operation result Error code to assign No error USBD_ERR_NONE Pend timeout USBD_ERR_OS_TIMEOUT Pend aborted USBD_ERR_OS_ABORT Pend failed for any other reason USBD_ERR_OS FAIL Table D 2 p_err assignment according to the pend operation result 406 D 2 5 USBD_HID_OS InputDataPendAbort Abort any operation on input report FILES usbd_hid_os c PROTOTYPE void USBD HID OS InputDataPendAbort CPU_INTO8U class_nbr ARGUMENTS class nbr_ Class instance number CALLERS USBD_HID_WrSyncCmp1 IMPLEMENTATION GUIDELINES If the input report transfer completes with an error the task waiting is waken up by aborting the active wait done with USBD HID OS InputDataPend The active wait abortion is executed by the Core layer internal task responsible for asynchronous communication 407 Appendix D D 2 6 USBD_HID_OS InputDataPost Signal that Input report data has been sent to the host FILES usbd_hid_os c PROTOTYPE void USBD_HID OS InputDataPost CPU_INTO8U class_nbr ARGUMENTS class nbr_ Class instanc
118. ED application APP_CFG USBD_MSC_EN Enables MSC in the application DEF_ENABLED Table 10 7 Application Preprocessor Constants If RAMDisk storage is used ensure that the associated storage layer files are included in the project and configure the following constants detailed in Table 10 8 Preprocessor Constants Description Default Value USBD_RAMDISK CFG NBR_UNITS Number of RAMDISK units 1 USBD_RAMDISK CFG BLK SIZE RAMDISK block size 512 USBD_RAMDISK_ CFG NBR_BLKS RAMDISK number of blocks 4 1024 1 USBD_RAMDISK_CFG BASE ADDR RAMDISK base address in memory OXA000000 This constant is optional and is used to define the data area of the RAMDISK If it is defined RAMDISK s data area will be set from this base address directly If it is not defined RAMDISKk s data area will be represented as a table from the program s data area Table 10 8 RAM Disk Preprocessor Constants 177 Chapter 10 If uC FS storage is used ensure that the associated uC FS storage layer files are included in the project and configure the following constants detailed in Table 10 8 Preprocessor Constant Description Default Value APP_CFG FS_EN Enables uC FS in the application DEF_ENABLED APP_CFG FS_DEV_CNT File system device count 1 APP_CFG FS _VOL_CNT File system volume count 1 APP_CFG FS FILE CNT File system file count 2 APP_CFG FS DIR CND File syste
119. ENTS class_nbr MSC instance number RETURNED VALUE None CALLERS OS layer NOTES WARNINGS None 427 Appendix E E 2 MSC OS FUNCTIONS E 2 1 USBD_MSC OS Init Initialize MSC OS interface FILES usbd_msc_os h usbd_msc_os c PROTOTYPE void USBD_MSC_OS Init USBD_ERR p err ARGUMENTS p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_OS FAIL RETURNED VALUE None CALLERS USBD_OS Init IMPLEMENTATION GUIDELINES Initialization of the MSC OS interface must include creating 1 Two semaphores one for MSC communication and one for enumeration 2 A MSC task to handle the MSC protocol 428 E 2 2 USBD_MSC OS CommSignalPost Post a semaphore used for MSC communication FILES usbd_msc_os h usbd_msc_os c PROTOTYPE void USBD_MSC_OS CommSignalPost CPU_INTO8U class_nbr USBD_ERR p err ARGUMENTS class _nbr MSC instance class number p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_OS FAIL RETURNED VALUE None CALLERS Various NOTES WARNINGS None 429 Appendix E E 2 3 USBD_MSC OS CommSignalPend Wait on a semaphore to become available for MSC communication FILES usbd_msc_os h usbd_msc_os c PROTOTYPE void USBD_MSC_OS CommSignalPend CPU_INTO8U class_nbr CPU_INT32U timeout USBD_ERR ap err ARGUMEN
120. EP INVALID TYPE USBD_ERR_OS TIMEOUT USBD_ERR_OS ABORT USBD_ERR_OS FAIL 267 Appendix A RETURNED VALUE Number of octets received If no error s 0 otherwise CALLERS USB device class drivers NOTES WARNINGS This function blocks until m All data is received or E An error occurred E Transfer does not complete in the period specified by timeout_ms 268 A 4 5 USBD_BulkRxAsync Receives data on bulk OUT endpoint asynchronously FILES usbd_core h usbd_core c PROTOTYPE void USBD_BulkRxAsync CPU_INT08U dev_nbr cPU_INTO8U ep_addr void p buf CPU_INT32U buf_len USBD_ASYNC_FNCT async_fnct void p_async_ arg USBD_ERR p err ARGUMENTS dev_nbr Device number ep addr Endpoint address p buf Pointer to destination buffer to receive data buf len Number of octets to receive async _fnct p async_arg p err Function that will be invoked upon completion of receive operation Pointer to argument that will be passed as parameter of async_fnct Pointer to variable that will receive the return error code from this function USBD_ERR_NONE Depp ERR DEV INVALID NBR USBD_ERR_ DEV INVALID STATE USBD_ERR_ EP INVALID ADDR USBD_ERR_EP INVALID STATE USBD_ERR_EP INVALID TYPE USBD_ERR_OS TIMEOUT USBD_ERR_OS ABORT USBD_ERR_OS FAIL 269 Appendix A RETURNED VALUE None CALLERS USB device class drivers NOTES WARNINGS The callback specified by async_fnct has the following
121. EP_RXZLP NOTES WARNINGS None 341 Appendix B B 1 14 USBD_DrvEP_Tx Configure endpoint with buffer to transmit data FILES Every device driver s usbd_drv c PROTOTYPE static CPU_INT32U USBD DrvEP_Tx USBD_DRV p drv CPU_INTO8U ep addr CPU_INTO8U p buf CPU_INT32U buf_len USBD_ERR p err ARGUMENTS p drv Pointer to USB device driver structure ep_addr Endpoint address p buf Pointer to data buffer buf len Length of the buffer p err Pointer to variable that will receive the return error code from this function RETURNED VALUE Number of octets transmitted if NO error s 0 otherwise CALLERS E USBD_EP Tx via p drv_api gt EP_Tx E USBD_EP Process 342 NOTES WARNINGS Typically the function to configure the endpoint receive transaction performs the following operations Check if data can be transmitted E Write data to device endpoint E Configure the packet length in USB device controller This is often necessary when the packet is shorter than the maximum packet size Depending on the USB controller this operation may need to be performed prior to writing the data to the device endpoint 343 Appendix B B 1 15 USBD_DrvEP_TxStart Transmit the specified amount of data to device endpoint FILES Every device driver s usbd_drv c PROTOTYPE static void USBD DrvEP_TxStart USBD_DRV p dru CPU_INT08U ep addr CPU_LINTO8U p buf CPU_INT3
122. ERR_ALLOC USBD_ERR_INVALID ARG RETURNED VALUE Data interface number if no errors USBD_CDC_DATA IF NBR NONE otherwise CALLERS CDC Subclass drivers NOTES WARNINGS None 362 C 1 6 USBD_ CDC DataRx Receive data on CDC data interface FILES usbd_cde h usbd_cdce c PROTOTYPE CPU_INT32U USBD_CDC_DataRx CPU_INT08U class_nbr CPU_LINTO8U data_if_nbr CPU_LINTO8U p buf CPU_INT32U buf len CPU_INT16U timeout USBD_ERR p err ARGUMENTS class_nbr CDC instance number data _if_nbr CDC data interface number p_buf buf_len timeout_ms p_err Pointer to destination buffer to receive data Number of octets to receive Timeout in milliseconds Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_INVALID ARG USBD_ ERR INVALID CLASS STATE USBD_ERR_ DEV INVALID NBR USBD_ERR_ DEV INVALID STATE USBD_ERR_ EP INVALID ADDR USBD_ERR_EP INVALID STATE USBD_ERR_ EP INVALID TYPE 363 Appendix C USBD_ERR_OS TIMEOUT USBD_ERR_OS ABORT USBD_ERR_OS FAIL RETURNED VALUE Numbers of octets received if no errors 0 otherwise CALLERS CDC Subclass drivers NOTES WARNINGS None 364 C 1 7 USBD_CDC DataTx Send data on CDC data class interface FILES usbd_cde h usbd_cdce c PROTOTYPE CPU_INT32U USBD_CDC_DataTx CPU_INT08U class_nbr CPU_LINTO8U data_if_nbr CPU_LINTO8U p buf CPU_INT32U buf len CPU_INT
123. ERR_EP ALLOC RETURNED VALUE Endpoint address If no error s USBD_EP ADDR NONE otherwise CALLERS USB device class drivers NOTES WARNINGS If the max okt len argument is 0 the stack will allocate the first available interrupt endpoint regardless its maximum packet size 277 Appendix A A 4 9 USBD_IntrRx Receives data on interrupt OUT endpoint FILES usbd_core h usbd_ep c PROTOTYPE CPU_INT32U USBD_IntrRx CPU_INTO8U dev_nbr CPU_LINTO8U ep addr void p buf CPU_INT32U buf len CPU_INT16U timeout ms USBD_ERR p err ARGUMENTS dev_nbr Device number ep_addr Endpoint address p buf Pointer to destination buffer to receive data buf len Number of octets to receive timeout ms Timeout in milliseconds p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_DEV_INVALID NBR USBD_ERR_DEVINVALID STATE USBD_ERR_ EP INVALID ADDR USBD_ERR_EP INVALID STATE USBD_ERR_EP INVALID TYPE USBD_ERR_OS TIMEOUT USBD_ERR_OS ABORT USBD_ERR_OS FAIL 278 RETURNED VALUE Number of octets received If no error s 0 otherwise CALLERS USB device class drivers NOTES WARNINGS This function blocks until m All data is received or E An error occurred E Transfer does not complete in the period specified by timeout_ms 279 Appendix A A 4 10 USBD_IntrRxAsync Receives data on interrupt OUT endpoint asynchronously FILES
124. FG_MAX_NBR_REPORTL_ID 143 USBD_HID_CFG_MAX_NBR_REPORT_PUSHPOP 143 USBD_HID_Init A 144 388 USBD_HID_ISCoOnmn eecceeceeeeeeeeeeeeeeeeeeeeeeteeeteneeeaee 393 USBD_HID_OS_CFG_TMR_TASK_PRIO nsnoneneneeneeen 143 USBD_HID_OS_CFG_TMR_TASK_STK_SIZE 143 USBD_HID_OS_InitQ oe eee eeeeeeeeeeeeeeeees 161 402 USBD_HID_OS_InputDataPend A 161 405 USBD_HID_OS_InputDataPendAborrt 161 407 USBD_HID_OS_InputDataPost 161 408 USBD_HID_OS_InputLock USBD_HID_OS_InputUnlock USBD_HID_OS_OutputDataPend 0 161 411 USBD_HID_OS_OutputDataPendAbort 161 413 USBD_HID_OS_OutputDataPost USBD_HID_OS_OutputLock USBD_HID_OS_OutputUnlock USBD_HID_OS_TmrTask USBD_HID_OS_TmrTask USBD_HID_OS_TxLock USBD_HID_OS_TxUnlock 161 416 USBD_HID_Rd 150 158 160 394 USBD_HID_RdAsync O 150 396 USBD_HID_Wr 150 157 158 160 163 398 USBD_HID_WrAsync O 150 400 USBD_IF_Add USBD_IF_AltAdd USBD_IF_Grp USBD_Init USBD_IntrAdd USBD_IntrRx USBD_IntrRxAsync USBD_IntrTx USBD_IntrTxAsync USBD_MSC_Add USBD_MSC_CfgAdd Q USBD_MSC_CFG_DATA_LEN USBD_MSC_CFG_MAX_LUN USbPD MSC CEO MAX NPP CEO ee 74 173 USBD_MSC_CFG_MAX_NBR_DEV 0 ee 74 173 USBD_MSC_Init USBD_MSC_IsConn USBD_MSC_LunAddQ USBD_MSC_OS_CFG_TASK_
125. GUMENTS timeout Timeout in milliseconds p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_OS TIMEOUT USBD_ERR_OS FAIL RETURNED VALUE None CALLERS Various NOTES WARNINGS None 433 Appendix E E 3 MSC STORAGE LAYER FUNCTIONS E 3 1 USBD_Storagelnit Initialize internal structures and local global variables used by the storage medium FILES usbd_storage h usbd_storage c PROTOTYPE void USBD_StorageInit USBD_ STORAGE LUN op storage lun USBD_ERR p err ARGUMENTS p_storage lun Pointer to logical unit storage structure p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR MEDIUM NOT PRESENT USBD_ERR_SCSI_LOG UNIT NOTRDY USBD_ERR_SCSI_LOG UNIT NOTSUPPORTED USBD_ERR_SCSI_LOG UNIT BUSY RETURNED VALUE None CALLERS USBD_SCSI_Init NOTES WARNINGS None 434 E 3 2 USBD_StorageCapacityGet Get the capacity of the storage medium FILES usbd_storage h usbd_storage c PROTOTYPE void USBD StorageCapacityGet USBD STORAGE LUN ap storage lun CPU_INT64U p nbr blks CPU_INT32U p blk size USBD_ERR p_err ARGUMENTS p storage lun Pointer to logical unit storage structure p_nbr_blks Pointer to variable that will receive the number of logical blocks p blk size Pointer to variable that will receive the size of each block in bytes p
126. HDC_OS WriIntrUnlock Unlocks write interrupt pipe USBD_PHDC_OS_Reset 204 Resets OS layer members Table 11 15 OS Layer API Summary Chapter 12 Vendor Class The Vendor class allows you to build vendor specific devices implementing for instance a proprietary protocol It relies on a pair of bulk endpoints to transfer data between the host and the device Bulk transfers are typically convenient for transferring large amounts of unstructured data and provides reliable exchange of data by using an error detection and retry mechanism Besides bulk endpoints an optional pair of interrupt endpoints can also be used Any operating system OS can work with the Vendor class provided that the OS has a driver to handle the Vendor class Depending on the OS the driver can be native or vendor specific For instance under Microsoft Windows your application interacts with the WinUSB driver provided by Microsoft to communicate with the vendor device 205 Chapter 12 12 1 OVERVIEW Figure 12 1 shows the general architecture between the host and the device using the Vendor class In this example the host operating system is Windows Windows PC Host Application USBDev_API 2 Winusb sys XZ Windows host stack A Control 0 i i IN amp OUT o Bulk Bulk Interrupt Interrupt IN OUT i IN OUT Vendor class i Ap
127. HID class a receive buffer for the Output report in the application task context This receive buffer will be used by the device stack s internal task upon reception of a SET_REPORT request The locking system ensures the receive buffer and related variables integrity BD A locking system is used to protect the interrupt IN endpoint access from multiple application tasks PB A synchronization mechanism is used to implement the blocking behavior of USBD_HID Rd when the control endpoint is used m A synchronization mechanism is used to implement the blocking behavior of USBD_HID Wr because the HID class internally uses the asynchronous interrupt API for HID write P A task is used to process periodic Input reports Refer to section 9 6 Periodic Input Reports Task on page 161 for more details about this task By default Micrium will provide an RTOS layer for both pC OS II and pC OS III However it is possible to create your own RTOS layer Your layer will need to implement the functions listed in Table 9 9 For a complete API description refer to Appendix D HID API Reference on page 387 160 Periodic Input Reports Task Function name Operation USBD_HID OS Init Creates and initializes the task and semaphores USBD_HID OS InputLock Locks Input report USBD_HID OS InputUnlock Unlocks Input report USBD_HID OS InputDataPend Waits for Input report data write completion
128. ING THE DEMO APPLICATION The mouse demo does not require anything on the Windows side You just need to plug the HID device running the mouse demo to the PC and see the screen cursor moving Figure 9 3 presents the mouse demo with the host and device interactions Windows PC USB Device Host 1 Mouse task el Ta Input report Send input report Figure 9 3 HID Mouse Demo 156 F9 3 1 F9 3 2 Using the Demo Application On the device side the task App USBD_HID MouseTask simulates a mouse movement by setting the coordinates X and Y to a certain value and by sending the Input report that contains these coordinates The Input report is sent by calling the USBD_HID Wr function through the interrupt IN endpoint The mouse demo does not simulate any button clicks only mouse movement The host Windows PC polls the HID device periodically following the polling interval of the interrupt IN endpoint The polling interval is specified in the Endpoint descriptor matching to the interrupt IN endpoint The host receives and interprets the Input report content The simulated mouse movement is translated into a movement of the screen cursor While the device side application is running the screen cursor moves endlessly The vendor specific demo requires you to launch a Windows executable Two executables are already provided in the following folder P Micrium Software uC USB Device V4 App Hos
129. Initializes MSC internal structures and variables USBD_MSC_Add Adds a new instance of the MSC USBD_MSC_CfgAdd Adds existing MSC instance into USB device configuration USBD_MSC_LunAdd Adds a LUN to the MSC interface Table 10 6 Class Instance API Functions To successfully initialize the MSC you need to follow these steps 174 Call USBD_MSC_Init This is the first function you should call and it should be called only once regardless of the number of class instances you intend to have This function will initialize all internal structures and variables that the class will need It will also initialize the real time operating system RTOS layer Call USBD_MSC_Add This function will add a new instance of the MSC Call USBD_MSC_CfgAdd Once the class instance is correctly configured and initialized you will need to add it to a USB configuration High speed devices will build two separate configurations one for full speed and one for high speed by calling USBD_MSC_CfgAdd for each speed configuration 4 Call USBD_MSC_LunAdd Configuration Lastly you add a logical unit to the MSC interface by calling this function You will specify the type and volume of the logical unit you want to add as well as device details such as vendor ID product ID product revision level and read only Logical units are added by a device driver string name composed of the storage device driver name and the logical unit nu
130. LLERS Application NOTES WARNINGS The function USBDev_GetNbrDev uses the concept of device information set A device information set consists of device information elements for all the devices that belong to some device setup class or device interface class The GUID passed to USBDev_GetNbrDev function is a device interface class Internally by using some control options the function retrieves the device information set which represents a list of all devices present in the system and registered under the specified GUID More details about the device information set can be found at http msdn microsoft com en us library 541247 VS 85 aspx 498 G 2 2 USBDev_Open Open a device by retrieving a general device handle FILES usbdev_api c PROTOTYPE HANDLE USBDev_Open const GUID guid_dev if DWORD dev_nbr DWORD p err ARGUMENTS guid_dev_if Device interface class GUID dev_nbr Device number p err Pointer to variable that will receive the return error code from this function ERROR_SUCCESS ERROR_INVALID PARAMETER ERROR HOT ENOUGH MEMORY ERROR BAD DEVICE RETURNED VALUE Handle to device if NO error s INVALID HANDLE VALUE otherwise CALLERS Application NOTES WARNINGS None 499 Appendix G G 2 3 USBDev_Close Close a device by freeing any allocated resources and by releasing any created handles FILES usbdev_api c PROTOTYPE void USBDev_Close HANDLE dev DWORD
131. MENTS class nr CDC instance number dev_nbr Device number cfg_nbr Configuration number p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_ALLOC USBD_ERR_ INVALID ARG USBD_ERR DEV INVALID NBR USBD_ERR_ DEV INVALID STATE USBD_ERR CFG INVALID NBR USBD_ERR_IF ALLOC USBD_ERR_IF ALT ALLOC USBD_ERR_IF INVALID NBR USBD_ERR_IF GRP NBR_IN USE USBD_ERR_IF GRP ALLOC USBD_ERR_EP NONE AVAIL USBD_ERR_EP ALLOC 358 RETURNED VALUE DEF_OK if CDC class instance was added to device configuration successfully DEF_FAIL otherwise CALLERS CDC Subclass drivers NOTES WARNINGS None 359 Appendix C C 1 4 USBD_CDC IsConn Determine if CDC instance is connected FILES usbd_cde h usbd_cdce c PROTOTYPE CPU_BOOLEAN USBD_CDC_IsConn CPU_INTO8U class_nbr ARGUMENTS class nbr CDC instance number RETURNED VALUE DEF_OK if CDC instance is connected and device is not in suspended state DEF_FAIL otherwise CALLERS E CDC Subclass drivers E Application NOTES WARNINGS If the USBD_CDC_IsConn returns DEF_OK than the CDC instance is ready for management notification read and write operations 360 C 1 5 USBD_ CDC DatalF_Add Add a data interface class to CDC FILES usbd_cde h usbd_cdce c PROTOTYPE CPU_INTO8U USBD_CDC_DataIF Add CPU_INTO8U class_nbr CPU_BOOLEAN isoc_en CPU_INTO8U protocol USBD_ERR Zp err
132. NA EAREN 171 Mass Storage Task Handler u ceccesseeseeeeeeeeeeeeeeeeeseeeeessaneeeeeeeeenees 171 COMMOUPAUION EE 173 General Configuration ee EEN EEN 173 Class Instance Configuration cc ssceeceesseeeeeeeeeeeeeeeeeseeeeeeeneneeneeeenees 174 Using the Demo Application ccccesseeeeeeeeeeeeeeeeeeeeeeeseeneeeeeeeeeeees 176 10 5 1 10 5 2 10 6 10 7 Chapter 11 11 1 11 1 1 11 1 2 11 2 11 2 1 11 2 2 11 3 11 3 1 11 3 2 11 4 11 5 11 5 1 11 5 2 11 6 Chapter 12 12 1 12 2 12 2 1 12 2 2 12 2 3 12 2 4 12 2 5 12 3 12 3 1 12 3 2 12 4 12 4 1 12 4 2 12 4 3 12 4 4 USB Device Application EEN 177 USB Host Application arn Eaa aaa aree aaae dee REES SEET 179 Porting MSC to a Storage Layer cccesseeeceeseseeeeeeeeseeeeseeeeseeeeeeeeeeeees 180 Porting MSC toa EE 181 Personal Healthcare Device Class ceeeceeeeeeeeeeeeseeeeneeeeeeeenees 183 EE 184 Data Characteristics sssini innisin aaaea enoatu aiaia aaeeeiai 184 Operational model use 185 Contigua ON EE 187 General configuration cececeesteeeeeeeeeeeeeeeeeeeneeeeesecneeeeeseenseeeeseceneeeeess 187 Class instance configuration ceeeeeteeeeeeeeeeeeeeeeeeeeeeeeseeeeeeeeenseneeeenees 189 Class Instance COMMUNICATION ccccceeeeeeseeeeee eee eeeeeeeeeeeeeeseeeneeees 192 Communication with metadata preamble ccccccecceeeeeeeeeseeneeeees 192 Communication without metadata preamble ccceeesseeeeeeeeeeees 196
133. NINGS None 395 Appendix D D 1 6 USBD_HID_RdAsync This function receives data from the host asynchronously through an interrupt OUT endpoint FILES usbd_hid c PROTOTYPE void USBD_HID RdAsyne CPU_INTO8U class_nbr void p buf CPU_INT32U buf_len USBD_HID_ASYNC_FNCT async_fnct void p async arg USBD_ERR p err ARGUMENTS class nr Class instance number p buf Pointer to receive buffer buf len Receive buffer length in octets async _fnct Receive callback p async org Additional argument provided by application for receive callback p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_NULL PTR USBD_ERR_INVALID ARG USBD_ERR_ INVALID CLASS STATE USBD_ERR_ FAIL USBD_ERR DEV INVALID NBR USBD_ERR_EP INVALID NBR 396 USBD_ERR DEV INVALID STATE USBD_ERR_EP INVALID TYPE USBD_ERR_ EP INVALID STATE RETURNED VALUE None CALLERS Application NOTES WARNINGS This function is non blocking and returns immediately after transfer preparation Upon transfer completion the callback provided is called to notify the application 397 Appendix D D 1 7 USBD_HID_Wr This function transmits data to the host through an interrupt IN endpoint FILES usbd_hid c PROTOTYPE CPU_INT32U USBD_HID Wr CPU_INTO8U class_nbr void p buf CPU_INT32U buf_len CPU_INT16U timeout USBD_ERR p err ARGUMENTS class nr Class instance num
134. NOTES WARNINGS Typically the set configuration function sets the device as configured For some controllers this may not be necessary 331 Appendix B B 1 7 USBD_DrvCfgCir Bring device into de configured state FILES Every device driver s usbd_drv c PROTOTYPE static void USBD DrvCfgClr USBD_DRV p drv CPU_INTO8U cfg val ARGUMENTS p drv Pointer to USB device driver structure cfg_val Configuration value RETURNED VALUE None CALLERS USBD_CfgClose via p drv_api gt CfgClr NOTES WARNINGS E Typically the clear configuration function sets the device as not being configured For some controllers this may not be necessary E This functions in invoked after a bus reset or before the status stage of some SET_CONFIGURATION requests 332 B 1 8 USBD_DrvGetFrameNbr Retrieve current frame number FILES Every device driver s usbd_drv c PROTOTYPE static CPU_INT16U USBD DrvGetFrameNbr USBD_DRV p drv ARGUMENTS p drv Pointer to USB device driver structure RETURNED VALUE Frame number CALLERS None NOTES WARNINGS None 333 Appendix B B 1 9 USBD_DrvEP_Open Open and configure a device endpoint given its characteristics e g endpoint type endpoint address maximum packet size etc FILES Every device driver s usbd_drv c PROTOTYPE static void USBD DrvEP_Open USBD_DEV p drv CPU_INT08U ep addr CPU_INTO8U ep_type CPU_LINT
135. NOTRDY RETURNED VALUE None CALLERS Application NOTES WARNINGS The pointer to logical unit driver specifies the type and volume of the logical unit to add Valid logical unit driver names follow the pattern lt device_driver_name gt lt logical_unit_number gt where lt device driver name gt is the name of the device driver and lt logical_unit_number gt is the device s logical unit number Take special note that the logical unit number starts counting from number 0 425 Appendix E E 1 5 USBD_MSC IsConn Get MSC connection state of the device FILES usbd_msc h usbd_msc c PROTOTYPE CPU_BOOLEAN USBD _MSC_IsConn CPU_INTO8U class_nbr ARGUMENTS class_nbr MSC instance number RETURNED VALUE DEF_YES if MSC is connected DEF_NO otherwise CALLERS Application NOTES WARNINGS USBD_MSC_ IsConn is typically used to verify that the device is in configured state and that the MSC instance is ready for communication The following code illustrates a typical example CPU_BOOLEAN conn conn USBD_MSC_IsConn class_nbr if conn DEF YES USBD_MSC_OS_EnumSignalPend CPU_INT16U 0 Sos err Once the connected status is DEF_YES the communication can start 426 E 1 6 USBD_MSC_TaskHandler Task to handle transfers for the MSC bulk only transport protocol FILES usbd_msc h usbd_msc c PROTOTYPE void USBD_MSC_TaskHandler CPU_INTO8U class_nbr ARGUM
136. NTERFACE FUNCTIONS A 3 1 USBD_IF_Add Send data on CDC data class interface FILES usbd_cde h usbd_cdc c PROTOTYPE CPU_INTO8U USBD_IF Add CPU_INTO8U dev_nbr CPU_INTO8U cfg_nbr USBD_CLASS DV sp class dru void p class arg CPU_INTO8U class_code CPU_INTO8U class_sub_code CPU_INTO8U class_protocol_code const CPU_CHAR p_name USBD_ERR p err ARGUMENTS dev_nbr Device number cfg_nbr Configuration index to add the interface p_class drv Pointer to interface driver p_class_arg Pointer to interface driver argument class_code Class code assigned by the USB IF class sub code Subclass code assigned by the USB IF class protocol_code Protocol code assigned by the USB IF p_name Pointer to string describing the Interface 255 Appendix A p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_INVALID ARG USBD_ERR NULL PTR USBD_ERR DEV INVALID NBR USBD_ERR DEV INVALID STATE USBD_ERR CFG INVALID NBR USBD_ERR_IF ALLOC USBD_ERR_IF ALT ALLOC RETURNED VALUE None CALLERS USB Class drivers NOTES WARNINGS Interface number If no error s USBD_IF NBR NONE otherwise 256 A 3 2 USBD_IF_AltAdd Adds an alternate setting to a specific interface FILES usbd_core h usbd_core c PROTOTYPE CPU_INTO8U USBD_IF AltAdd CPU_INTO8U dev_nbr CPU_INTO8U cfg_nbr CPU_LINTO8U if nbr const CPU_CHAR p name USBD_ERR KEE EI ARGUMENTS dev
137. None 490 G 1 10 USBD_ Vendor _IntrWr Send data to host through Interrupt IN endpoint This function is blocking FILES usbd_vendor c PROTOTYPE CPU_INT32U USBD_Vendor_IntrWr CPU_INT08U class_nbr void p buf CPU_INT32U buf_len CPU_INT16U timeout CPU_BOOLEAN end USBD_ERR p err ARGUMENTS class nr Class instance number p_buf Pointer to transmit buffer buf_len Transmit buffer length in octets timeout Timeout in milliseconds end End of transfer flag p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR NULL PTR USBD_ERR_INVALID ARG USBD_ERR_ INVALID CLASS STATE USBD_ERR_ DEV INVALID NBR USBD_ERR_ EP INVALID NBR USBD_ERR DEV INVALID STATE USBD_ERR_EP INVALID TYPE 491 Appendix G RETURNED VALUE Number of octets sent if NO error s 0 otherwise CALLERS Application NOTES WARNINGS If end of transfer flag is set and transfer length is multiple of maximum packet size a zero length packet is transferred to indicate the end of transfer to the host 492 G 1 11 USBD_Vendor_IntrRdAsync Receive data from host through Interrupt OUT endpoint This function is non blocking It returns immediately after transfer preparation Upon transfer completion a callback provided by the application will be called to finalize the transfer FILES usbd_vendor c PROTOTYPE void USBD_Vendor_IntrRdAsync CPU_INTO8U class_nbr
138. OCOL AT PCCA_101 ANNEX USBD_CDC_COMM PROTOCOL AT GSM 7 07 USBD_CDC_COMM PROTOCOL AT 3GPP_27 07 USBD_CDC_COMM PROTOCOL AT TIA CDMA USBD_CDC_COMM PROTOCOL EEM USBD_CDC_COMM PROTOCOL EXT USBD_CDC_COMM PROTOCOL VENDOR CDC protocol codes are defined in the Universal Serial Bus Class Definitions for Communication Devices Revision 2 1 Table 5 notify en Notification enabled DEF_ENABLED CDC notifications are enabled DEF_DISABLED CDC notifications are disabled notify interval Notification interval in milliseconds p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_ALLOC RETURNED VALUE CDC class interface number if CDC class successfully created USBD_CDC_NBR_NONE otherwise 356 CALLERS CDC Subclass drivers NOTES WARNINGS The CDC defines a communication class interface consisting of a management element and optionally a notification element The notification element transports event to the host The enable en enable notifications in the CDC The notification are sent to the host using an interrupt endpoint the interval of the interrupt endpoint is specified by the notify interval parameter 357 Appendix C C 1 3 USBD_CDC CfgAdd Add a CDC instance to specific USB configuration FILES usbd_cde h usbd_cdce c PROTOTYPE CPU_BOOLEAN USBD_CDC_CfgAdd CPU_INTO8U class_nbr CPU_LINTO8U dev_nbr CPU_INTO8U cfg_nbr USBD_ERR p err ARGU
139. ODING SET LINE CODING SET CONTROL LINE STATE to your device Note that Windows Vista and later don t provide HyperTerminal anymore You may use other free serial terminals such TeraTerm http ttssh2 sourceforge jp Hercules http www hw group com products hercules index_en htm1 RealTerm http realterm sourceforge net etc In order to start the communication with the serial task on the device side the Data Terminal Ready DTR signal must be set and sent to the device The DTR signal prevents the serial task from sending characters if the terminal is not ready to receive data Sending the DTR signal may vary depending on your serial terminal For example HyperTerminal sends a properly set DTR signal automatically upon opening of the COM port Hercules terminal allows you to set and clear the DTR signal from the graphical user interface GUD with a checkbox Other terminals do not permit to set clear DTR or the DTR set clear s functionality is difficult to find and to use Once the serial task receives the DTR signal the task sends a menu to the serial terminal with two options as presented in Figure 8 5 ACM Subclass F8 4 4 The menu option 1 is the Echo 1 demo It allows you to send one unique character to the device This character is received by the serial task and sent back to the host F8 4 5 The menu options 2 is the Echo N demo It allows you to send several characters to the device All the characters are
140. OTYPE static void USBD_DrvEP_Close USBD_DRV Sp dru CPU_INTO8U ep_addr ARGUMENTS p drv Pointer to USB device driver structure ep_addr Endpoint address RETURNED VALUE None CALLERS E USBD_EP Close via p drv_api gt EP_Close E USBD_CtrlOpen NOTES WARNINGS Typically the endpoint close function clears the endpoint information in the device controller For some controllers this may not be necessary 336 B 1 11 USBD_DrvEP_RxStart Configure endpoint with buffer to receive data FILES Every device driver s usbd_drv c PROTOTYPE static void USBD DrvEP_RxStart USBD_DRV p dru CPU_INTO8U ep addr CPU_LINTO8U p buf CPU_INT32U buf len USBD_ERR p err ARGUMENTS p drv Pointer to USB device driver structure ep_addr Endpoint address p buf Pointer to data buffer buf_len Length of the buffer p err Pointer to variable that will receive the return error code from this function RETURNED VALUE None CALLERS E USBD_EP Rx via p drv _api gt EP_Rx E USBD_EP Process 337 Appendix B NOTES WARNINGS Typically the function to configure the endpoint receive transaction performs the following operations E Determine maximum transaction length given the specified length of the buffer buf_len E Setup receive transaction 338 B 1 12 USBD_DrvEP_Rx Receive the specified amount of data from device endpoint FILES Every device driver s usbd_drv
141. One of the typical ways to connect these devices to a computer is by using a USB connection and that s why PHDC has been developed Although PHDC is a standard most modern Operating Systems OS do not provide any specific driver for this class When working with Microsoft Windows developers can use the WinUsb driver provided by Microsoft to create their own driver The Continua Health Alliance also provides an example of a PHDC driver based on libusb an open source USB library for more information see http www libusb org This example driver is part of the Vendor Assisted Source Code VASC 183 Chapter 11 11 1 OVERVIEW 11 1 1 DATA CHARACTERISTICS Personal healthcare devices due to their nature may need to send data in 3 different ways E Episodic Data is sent sporadically each time user accomplishes a specific action E Store and forward data is collected and stored on device while it is not connected The data is then forwarded to the host once it is connected E Continuous Data is sent continuously to the host for continuous monitoring Considering these needs data transfers will be defined in terms of latency and reliability PHDC defines three levels of reliability and four levels of latency P Reliability Good better and best E Latency Very high high medium and low For example a device that sends continuous data for monitoring will send them as low latency and good reliability PHDC does not s
142. PRIO USBD_MSC_OS_CFG_TASK_STK_SIZE USBD_MSC_OS_CommSignalDel 00 USBD_MSC_OS_CommSignalPend 4 USBD_MSC_OS_CommSignalPost A USBD_MSC_OS_EnumSignalPend 26 USBD_MSC_OS_EnumSignalPosi USBD_MSC_OS_Init USBD_MSC_TaskHandler 426 USBD_OS_CFG_CORE_TASK_PRIO USBD_OS_CFG_CORE_TASK_STK_SIZE USBD_OS_CFG_TRACE_TASK_PRIO USBD_OS_CFG_TRACE_TASK_STK_SIZE USBD_OS_CoreEventGet USBD_OS_CoreEventPut USBD_OS_DbgEventRady USBD_OS_DbgEventWait USBD_OS_DbgEventWait USBD_OS_EP_SignalAbort 00 0 cece 242 310 USBD_OS_EP_SignalCreate 0008 238 242 302 USBD_OS_EP_SignalDel AA 242 304 USBD_OS_EP_SignalPend A 242 305 USBD_OS_EP_SignalPost AA 242 308 USbBD OS Initia 242 298 USBD_OS_Q Post cecceeecceceeeeeeeeeeeeeeeseeeeeeeeteeeeeeeeeaee 238 USBD_OS_SemCreate AA 238 USBD_OS_TaskCreate A 238 USBD_PHDC_11073_ExtCfg eee 189 190 452 USBD_PHDC_Add A 189 193 195 443 USBD_PHDC_CfgAdd 189 190 445 USBD_PHDC_CFG_DATA_OPAQUE_MAX_LEN 187 USBD_PHDC_CFG_MAX_NBR_CFG eneen 74 187 USBD_PHDC_CFG_MAX_NBR_DEV nee 74 187 USBD_PHDC_Init USBD_PHDC_IsConn Q USBD_PHDC_LATENCY_HIGH_RELY_BEST USBD_PHDC_LATENCY_LOW_RELY_GOOD USBD_PHDC_LATENCY_MEDIUM_RELY_BEST USBD_PHDC_LATENCY_MEDIUM_RELY_BETTER USBD_PHDC_LATENCY_MEDIUM_REL
143. QUIREMENT Endpoint zero also known as Default Endpoint is a bi directional endpoint used by the USB host system to get information and configure the device via standard requests All devices must implement an endpoint zero configured for control transfers see section Control Transfers on page 18 for more information 17 Chapter 7 1 2 2 PIPES A USB pipe is a logical association between an endpoint and a software structure in the USB host software system USB pipes are used to send data from the host software to the device s endpoints A USB pipe is associated to a unique endpoint address type of transfer maximum packet size and interval for transfers The USB specification defines two types of pipes based on the communication mode E Stream Pipes Data carried over the pipe is unstructured E Message Pipes Data carried over the pipe has a defined structure The USB specification requires a default control pipe for each device A default control pipe uses endpoint zero The default control pipe is a bi directional message pipe 1 2 3 TRANSFER TYPES The USB specification defines four transfer types that match the bandwidth and services requirements of the host and the device application using a specific pipe Each USB transfer encompasses one or more transactions that sends data to and from the endpoint The notion of transactions is related to the maximum payload size defined by each endpoint type in that when a
144. R_IF GRP 0 USBD_CFG MAX NBR_EP DESC 2 USBD_CFG MAX NBR_EP OPEN 4 USBD_VENDOR_CFG MAX NBR_DEV 1 USBD_VENDOR_CFG MAX NBR_CFG 2 Table I 11 Vendor Class Configuration for Memory Footprint Module Code kB Constant kB Data kB Device Core 18 18 E 0 85 Device RTOS Port 0 76 S 1 35 Device Controller 6 74 0 21 Data allocated from heap Driver Vendor 1 05 0 09 Total 26 73 0 21 2 29 Table l 12 Vendor Class Memory Footprint 537 Appendix 538 A abstraction layer eceecceeseeeeeeeeeeeeeeeeeeaeeeeeeseaeeeneeeeaeees ACM requests ACM subclass initialization API requests and notifications serial emulation app c app_ lt module gt c app_ lt module gt h app_cfg h APP_CFG_FS_BUF_CNT APP_CFG_FS_DEV_CNT APP_CFG_FS_DEV_DRV_CNT APP_CFG_FS_DIR_CNT APP_CFG_FS_EN APP_CFG_FS_FILE_CNT APP_CFG_FS_IDE_EN APP_CFG_FS_MAX_SEC_SIZE APP_CFG_FS_MSC_EN APP_CFG_FS_NBR_TEST APP_CFG_FS_NOR_EN APP_CFG_FS_RAM_EN APP_CFG_FS_RAM_NBR_SEC APP_CFG_FS_RAM_SEC_SIZE APP_CFG_FS_SD_CARD_EN APP_CFG_FS_SD_EN APP_CFG_FS_VOL_CNT APP_CFG_FS_WORKING_DIR_CNT APP_CFG_RX_ASYNC_EN APP_CFG_USBD_CDC_EN APP_CFG_USBD_CDC_SERIAL_TASK_PRIO 130 APP_CFG_USBD_CDC_SERIAL_TASK_STK_SIZE 130 APP_CFG_USBD_CDC_SERIAL_TEST_EN APP_CFG_USBD_EN APP_CFG_USBD_HID_EN APP_CFG_USBD_HID_MOUSE_TASK_PRIO APP_CFG_USBD_HID_READ_TASK_PRIO APP_CFG_USBD_HID_TASK_S
145. SBD_ERR_OS ABORT USBD_ERR_OS FAIL RETURNED VALUE None 289 Appendix A CALLERS USBD_Ctrl1TxStatus USB device class drivers NOTES WARNINGS None 290 A 4 15 USBD_EP_Abort Abort I O transfer on endpoint FILES usbd_core h usbd_ep c PROTOTYPE void USBD_EP Abort CPU_INTO08U dev_nbr CPU_INTO8U ep addr USBD_ERR p err ARGUMENTS dev_nbr Device number ep_addr Endpoint address p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR DEV INVALID NBR USBD_ERR_EP INVALID ADDR USBD_ERR_ EP INVALID STATE USBD_ERR_EP ABORT USBD_ERR_ EP OS FAIL RETURNED VALUE None CALLERS USBD EP Stall USB device class drivers NOTES WARNINGS None 291 Appendix A A 4 16 USBD ER Sta Modify stall state condition on non control endpoints FILES usbd_core h usbd_ep c PROTOTYPE void USBD_EP Stall CPU_INTO8U dev_nbr CPU_INTO8U ep_addr CPU_BOOLEAN state USBD_ERR p err ARGUMENTS dev_nbr Device number ep addr Line control change notification callback see note 1 state Endpoint stall state DEF_SET Set stall condition DEF_NO Clear stall condition p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_ DEV INVALID ARG USBD_ERR_ EP INVALID ADDR USBD_ERR_ EP INVALID STATE USBD_ERR_EP STALL USBD_ERR_EP ABORT USBD_ERR_OS FAIL RETURNED VALUE None 2
146. SBD_HID CA MOUSE 3 USBD_HID MAIN COLLECTION 1 USBD_HID COLLECTION _APPLICATION 4 USBD_HID LOCAL USAGE 1 USBD_HID CP POINTER 5 USBD_HID MAIN COLLECTION 1 USBD_HID COLLECTION PHYSICAL 6 7 USBD_HID GLOBAL USAGE PAGE 1 USBD HID USAGE PAGE BUTTON USBD_HID LOCAL USAGE MIN 1 0x01 USBD_HID LOCAL USAGE MAX 1 0x03 USBD_HID GLOBAL LOG MIN 1 0x00 USBD_HID GLOBAL LOG MAX 1 0x01 USBD_HID GLOBAL REPORT COUNT 1 0x03 USBD_HID GLOBAL REPORT SIZE 1 0x01 USBD_HID MAIN INPUT 1 USBD_HID MAIN DATA USBD_HID MAIN VARIABLE USBD_HID_ MAIN ABSOLUTE 8 USBD_HID GLOBAL REPORT COUNT 1 0x01 USBD_HID GLOBAL REPORT SIZE 1 0x0D USBD_HID MAIN INPUT 1 USBD_HID MAIN CONSTANT 9 USBD_HID GLOBAL USAGE PAGE 1 USBD_HID USAGE PAGE GENERIC_DESKTOP_CONTROLS USBD_HID LOCAL USAGE 1 USBD_HID DV X USBD_HID LOCAL USAGE 1 USBD_HID DV_Y USBD_HID GLOBAL LOG MIN 1 0x81 USBD_HID GLOBAL LOG MAX 1 Ox7F USBD_HID GLOBAL REPORT SIZE 1 0x08 USBD_HID GLOBAL REPORT COUNT 1 0x02 USBD_HID MAIN INPUT 1 USBD_HID MAIN DATA USBD_HID MAIN VARIABLE USBD_HID MAIN RELATIVE USBD_HID MAIN ENDCOLLECTION 10 USBD_HID MAIN ENDCOLLECTION 11 Jr Listing 9 2 Mouse Report Descriptor Example L9 2 1 The table representing a mouse Report descriptor is initialized in such way that each line corresponds to a short item The latter is formed from a 1 byte prefix and a 1 byte data Refer to Device Class Definit
147. Set this constant to the maximum period in ms that a user can specify for an item APP ITEM PERIOD MULTIPLE Set this constant to a multiple in ms that periodicity of items specified by the user must comply Table 11 14 Host Side Windows Demo Application s Configuration Constants Since Microsoft does not provide any specific driver for PHDC you will have to indicate to windows which driver to load using an inf file The inf file will ask Windows to load the WinUSB generic driver provided by Microsoft The application uses the USBDev_API which is a wrapper of the WinUSB driver refer to section 12 3 USBDev_API on page 214 Windows will ask for the INF file refer to section 3 1 1 About INF Files on page 46 the first time the device will be plugged in It is located in the following folder Micrium Software uC USB Device V4 App Host 0S Windows PHDC INF Once the driver is successfully loaded the Windows host application is ready to be launched The executable is located in the following folder Micrium Software uC USB Device V4 App Host 0S Windows PHDC Visual Studio 2010 exe 201 Chapter 11 11 5 2 RUNNING THE DEMO APPLICATION In this demo application you can ask the device to continuously send data of different QoS level and using a given periodicity Each requested transfer is called an item Using the monitor you can see each transfer s average periodicity and standa
148. TALL Device driver stall endpoint failed 407 USBD_ERR_EP_IO_PENDING I O operation pending on endpoint H 6 OS LAYER ERROR CODES 500 USBD_ERR_OS_INIT FAIL OS layer initialization failed 501 USBD_ERR_OS SIGNAL CREATE OS signal NOT successfully created 502 USBD_ERR_OS FAIL OS object Pend Post failed 503 USBD_ERR_OS_ TIMEOUT OS object timeout 504 USBD_ERR_OS_ABORT OS object abort 505 USBD_ERR_OS_DEL OS object delete 529 Appendix H 530 Appendix Memory Footprint pC USB Device s memory footprint can be scaled to contain only the features required for your specific application Refer to Chapter5 Configuration on page 65 to better understand how to configure the stack and your application This appendix will provide a reference to C USB Device s memory footprint for each associated device class offered by Micrium Each class presents a table of device configuration values that represents the configuration used for the footprint calculation All footprint values calculated in this appendix has been obtained with the environment configuration shown in Table I 1 and uC USB Device general configuration shown in Table I 2 Note that any Device Controller Driver offered by the pC USB Device stack can allocate internal data structures from the heap You can use memory functions from wC LIB common standard library functions macros and constants developed by Micrium to determine the amount of h
149. TATE PARITY Parity error USBD_ACM SERIAL STATE OVERUN Overrun RETURNED VALUE DEF_OK if new line state event set successfully DEF_FAIL otherwise CALLERS Application NOTES WARNINGS None 385 Appendix C C 2 13 USBD_ACM_SerialLineStateCir Clear one or several line state event s FILES usbd_acm_serial h usbd_acm_serial c PROTOTYPE CPU_BOOLEAN USBD ACM SerialLineStateSet CPU_INT08U subclass nbr CPU_INTO8U events ARGUMENTS subclass nbr CDC ACM serial emulation subclass instance number events Line state event s to clear see Note 1 USBD_ACM SERIAL STATE DCD DCD Rx carrier USBD_ACM SERIAL STATE DSR DSR Tx carrier RETURNED VALUE DEF_OK if new line state event clear successfully DEF_FAIL otherwise CALLERS Application NOTES WARNINGS E Universal Serial Bus Communications Class Subclass Specification for PSTN Devices version 1 2 states For the irregular signals like break the incoming ring signal or the overrun error state this will reset their values to zero and again will not send another notification until their state changes The irregular events are self clear and cannot be clear using this function 386 Appendix HID API Reference This appendix provides a reference to the Human Interface Device HID class API The following information is provided for each of the services A brief description The function prototype The filename of the source co
150. TK_SIZE APP_CFG_USBD_HID_TEST_MOUSE_EN APP_CFG_USBD_HID_WRITE_TASK_PRIO APP_CFG_USBD_MSC_EN Index APP_CFG_USBD_VENDOR_ECHO_ASYNC_EN 221 APP_CFG_USBD_VENDOR_ECHO_ASYNC_TASK_PRIO 221 APP_CFG_USBD_VENDOR_ECHO_SYNC_EN 221 APP_CFG_USBD_VENDOR_ECHO_SYNC_TASK_PRIO 221 APP_CFG_USBD_VENDOR_EN c eee eee 221 APP_CFG_USBD_VENDOR_TASK_STK_SIZE 221 APP_CFG_USBD_XXXX_EN u coe eects eee eee teens 39 App_DevPathStr app_hid_common c application CONFIQUIATION 00 AAEE EEE EAEE configuration constants configuration file modules relationship we Preprocessor Constants 2 0 ceeeeeeseeeeseeeeeeneeeeeees APP_MAX_NBR_VENDOR_DEV app_usbd Ce DEE app Uebd class ie WE BR TEE App_USBD_CDC_Init App_USBD_CDC_SerialLineCoding ee 126 App_USBD_CDC_SerialLineCitrl a App_USBD_HID_ Callback A 147 App_USBD_HID_Init 0 cece eeeeeeeeeeeeeeeeeeeaeeeeeees 43 App_USBD_HID_MouseTaskK A 157 App_USBD_HID_ReadTask uoces 158 App_USBD_HID_WriteTask eceeeeeeeeeeeeeeeeeeeeees 158 App_USBD_Init 0 0 00 ceeceeeceeeeeeeeeeeeeeeeeeeeeeteeeeeeee App_USBD_MSC_Init A App_USBD_PHDC_Init A APP_USDA_VENCON C AE App_USBD_Vendor_Init App_USBD_XXXX_Init APP_VENCOr_CCHO C 0 eeeeeeeeeeeeeeeeeeteeeteeeeteeeteeeeenee architecture block diagram e sea e eas
151. TS class_nbr MSC instance class number timeout Timeout in milliseconds p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_OS TIMEOUT USBD_ERR_OS FAIL RETURNED VALUE None CALLERS Various NOTES WARNINGS None 430 E 2 4 USBD_MSC OS CommSignalDel Delete a semaphore if no tasks are waiting on it for MSC communication FILES usbd_msc_os h usbd_msc_os c PROTOTYPE void USBD_MSC_OS CommSignalDel CPU_INTO8U class_nbr USBD_ERR p err ARGUMENTS class _nbr MSC instance class number p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_OS FAIL RETURNED VALUE None CALLERS Various NOTES WARNINGS None 431 Appendix E E 2 5 USBD_MSC OS EnumSignalPost Post a semaphore for MSC enumeration process FILES usbd_msc_os h usbd_msc_os c PROTOTYPE void USBD_MSC_OS_EnumSignalPost USBD_ERR p err ARGUMENTS p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_OS FAIL RETURNED VALUE None CALLERS Various NOTES WARNINGS None 432 E 2 6 USBD_MSC OS EnumSignalPend Wait on a semaphore to become available for MSC enumeration process FILES usbd_msc_os h usbd_msc_os c PROTOTYPE void USBD_MSC_OS EnumSignalPend CPU_INT32U timeout USBD_ERR p err AR
152. Time Library app_cfg h usbd_cfg h cpu_cfg h os_cfg h 1lib_def h app c usbd_dev_cfg c h os_app_cfg c h lib mem c h lib mem az app_usbd c lib_str c h Application Layer PHDC g Vendor usbd_phdc c h ACM Serial usbd_vendor c h Emulation usbd acm serial c h MSC usbd msc c h HID usbd_hid c h HID Report Manager usbd_report c h SCSI Commands usbd_scsi c h Storage Driver usbd_storage c h USB Classes Endpoint Core usbd_core c h Management J usbd_ep c USB Core iced Peal Sa ae RTOS RTOS Device Controller Classes Core amp EP Driver usbd_hid_os c h usbd_os c h usbd_drv_ lt name gt c h usbd_phdc_os c h usbd_msc_os c h Device Controller BSP RTOS usbd_ bsp lt name gt c h and Hardware Abstraction CPU cpu_core c h cpu h cpu_c c cpu_a Figure 4 1 pC USB Device Architecture Block Diagram 54 Modules Relationship 4 1 MODULES RELATIONSHIP 4 1 1 APPLICATION Your application layer needs to provide configuration information to pC USB Device in the form of four C files app_cfg h usbd_cfg h usbd_dev_cfg c and usbd_dev_cfg h E app cfg h is an application specific configuration file It contains defines to specify task priorities and the stack size of each of the task within the application and the task required by pC USB Device Some small Micrium modules like pC LIB run time library use app _cfg h to configure parameters such as the he
153. UNCTIONS F 1 1 USBD_PHDC_Init Initialize internal structures and local global variables used by the PHDC FILES usbd_phdc h usbd_phdc c PROTOTYPE void USBD_PHDC Init USBD_ERR p err ARGUMENTS p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE RETURNED VALUE None CALLERS Application NOTES WARNINGS None 442 F 1 2 USBD_PHDC_ Addi Create a new instance of the PHDC FILES usbd_phdc h usbd_phdc c PROTOTYPE CPU_INTO8U USBD_PHDC Add CPU BOOLEAN data_fmt 11073 CPU_BOOLEAN preamble capable USBD_PHDC_PREAMBLE EN NOTIFY preamble en notify CPU_INT16U low_latency_interval USBD_ERR p err ARGUMENTS data_fmt_11073 preamble _ capable preamble en notify low_latency_ interval Variable that indicates whether the class instance uses IEEE 11073 or a vendor defined data format DEF_YES Class instance uses IEEE 11073 data format DEF_NO Class instance uses vendor defined data format Variable that indicates whether the class instance support metadata message preamble or not DEF_YES Class instance support metadata message preamble DEF_NO Class instance doesn t support metadata message preamble Pointer to a callback function that will notify the application if the host enable disable metadata message preamble Interrupt endpoint interval in frames or microframes Can be 0 if PHDC device will not send low latency data
154. USBD_DrvEP_RxStart is invoked On DMA based controllers this device driver API is responsible for queuing a receive transfer The queued receive transfer does not need to satisfy the whole requested transfer length at once If multiple transfers are queued only the last queued transfer must be signaled to the USB device stack This is required since the USB device stack iterates through the receive process until all requested data or a short packet has been received On FIFO based controllers this device driver API is responsible for enabling data to be received into the endpoint FIFO including any related ISR s While data is being received the device synchronous receive operation waits on the device receive signal The USB device controller triggers an interrupt request when it is finished receiving the data This invokes the USB device driver interrupt service routine CSR handler directly or indirectly depending on the architecture Inside the USB device driver ISR handler the type of interrupt request is determined to be a receive interrupt USBD_EP RxCmpl is called to unblock the device receive signal The device receive operation reaches the USBD_EP_Rx which internally calls USBD_DrvEP_Rx On DMA based controllers this device driver API is responsible for de queuing the completed receive transfer and returning the amount of data received In case the DMA based controller requires the buffered data to be placed in a
155. USBD_HID OS InputDataPendAbort Aborts the wait for Input report data write completion USBD_HID OS InputDataPost Signals that Input report data has been sent to the host USBD_HID OS OutputLock Locks Output report USBD_HID OS OutputUnlock Unlocks Output report USBD_HID OS OutputDataPend Waits for Output report data read completion USBD_HID OS OutputDataPendAbort Aborts the wait for Output report data read completion USBD_HID OS OutputDataPost Signals that Output report data has been received from the host USBD_HID_OS_TxLock Locks class transmit USBD_HID_OS_TxUnlock Unlocks class transmit USBD_HT D OS _TmrTask Task processing periodic input reports Refer to section 9 6 Periodic Input Reports Task on page 161 for more details about this task Table 9 9 HID OS Layer API Summary 9 6 PERIODIC INPUT REPORTS TASK In order to save bandwidth the host has the ability to silence a particular report in an interrupt IN endpoint by limiting the reporting frequency The host sends the SET_IDLE request to realize this operation The HID class implemented by Micrium contains an internal task responsible for respecting the reporting frequency limitation applying to one or several input reports Figure 9 7 shows the periodic input reports tasks functioning 161 Chapter 9 F9 7 1 F9 7 2 F9 7 3 162 Input reports ID list 1 SET_IDLE X 9 1 gt 2 5
156. VALUE Handle the error bulk_in_ handle USBDev_BulkIn Open dev_handle 0 0 Serr 3 if bulk_in_handle INVALID HANDLE VALUE Handle the error bulk_out_handle USBDev_BulkOut_Open dev_handle 0 0 amp err 3 if bulk_out_handle INVALID HANDLE VALUE Handle the error Communicate with the device 4 5 USBDev_PipeClose bulk_in handle amp err if err ERROR SUCCESS Handle the error 216 USBDev_API USBDev_PipeClose bulk_out_handle amp err if err ERROR SUCCESS Handle the error USBDev_Close dev_handle amp err 6 if err ERROR_SUCCESS Handle the error 112 41 L12 4 2 112 403 L12 4 4 L12 4 5 L12 4 6 Listing 12 4 USBDev_API Device and Pipe Management Example Get the number of devices connected to the host under the specified GUID A GUID provides a mechanism for applications to communicate with a driver assigned to devices in a class The number of devices could be used in a loop to open at once all the devices In this example one device is assumed Open the device by retrieving a general device handle This handle will be used for pipe management and communication Open a bulk pipe by retrieving a pipe handle In the example a bulk IN and a OUT pipe are open If the pipe does not exist for this device an error is returned When opening a pipe the interface number
157. X_NBR_CFG 72 76 207 USBD_VENDOR_CFG_MAX_NBR_DEV 72 76 207 USBD_Vendor_Init 208 474 USBD_Vendor_IntrRd 210 212 489 USBD_Vendor_IntrRdAsync 210 214 493 USBD_Vendor_IntrWr 210 212 491 USBD_Vendor_IntrWrAsync USBD_Vendor_IsConn USBD_Vendor_Rd USBD_Vendor_RdAsync USBD_Vendor_Wr USBD_Vendor_WrAsync USBD_XXXX_Add USBD_XXXX_CfgAdd USBD_XXXX_CFG_MAX_NBR_CFG USBD_XXXX_CFG_MAX_NBR_DEV usbser sys V Vendor class architecture communication communication API configuration Configuration constants 0 0 eee eeeee eee teeeeeeeeteeeeeeee demo application endpoints functions initialization initialization API memory footprint VendorReq virtual COM port W Windows application Constants cceeeeeeeeteeeeeeee 222 Windows drivers Winusb dll Winusb sys WinUSB_composite inf WinUSB single inf wrapper 546
158. Y_GOOD USBD_PHDC_LATENCY_VERYHIGH_RELY_BEST USpD PHDC OS CEOG SGCHED EN nnsnsnsnsnsisisisrsesenne USBD_PHDC_OS_CFG_SCHED_TASK_PRIO USBD_PHDC_OS_CFG_SCHED_TASK_STK_SIZE USBD_PHDC_OS_Init cece ccc eseeeeeeeeeeeneeeeeees USBD_PHDC_OS_RdLOCK ccccecceesseeeeeeeeeeteeeeeees USBD_PHDC_OS_RdUnLOCK e USBD_PHDC_OS_WrBulkLock 005 198 199 469 USBD_PHDC_OS_WrBulkSchedTask ecseee 198 USBD_PHDC_OS_WrBulkUnLock ccccesseeeeees 471 USBD_PHDC_OS_WrBulkUnlock e 198 199 USBD_PHDC_OS_WrlntrLock ue 467 USBD_PHDC_OS_WrlntrUnLock ue 468 USBD_PHDC_Rad0 192 193 456 USBD_PHDC_RdCfg ccccccesssesseeeneeees 189 190 448 USBD_PHDC_RdPreamble 192 193 196 454 USBD_PHDC_Reset ue 462 USBD_PHDC_W1r ccccsessesssseeseeeseeeseeeeneees 192 194 460 USBD_PHDC_WrCfg ccccccscesesesseesneees 189 190 450 USBD_PHDC_WrPreamble un 192 194 196 USBD_PHDC_Wrpreamble AAA USBD_RAMDISK_CFG_BASE_ADDR USBD_RAMDISK_CFG_BLK_SIZE 0 ee USBD_RAMDISK_CFG_NBR_BLKS ee USBD_RAMDISK_CFG_NBR_UNITS USBD_StorageCapacityGet 0 ee USBD_Storagelnit USBD_StorageRd USBD_StorageStatusGet USBD_StorageWr USBD Trace WEE USBD_Trace Example A USBD_Vendor_Add cceeceeseeeeees 545 Index USBD_Vendor_CfgAdd e 208 210 477 USBD_VENDOR_CFG_MA
159. _CfgAdd CPU_INTO8U dev_nbr CPU_INTO8U attrib CPU_INT16U max_pwr USBD_DEV_ SPD spd const CPU_CHAR p name USBD_ERR p err ARGUMENTS dev_nbr Device number attrib Configuration attributes USBD_DEV_ ATTRIB SELF POWERED USBD_DEV_ ATTRIB REMOTE WAKEUP max _pwr Bus power required for this device see Note 1 spd Configuration speed USBD_DEV_SPD_ FULL USBD_DEV_SPD_ HIGH p_name Pointer to string describing the configuration See Note 2 253 Appendix A p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR DEV INVALID NBR USBD_ERR_ DEV INVALID STATE USBD_ERR_ CFG ALLOC USBD_ERR CFG INVALID MAX PWR RETURNED VALUE Configuration number If no error s USBD_CFG NBR NONE otherwise CALLERS Application NOTES WARNINGS P USB spec 2 0 section 7 2 1 3 4 defines power constrains for bus powered devices A low power function is one that draws up to one unit load from the USB cable when operational A function is defined as being high power if when fully powered it draws over one but no more than five unit loads from the USB cable A unit load is defined as 100mA thus max_pwr argument should be between 0 mA and 500m lt A E String support is optional in this case p_ name can be a NULL string pointer E Configuration can only be added when the device is in either the USBD_DEV_STATE NONE or USB DEV STATE INIT states 254 A 3 I
160. _DrvEP_TxStart Figure 6 4 Device Asynchronous Transmit Diagram The upper layer APIs USBD_BulkTxAsync and USBD_IntrTxAsync call USBD_EP Tx passing a transmit complete callback function as an argument In USBD_EP_Tx the USBD_DrvEP_Tx function is invoked in the same way as for the synchronous operation On DMA based controllers this device driver API is responsible for preparing the transmit transfer descriptor and returning the amount of data to transmit In case the DMA based controller requires the buffered data to be placed in a dedicated USB memory region the contents of the application buffer area must be transferred into the dedicated memory region On FIFO based controllers this device driver API is responsible for writing the amount of data to transfer into the FIFO and returning the amount of data to transmit 95 Chapter 6 F6 4 2 F6 4 3 F6 4 4 F6 4 5 F6 4 6 F6 4 7 96 The USBD_DrvEP_TxStart API starts the transmit process On DMaA based controllers this device driver API is responsible for queuing the DMA transmit descriptor and enabling DMA transmit complete ISR s On FIFO based controllers this device driver API is responsible for enabling transmit complete ISR s The call to USBD_EP_ Tx returns immediately to the application without blocking while data is being transmitted The USB device controller triggers an interrupt request when it is finished
161. _ERR_NONE should be used 463 Appendix F F 2 2 USBD_PHDC_OS RdLock Lock the read pipe FILES usbd_phdc_os h usbd_phdc_os c PROTOTYPE void USBD_PHDC_OS RdLock CPU_INTO8U class_nbr CPU_INT16U timeout USBD_ERR p err ARGUMENTS class_nbr PHDC instance number timeout Timeout p err Pointer to variable that will receive the return error code from this function RETURNED VALUE None CALLERS USBD_PHDC_Rd USBD_PHDC_RdPreamble IMPLEMENTATION GUIDELINES Typical implementation will consist in pending on a semaphore that locks the read pipe p err argument should be assigned as described in Table F 1 464 Operation result Error code to assign No error USBD_ERR_NONE Pend timeout USBD_ERR_OS TIMEOUT Pend aborted USBD_ERR_OS ABORT Pend failed for any other reason USBD_ERR_OS FAIL Table F 1 p_err assignment in function of operation result 465 Appendix F F 2 3 USBD_PHDC_OS RdUnLock Unlock the read pipe FILES usbd_phdc_os h usbd_phdc_os c PROTOTYPE void USBD_PHDC_OS RdUnlock CPU_INTO8U class_nbr ARGUMENTS class_nbr PHDC instance number RETURNED VALUE None CALLERS USBD_PHDC_Rd USBD_PHDC RdPreamble IMPLEMENTATION GUIDELINES Typical implementation will consist in posting a semaphore that locks the read pipe 466 F 2 4 USBD_ PHDC_OS WrintrLock Lock the write interrupt pipe FILES
162. _INTO8U tx buf 2 USBD_ERR err USBD_HID_RdAsync class nbr 1 void amp rx_buf 0 2 2u App USBD_HID RxCmp1 3 void 0u 4 amp err if err USBD ERR NONE Handle the error USBD_HID_WrAsync class_nbr 1 void amp tx_buf 0 5 2u App USBD_HID TxCmp1 3 void 0u 4 amp err if err USBD_ERR_NONE Handle the error 3 static void App USBD HID RxCmpl CPU_INTO8U class_nbr void p buf CPU_INT32U buf len CPU_INT32U xfer_len void p callback_arg USBD_ERR err 152 Configuration void class_nbr void p buf void buf_len void xfer_len void p_callback_arg 4 if err USBD_ERR_NONE Do some processing else Handle the error 3 static void App USBD HID TxCmpl CPU_INTO8U class_nbr void p buf CPU_INT32U buf len CPU_INT32U xfer_len void p callback_arg USBD_ERR err void class_nbr void p buf void buf_len void xfer_len void p_callback_arg 4 if err USBD_ERR_NONE Do some processing else Handle the error Listing 9 4 Asynchronous Bulk Read and Write Example L9 4 1 The class instance number serves internally for the HID class to route the transfer to the proper interrupt OUT or IN endpoint L9 4 2 The application must ensure that the buffer provided to the function is large enough to accommodate all the data Otherwise sync
163. _SUCCESS Handle the error Listing 12 5 USBDev_API Synchronous Read and Write Example L12 5 1 The pipe handle gotten with USBDev_BulkIn_Open or USBDev_BulkOut_Open is passed to the function to schedule the transfer for the desired pipe L12 5 2 The application provides a receive buffer to store the data sent by the device L12 5 3 In order to avoid an infinite blocking situation a timeout expressed in milliseconds can be specified A value of 0 makes the application thread wait forever In the example a timeout of 5 seconds is set L12 5 4 Application provides the transmit buffer that contains the data for the device 218 USBDev_AP ASYNCHRONOUS COMMUNICATION Asynchronous communication means that the transfer is non blocking Upon function call the application passes the transfer information to the device stack and does not block Other application processing can be done while the transfer is in progress over the USB bus Once the transfer has completed a callback is called by USBDev_API to inform the application about the transfer completion Code Listing 12 6 presents a read example The asynchronous write is not offered by USBDev_API UCHAR rx _buf 2 DWORD err USBDev_PipeRdAsync bulk_in_ handle tf amp rx_buf 0 2 2u App PipeRdAsyncComplete 3 void 0u 4 amp err if err ERROR SUCCESS Handle the error 3 static void App PipeRdAsyncComplete voi
164. _Vendor_CfgAdd Adds Vendor instance to the specified device configuration Table 12 3 Vendor Class Initialization API Summary You need to call these functions in the order shown below to successfully initialize the Vendor class 208 Call USBD_Vendor_Init This is the first function you should call and you should do it only once even if you use multiple class instances This function initializes all internal structures and variables that the class needs Call USBD_Vendor_Add_ This function allocates a Vendor class instance This function allows you to include a pair of interrupt endpoints for the considered class instance If the interrupt endpoints are included the polling interval can also be indicated The polling interval will be the same for interrupt IN and OUT endpoints Moreover another parameter lets you specify a callback function used when receiving vendor requests This callback allows the decoding of vendor specific requests utilized by a proprietary protocol Call USBD_Vendor_CfgAdd Finally once the Vendor class instance has been created you must add it to a specific configuration Configuration Listing 12 1 illustrates the use of the previous functions for initializing the Vendor class 1 static CPU_BOOLEAN App USBD_Vendor_VendorReq CPU_INTO8U class_nbr const USBD_SETUP_REQ p setup req CPU_BOOLEAN App USBD Vendor Init CPU_INTO8U dev_nbr CPU_INTO8U cfg_hs CPU_INTO8U cfg fs
165. _nbr Device number cfg_nbr Configuration number if_nbr Interface number p_name Pointer to alternate setting name p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR DEV INVALID NBR USBD_ERR CFG INVALID NBR USBD_ERR_IF INVALID NBR USBD_ERR_IF ALT ALLOC 257 Appendix A RETURNED VALUE Interface alternate setting number if no errors USBD_IF ALT NBR NONE otherwise CALLERS USB class drivers NOTES WARNINGS None 258 A 3 3 USBD_IF_Grp Creates an interface group FILES usbd_core h usbd_core c PROTOTYPE CPU_INTO8U USBD_IF Grp CPU_INTO8U dev_nbr CPU_INTO8U cfg_nbr CPU_INT08U class Code CPU_LINTO8U class sub Code CPU_LINTO8U class_protocol code CPU_LINTO8U if start cPU_INTO8U if cnt const CPU CHAR p name USBD_ERR p err ARGUMENTS dev_nbr Device number cfg_nbr Configuration index to add the interface p_class drv Pointer to interface driver p_class arg Pointer to interface driver argument class_code Class code assigned by the USB IF Class sub code Subclass code assigned by the USB IF class protocol_code Protocol code assigned by the USB IF if start Interface number of the first interface that is associated with this group if cnt Number of consecutive interfaces that are associated with this group 259 Appendix A p err Pointer to variable that will receive the return error code from this function USB
166. air of bulk IN and OUT endpoints Overview Table 10 lindicates the different usages of the endpoints Endpoint Direction Usage Control IN Device to Host Enumeration and MSC class specific requests Control OUT Host to Device Bulk IN Device to Host Send CSW and data Bulk OUT Host to Device Receive CBW and data Table 10 1 MSC Endpoint Usage 10 1 3 MASS STORAGE CLASS REQUESTS There are two defined control requests for the MSC BOT protocol These requests and their descriptions are detailed in Table 10 2 Class Requests Bulk Only Mass Storage Reset Description This request is used to reset the mass storage device and its associated interface This request readies the device to receive the next command block Get Max LUN This request is used to return the highest logical unit number LUN supported by the device For example a device with LUN 0 and LUN 1 will return a value of 1 A device with a single logical unit will return O or stall the request The maximum value that can be returned is 15 Table 10 2 Mass Storage Class Requests 167 Chapter 10 10 1 4 SMALL COMPUTER SYSTEM INTERFACE SCSI SCSI is a set of standards for handling communication between computers and peripheral devices These standards include commands protocols electrical interfaces and optical interfaces Storage devices that use other hardware interfaces such as USB use SCSI commands for obtaining device host informat
167. al endpoint number FILES usbd_core h usbd_ep c PROTOTYPE CPU_INTO8U USBD_EP_GetMaxPhyNbr CPU_INTO8U dev_nbr ARGUMENTS dev_nbr Device number RETURNED VALUE Maximum physical endpoint number If no error s USBD_EP PHY NONE otherwise CALLERS USB device controllers drivers Application NOTES WARNINGS None 296 A 4 20 USBD_EP_GetMaxNbrOpen Retrieve maximum number of opened endpoints FILES usbd_core h usbd_ep c PROTOTYPE CPU_INTO8U USBD_EP GetMaxNbrOpen CPU_INTO8U dev_nbr ARGUMENTS dev_nbr Device number RETURNED VALUE Maximum number of opened endpoints If no errors 0 otherwise CALLERS USB device controllers drivers Application NOTES WARNINGS None 297 Appendix A A 5 CORE OS FUNCTIONS A 5 1 USBD_ OS Init Initialize USB RTOS layer internal objects FILES usbd_internal h usbd_os c PROTOTYPE void USBD_OS Init USBD ERR p err ARGUMENTS p err Pointer to variable that will receive the return error code from this function RETURNED VALUE None CALLERS USBD_Init IMPLEMENTATION GUIDELINES E The followings RTOS resources are required by the stack and should be allocated in when this function is called One task for core and asynchronous events One queue that can hold up to USBD_CORE_EVENT_NBR_TOTAL events USBD_CFG MAX NBR DEV x USBD_CFG MAX NBR_EP OPEN semaphores for endpoints operations 298 If tracing is enabled
168. al or less to MaxPacketSize 21 187 Chapter 11 Constant Description USBD_PHDC_OS CFG SCHED EN If using uC OS II or uC OS III RTOS port enable or disable the scheduler feature You should set it to DEF_DISABLED if device only use one QoS level to send data for instance See section 11 4 RTOS QoS based scheduler on page 196 WARNING If you set this constant to DEF_ENABLED you MUST ensure that the scheduler s task has a lower priority i e higher priority value than any task that can write PHDC data Table 11 4 Configuration Constants Summary If you set USBD_PHDC_OS CFG SCHED EN to DEF ENABLED and you use a pC OS II or pC OS IIL RTOS port PHDC will n eed an internal task for the scheduling operations There are two application specific configurations that must be set in this case They should be defined in the app_cfg h file Table 11 5 describes these configurations Constant Description USBD_PHDC_OS CFG SCHED TASK PRIO QoS based scheduler s task priority WARNING You must ensure that the scheduler s task has a lower priority i e higher priority value than any task writing PHDC data USBD_PHDC_OS CFG SCHED TASK STK SIZE 188 QoS based scheduler s task stack size Default value is 512 Table 11 5 Application Specific Configuration Constants Configuration 11 2 2 CLASS INSTANCE CONFIGURATION Before starting the communication phase your application
169. ambles are enabled by the host and if the latency of the transfer is not low Application will have to call USBD_PHDC_Wr nbr_xfers of times with the same latency reliability parameter after a call to USBD_PHDC_WrPreamble 459 Appendix F F 1 11 USBD_PHDC Wil Write PHDC data This function is blocking FILES usbd_phdc h usbd_phdc c PROTOTYPE void USBD_PHDC_Wr CPU_INTO8U class_nbr void p buf CPU_INT16U buf_len LATENCY RELY FLAGS latency rel CPU_INT16U timeout USBD_ERR p_err ARGUMENTS class obt PHDC instance number p_buf Pointer to buffer that will supply data buf_len Buffer length in octets latency rely Latency reliability of this transfer timeout Timeout in milliseconds p err Pointer to variable that will receive the return error code from this 460 function USBD_ERR_NONE USBD_ERR_ INVALID ARG USBD_ERR NULL PTR USBD_ERR_TX USBD_ ERR INVALID CLASS STATE USBD_ERR_ DEV INVALID NBR USBD_ERR DEV INVALID STATE USBD_ERR_ EP INVALID ADDR USBD_ERR_EP INVALID STATE USBD_ERR_ EP INVALID TYPE USBD_OS ERR TIMEOUT USBD_OS ERR ABORT USBD_OS ERR FAIL RETURNED VALUE None CALLERS Application NOTES WARNINGS USBD_PHDC Wr should always be called after USBD_PHDC WrPreamble if metadata message preambles are enabled by the host and if the latency of the transfer is not low Application will have to call USBD_PHDC_Wr nbr_xfers of times with the same latenc
170. amp choAsync exe for the Windows application with the asynchronous IN API of USBDev_API The Windows application interacts with WinUSB driver via USBDev_API which is a wrapper of WinUSB driver USBDev_API is provided by Micrium Refer to section 12 3 USBDev_API on page 214 for more details about USBDev_API and WinUSB driver The Echo Sync or Async demo will first determine the number of vendor devices connected to the PC For each detected device the demo will open a bulk IN and a bulk OUT pipe Then the demo is ready to send receive data to from the device You will have to enter the maximum number of transfers you want as shown by Figure 12 4 B C Micrium Software uC USB Device V4 App Host OS Windows Vendor Visual Studio 2010 exe x al xs devices attached 1 a 1 open i WinUSB internal alternate setting set 1 1 interface lt s gt default IF associated interfaces 1 attached is FULL SPEED CIF gt Bulk IN pipe open CIF gt Bulk OUT pipe open Figure 12 4 Demo Application at Startup 226 Using the Demo Application In the example of Figure 12 4 the demo will handle 10 transfers Each transfer is sent after the header following the simple protocol described in Figure 12 3 The first transfer will have a data payload of 1 byte Then subsequent transfers will have their size incremented of 1 byte until the last transfer In our example the last transfer will have 10 bytes Figure 12 5 pre
171. another for MSC A different interface for each configuration is also needed USBD_CFG MAX NBR_IF ALT 4 No alternate interface needed but this value must at least be equal to USBD_CFG MAX NBR_IF USBD_CFG MAX NBR_IF_ GRP 0 No interface association needed USBD_CFG MAX NBR_EP_DESC 4or5 Two bulk endpoints for MSC Two bulk plus one optional interrupt endpoint for PHDC USBD_CFG MAX NBR EP OPEN 6or7 Two control endpoints for device s standard requests Two bulk endpoints for MSC Two bulk plus 1 optional interrupt endpoint for PHDC USBD_PHDC_CFG MAX NBR_DEV 1 Only one instance of PHDC is needed It will be shared between all the configurations USBD_PHDC_ CFG MAX NBR CFG 2 PHDC instance can be used in both of device s configurations USBD_MSC_CFG MAX NBR_DEV 1 Only one instance of MSC is needed It will be shared between all the configurations USBD_MSC_CFG MAX NBR_CFG 2 MSC instance can be used in both of device s configurations Table 5 2 Configuration Example of a Composite High Speed USB Device 5 4 3 COMPLEX COMPOSITE HIGH SPEED USB DEVICE Table 5 3 shows the values that should be set for the different configuration constants described earlier if you build a composite high speed USB device using a single instance of Micripm s HID class in two different configurations plus a different instance of Micrium s CDC ACM class in each configuration The device also uses an instance of Mic
172. ap size E Configuration data in usbd_cfg h consists of specifying the number of devices supported in the stack the maximum number of configurations the maximum number of interfaces and alternate interfaces maximum number of opened endpoints per device class specific configuration parameters and more In all there are approximately 20 defines to set E Finally usbd_dev_cfg c h consists of device specific configuration requirements such as vendor ID product ID device release number and its respective strings It also contains device controller specific configurations such as base address dedicated memory base address and size and endpoint management table Refer to Chapter 5 Configuration on page 65 for more information on how to configure C USB Device 4 1 2 LIBRARIES Given that uC USB Device is designed to be used in safety critical applications some of the standard library functions such as strepy memset etc have been rewritten to conform to the same quality standards as the rest of the USB device stack All these standard functions are part of a separate Micrium s product uC LIB uC USB Device depends on this product In addition some data objects in USB controller drivers are created at run time which implies the use of memory allocation from the heap function Mem_HeapAlloc 55 Chapter 4 4 1 3 USB CLASS LAYER Your application will interface with pC USB Device using the class layer API In
173. ass MSC configuration memory footprint table is shown in Table I 8 Table l 6 HID Memory Footprint is presented in Table I 7 and its associated Configuration Value USBD_CFG MAX NBR_IF 1 USBD_CFG MAX NBR_IF ALT 1 USBD_CFG MAX NBR_IF GRP 0 USBD_CFG MAX NBR_EP DESC 2 USBD_CFG MAX NBR_EP OPEN 4 USBD_MSC_CFG MAX NBR_DEV 1 USBD_MSC_CFG MAX NBR CFG 2 USBD_MSC_CFG MAX LUN 1 USBD_MSC_ CFG DATA LEN 2048 534 Table l 7 MSC Configuration for Memory Footprint Module Code kB Constant kB Data kB Device Core 19 13 0 85 Device RTOS Port 0 76 1 35 Device Controller 6 74 0 21 Data allocated from heap Driver MSC 7 57 0 03 2 55 MSC RTOS Port 0 68 1 27 RAMDisk Storage 0 36 RAMDisk Storage layer allocates data sections to simulate a memory area from a media storage This memory area size is configured in app_cfg h Total 35 24 0 24 6 02 Table l 8 MSC Memory Footprint 1 0 4 PERSONAL HEALTHCARE DEVICE CLASS The Personal Healthcare Device Class PHDC configuration is presented in Table I 9 and its associated memory footprint table is shown in Table I 10 Note that there is an optional Interrupt IN endpoint that you may add during PHDC initialization that has been omitted in the configuration below Also note that the memory footprint is taken for both QOS Based Scheduler enabled and disabled configurations The memory footprint for the PHDC RTOS lay
174. at least one of the Micrium USB classes m USB device controller driver compatible with your hardware for the pC USB Device stack P Board support package BSP for your development board E Example project for your selected RTOS that is pC OS II or wC OS IID If Micrium does not support your USB device controller or BSP you will have to write your own device driver Refer to Chapter 6 Device Driver Guide on page 77 for more information on writing your own USB device driver 2 2 DOWNLOADING THE SOURCE CODE FILES pC USB Device can be downloaded from the Micrium customer portal The distribution package includes the full source code and documentation You can log into the Micrium customer portal at the address below to begin your download you must have a valid license to gain access to the file http micrium com login pC USB Device depends on other modules and you need to install all the required modules before building your application Depending on the availability of support for your hardware platform ports and drivers may or may not be available for download from the customer portal Table 2 1 shows the module dependency for pC USB Device 28 Downloading the Source Code Files Module Name Required Note s yC USB Device Core YES Hardware independent USB stack yC USB Device Driver YES USB device controller driver Available only if Micrium supports your controller otherwi
175. at you receive a Micrium example the directory structure shown above is generally used by Micrium You may use a different directory structure to store the application and toolchain projects files 31 Chapter 2 Micrium This is where Micrium places all software components and projects This directory is generally located at the root directory Software This sub directory contains all software components and projects EvalBoards This sub directory contains all projects related to evaluation boards supported by Micripm lt manufacturer gt This is the name of the manufacturer of the evaluation board In some cases this can be also the name of the microcontroller manufacturer lt board name gt This is the name of the evaluation board lt compiler gt This is the name of the compiler or compiler manufacturer used to build the code for the evaluation board lt project name gt The name of the project that will be demonstrated For example a simple pC USB Device with pC OS III project might have the project name uCOS II USBD Vir k These are the source files for the project This directory contains configuration files app _cfg h os cfg h os cfg _app h cpu_cfg h and other project required sources files os_cfg h is a configuration file used to configure pC OS II or pC OS ID parameters such as the maximum number of tasks events objects which pC OS III services are enabled semaphores mailboxes queues
176. ated in the USB device configuration file usbd_cfg h Table 9 4 shows their description Constant Description USBD_HID CFG MAX NBR_DEV Configures the maximum number of class instances Unless you plan on having multiple configurations or interfaces using different class instances this can be set to 1 USBD_HID CFG MAX NBR_CFG USBD_HID CFG MAX NBR REPORT ID Configures the maximum number of configurations in which HID class is used Keep in mind that if you use a high speed device two configurations will be built one for full speed and another for high speed Configures the maximum number of report IDs allowed in a report The value should be set properly to accommodate the number of report ID to be used in the report The minimum value is 1 USBD_HID CFG MAX NBR _REPORT_PUSHPOP Configures the maximum number of Push and Pop items used in a report If the constant is set to 0 no Push and Pop items are present in the report Table 9 4 HID Class Configuration Constants The HID class uses an internal class to manage periodic input reports The task priority and stack size shown in Table 9 5 are defined in the application configuration file app_cfg h Refer to section 9 6 Periodic Input Reports Task on page 161 for more details about the HID internal task Constant Description USBD_HID OS CFG TMR TASK PRIO Configures the priority of the HID periodic input reports task US
177. atiodueiesatadentuers 246 ER We NEE 247 WSBD Devise et eeegeegdeeggeerd Ree ee EEN 248 USBD DevGetState ruriri rennen Sage eieviacti detec cv OARE ARANEAE EREA ae 249 USB Dev cdeit euer geed 251 Configuration FUNCTIONS ee 253 USBD te LTE 253 Interface FUNCTIONS een 255 WSBD IF Add EE 255 VSB DA AMA dd f arr re ree ee 257 UR ET ET E 259 Endpoints FUNCtIONS ccs ctesccccececececeeceveesd EES ce ceeveereasenneccestersunaress 261 USBD E EE 261 VSBD el EE 263 USBD BulkAGd rr e aa ara aare aea a Aen aa e a aa ranae a anaa iea aeae 265 UR BUKRX E 267 A 4 5 A 4 6 A 4 7 A 4 8 A 4 9 A 4 10 A 4 11 A 4 12 A 4 13 A 4 14 A 4 15 A 4 16 A 4 17 A 4 18 A 4 19 A 4 20 A 5 A 5 1 A 5 2 A 5 3 A 5 4 A 5 5 A 5 6 A 5 7 A 5 8 A 5 9 A 5 10 A 5 11 A 5 12 A 6 A 6 1 A 6 2 A 6 3 A 6 4 A 6 5 A 6 6 A 6 7 USBD_BUuIkKRXASYIC 2 ecececeeeeeeeeeeeeeeneeeeeeeeeeeeeeesaeeeeeeeeeeseaeeeeseeeeesenes 269 ET RT a KEE 271 USB BulkTXASYINC sess ccicvcveccctvecssccctveecveccentdevencceereeesnictveveveccenveeeveces 273 USBD INA EE 276 USBD IURI ET 278 USBD INthRXASYNG rra Ear ae Seed ENEE aaa iaaa 280 USBD BT E RE 282 WSBD2 INTE XAS YING sce ccecesacc corerdctecerevestereevesstcthcercvsceeteverssnersereestuny 284 USBD ER2RXZLP iiaeiai e Eh eines 287 USBD EP TXZLP engt ege ege Cd EEN ege events eer d 289 USPE EP Abort eroian atA tv cine cians AEN 291 USBD EP Stall re a arar a aar naaa a a a aaa ra aa aeaa 292 US
178. ation Descriptor Interface Descriptor Vendor class Endpoint Descriptor Bulk OUT Endpoint Descriptor Bulk IN Endpoint Descriptor Interrupt OUT optional Endpoint Descriptor Interrupt IN optional The pair of Interrupt endpoints are optional They can be added to the Interface descriptor by setting the parameter intr_en to DEF_TRUE If USBD_Vendor_CfgAdd is called several times from the application it allows to create multiple instances and multiple configurations For instance the following architecture could be created for an high speed device High speed Configuration 0 Interface 0 Vendor 0 Configuration 1 Interface 0 Vendor 0 Interface 1 Vendor 1 In that example there are two instances of Vendor class Vendor 0 and Vendor 1 and two possible configurations for the device Configuration 0 and Configuration 1 Configuration 1 is composed of two interfaces Each class instance has an association with one of the interfaces If Configuration 1 is activated by the host it allows the host to access two different functionalities offered by the device 478 G 1 4 USBD_Vendor_IsConn Get the vendor class connection state FILES usbd_vendor c PROTOTYPE CPU_BOOLEAN USBD Vendor _IsConn CPU_INTO8U class_nbr ARGUMENTS class nr Class instance number RETURNED VALUE DEF_YES if Vendor class is connected DEF_NO otherwise CALLERS Application
179. ation to the USB device stack At a minimum your USB device application only needs one full speed and one high speed configuration if your device is a high speed capable device For a full speed device only a full speed configuration will be required You can create as many configurations as needed by your application and you can associate multiple instances of USB classes to these configurations For example you can create a configuration to contain a mass storage device and another configuration for a human interface device such as a keyboard and a vendor specific device Create and add a full speed configuration to your device Initialize the class specific application demos by calling the function App USBD XXXX Init where XXXX can be CDC HID MSC PHDC or VENDOR Class specific demos are enabled and disabled using the APP CFG USB_XXXX EN define After all the class instances are created and added to the device configurations the application should call USBD_DevStart This function connects the device with the host by enabling the pull up resistor on the D line Table 2 2 lists the sections Running the Sample Application you should refer to for more details about each App USBD_XXXX_ Init function Class Function Refer to CDC ACM App USBD CDC _Init section 8 3 1 General Configuration on page 120 HID App USBD HID Init section 9 3 2 Class Instance Configuration on page 144 MSC
180. bd c and it is up to you to define how messages are outputted whether through console terminal printf statements or serial print statements for example Listing 13 1 shows an example of an implementation for USBD_Trace with a serial print function void USBD Trace const CPU_CHAR p str App SerPrintf s CPU CHAR p str Listing 13 1 USBD_Trace Example 232 13 1 3 DEBUG FORMAT Using Debug Traces The debug task handler follows a simple format when outputting debug events The format is as follows USB lt timestamp gt lt endpoint address gt lt interface number gt lt error info message gt In the event that timestamp endpoint address interface number or error messages are not provided they are left void in the output An example output is shown in Listing 13 2 This example corresponds to traces placed in the USB device core and device driver functions This trace shows the enumeration process where bus events are received and related endpoints are opened in the device driver Next a setup event is sent to the core task followed by receiving the first Get Device Descriptor standard request USB USB USB USB USB USB USB USB USB USB USB USB USB USB USB USB USB USB USB USB USB USB SOR OROs O5ONO COOOL OMOMO COMO On Omni OmOme 80 80 80 80 80 80 Bus Reset Drv Drv EP DMA EP DMA Bus Suspend Bus Reset Drv Drv Drv Drv Drv Setup Drv Drv Get
181. ber p buf Pointer to transmit buffer buf len Transmit buffer length in octets timeout Timeout in milliseconds p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_NULL PTR USBD_ERR_INVALID ARG USBD_ERR_ INVALID CLASS STATE USBD_ERR_ DEV INVALID NBR USBD_ERR_ EP INVALID NBR USBD_ERR DEV INVALID STATE USBD_ERR_EP INVALID TYPE 398 RETURNED VALUE Number of octets transmitted if NO error s 0 otherwise CALLERS Application NOTES WARNINGS None 399 Appendix D D 1 8 USBD_HID_WrAsync This function transmits data to the host asynchronously through an interrupt IN endpoint FILES usbd_hid c PROTOTYPE void USBD_HID WrAsync CPU_INTO8U class_nbr void p buf CPU_INT32U buf_len USBD_HID ASYNC_FNCT async_fnct void p async arg USBD_ERR p err ARGUMENTS class nr Class instance number p_buf Pointer to transmit buffer buf_len Transmit buffer length in octets async _fnct Transmit callback p async org Additional argument provided by application for transmit callback p err 400 Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR NULL PTR USBD_ERR_INVALID ARG USBD_ERR_ INVALID CLASS STATE USBD_ERR_ FAIL USBD_ERR_ DEV INVALID NBR USBD_ERR_EP INVALID NBR USBD_ERR DEV INVALID STATE USBD_ERR_EP INVALID TYPE USBD_ERR_ EP INVALID STATE RETURNED VALUE None
182. between the host and the device using the HID class offered by Micrium Host operating system Application USB Host stack Control 0 3 IN amp OUT 3k NIK Interrupt Interrupt N HUT HID Report HID class i parser Application USB Device Figure 9 2 General Architecture Between a Host and HID Class The host operating system OS enumerates the device using the control endpoints Once the enumeration phase is done the host starts the transmission reception of reports to from the device using the interrupt endpoints On the device side the HID class interacts with an OS layer specific to this class The HID OS layer provides specific OS services needed for the internal functioning of the HID class This layer does not assume a particular OS By default Micrium provides the HID OS layer for pC OS II and pC OS IIIL If you need to port the HID class to your own OS refer to section 9 5 Porting the HID Class to a RTOS on page 160 for more details about the HID OS layer During the HID class initialization phase a report parser module is used to validate the report provided by the application If any error is detected during the report validation the initialization will fail 142 9 3 CONFIGURATION Configuration 9 3 1 GENERAL CONFIGURATION Some constants are available to customize the class These constants are loc
183. ble that will receive the return error code from this function ERROR_SUCCESS ERROR INVALID HANDLE ERROR INVALID USER BUFFER ERROR BAD PIPE ERROR INVALID PARAMETER ERROR HOT ENOUGH MEMORY ERROR _SEM TIMEOUT7 522 RETURNED VALUE Number of bytes received if NO error s 0 otherwise CALLERS Application NOTES WARNINGS None 523 Appendix G G 2 20 USBDev_PipeRdAsync Read data from device over the specified pipe This function returns immediately if data is not present The data will be retrieved later FILES usbdev_api c PROTOTYPE void USBDev_PipeRdAsync HANDLE pipe UCHAR p buf DWORD buf_len USBDEV_PIPE RD CALLBACK callback void p_callback_arg DWORD p err ARGUMENTS pipe Pipe handle p buf Pointer to receive buffer buf len Receive buffer length callback Pointer to application callback called by Asynchronous thread upon completion p callback arg Pointer to argument which can carry private information passed by application This argument is used when the callback is called p err Pointer to variable that will receive the return error code from this function ERROR_SUCCESS ERROR INVALID HANDLE ERROR INVALID USER BUFFER ERROR BAD PIPE ERROR HOT ENOUGH MEMORY ERROR _SEM TIMEOUT 524 RETURNED VALUE None CALLERS Application NOTES WARNINGS When a IN pipe is open with one of the open functions USBDev_xxxxIn_Open a thread is automatically created This th
184. buffered data to be placed in a dedicated USB memory region the buffered data must be transferred into the application buffer area On FIFO based controllers this device driver API is responsible for reading the amount of data received by copying it into the application buffer area and returning the data back to its caller If the overall amount of data received is less than the amount requested and the current transfer is not a short packet USBD_DrvEP_RxStart is called to request the remaining data On DMA based controllers this device driver API is responsible for queuing a receive transfer The queued receive transfer does not need to satisfy the whole requested transfer length at once If multiple transfers are queued only the last queued transfer must be signaled to the USB device stack This is required since the USB device stack iterates through the receive process until all requested data or a short packet has been received On FIFO based controllers this device driver API is responsible for enabling data to be received into the endpoint FIFO including any related ISRs The receive operation finishes when the amount of data received matches the amount requested or a short packet is received The receive complete callback is invoked to notify the application about the completion of the process USB Device Driver Functional Model 6 8 3 DEVICE SYNCHRONOUS TRANSMIT The device synchronous transmit operation is initiated by
185. by the host the input reports ID list is empty and the task has nothing to process The task processes only report IDs different from 0 and with an idle duration greater than 0 For a given input report ID the task verifies if the idle duration has elapsed If the idle duration has not elapsed the counter is decremented and no input report is sent to the host If the idle duration has elapsed that is the idle duration counter has reached zero an input report is sent to the host by calling the USBD_HID Wr function via the interrupt IN endpoint The input report data sent by the task comes from an internal data buffer allocated for each input report described in the Report descriptor An application task can call the USBD_HID Wr function to send an input report After sending the input report data USBD_HID Wr updates the internal buffer associated to an input report ID with the data just sent Then the periodic input reports task always sends the same input report data after each idle duration elapsed and until the application task updates the data in the internal buffer There is some locking mechanism to avoid corruption of the input report ID data in the event of a modification happening at the exact time of transmission done by the periodic input report task The periodic input reports task is implemented in the HID OS layer in the function USBD_HID OS TmrTask Refer to section D 2 HID OS Functions on page 402 for more detai
186. called to inform the device driver layer of the new address For controllers that have hardware assistance in setting the device address after the status stage this device driver API is used to configure the device address and enable the transition after the status stage For controllers that activate the device address as soon as configured this device driver API should not perform any action The setup request status stage is transmitted to acknowledge the address change After the status stage the USBD_DrvAddrEn is called to inform the device driver layer to enable the new device address For controllers that activate the device address as soon as configured this device driver API is responsible for setting and enabling the new device address For controllers that have hardware assistance in setting the device address after the status stage this device driver API should not perform any action since USBD_DrvAddrSet has already taken care of setting the new device 97 Chapter 6 98 Chapter USB Classes The USB classes available for the pC USB Device stack have some common characteristics This chapter explains these characteristics and the interactions with the core layer allowing you to better understand the operation of classes 7 1 CLASS INSTANCE CONCEPT The USB classes available with the pC USB Device stack implement the concept of class instances A class instance represents one function within a device The fu
187. ce On the device side the demo application file app usbd_hid c offering the two HID demos is provided for pC OS II and pC OS III It is located in these two folders E Micrium Software uC USB Device V4 App Device 0S uCcOS II E Micrium Software uC USB Device V4 App Device 0S uCOS III The use of these constants usually defined in app _cfg h allows you to use one of the HID demos 154 Using the Demo Application Constant Description APP CFG USBD_HID EN General constant to enable the Vendor class demo application Must be set to DEF_ENABLED APP_CFG USBD_ HID TEST MOUSE_EN Enables or disables the mouse demo The possible values are DEF_ENABLED or DEF_DISABLED If the constant is set to DEF DISABLED the vendor specific demo is enabled APP_CFG USBD HID MOUSE TASK PRIO Priority of the task used by the mouse demo APP_CFG USBD HID READ TASK PRIO Priority of the read task used by the vendor specific demo APP_CFG USBD HID WRITE TASK PRIO Priority of the write task used by the vendor specific demo APP_CFG USBD HID TASK STK SIZE Stack size of the tasks used by mouse or vendor specific demo A default value can be 256 Table 9 8 Device Application Constants Configuration On the Windows side the mouse demo influences directly the cursor on your monitor while the vendor specific demo requires a custom application The latter is provided by a Visual Studio solution located in this folder
188. ceive the return error code from this function ERROR_SUCCESS ERROR INVALID HANDLE RETURNED VALUE None CALLERS Application NOTES WARNINGS None 516 G 2 17 USBDev_CitrlReq Send control data over the default control endpoint FILES usbdev_api c PROTOTYPE ULONG USBDev_CtrlReq HANDLE dev UCHAR bm_req type UCHAR b_request USHORT w_value USHORT w_index UCHAR p buf USHORT buf len DWORD p err ARGUMENTS dev General handle to device bm reg type Variable representing bmRequestType of setup packet bmRequestType is a bitmap with the following characteristics D7 Data transfer direction 0 USB DIR HOST TO DEVICE 1 USB DIR DEVICE TO HOST D6 5 Request type 00 USB_REQUEST TYPE STD standard 01 USB_REQUEST TYPE CLASS 10 USB_REQUEST TYPE VENDOR 517 Appendix G b request w_value w_index p_buf buf_len 518 D4 0 Recipient 0000 USB RECIPIENT DEV device 0001 USB RECIPIENT IF interface 0010 USB RECIPIENT ENDPOINT bm_req type Argument is a OR ed of D7 D6 5 and D4 0 values Variable representing bRequest of setup packet Possible values are GET_STATUS CLEAR_FEATURE SET_FEATURE SET_ADDRESS GET_DESCRIPTOR SET_DESCRIPTOR GET_CONFIGURATION SET_CONFIGURATION GET_INTERFACE SET_INTERFACE SYNCH_FRAME Returns status for the specified recipient Clear or disable a specific feature
189. controller gt DMAIntHandler void ARGUMENTS None NOTES WARNINGS In this configuration the pointer to the USB device driver structure must be stored globally in the driver Since the pointer to the USB device structure is never modified the BSP initialization function USBD_BSP_Init can save its address for later use 6 4 5 USBD_DrviSR_HANDLER The device driver interrupt handler must notify the USB device stack of various status changes Table 6 1 shows each type of status change and the corresponding notification function Connect Event USBD_EventConn Disconnect Event USBD_EventDisconn Reset Event USBD_EventReset Suspend Event USBD_EventSuspend Resume Event USBD_EventResume High Speed Handshake Event USBD_EventHS 83 Chapter 6 Setup Packet USBD_EventSetup Receive Packet Completed USBD_EP_RxCmp1 Transmit Packet Completed USBD_EP_TxCmp1 Table 6 1 Status Notification API Each status notification API queues the event type to be processed by the USB stack s event processing task Upon reception of an USB event the interrupt service routine may perform some operations associated to the event before notifying the stack For example the USB device controller driver must perform the proper actions for the bus reset when an interrupt request for that event is triggered Additionally it must also notify the USB device stack about the bus reset event by
190. ction 4 2 3 Processing Debug Events on page 63 for details on processing debug events 13 2 3 DEBUG MACROS Within the core several macros are created to set debug messages These macros are defined in usbd_core h and make use of the core functions USBD_Dbg and USBD_DbgArg that will set up a debug event structure and put the event into the debug event pool These macros are defined in Listing 13 3 234 Handling Debug Events define USBD_DBG_GENERIC msg ep_addr if _nbr USBD_Dbg msg N ep_addr if_nbr USBD_ERR_NONE define USBD_DBG GENERIC_ERR msg ep addr if_nbr err USBD_Dbg msg ep_addr if_nbr err define USBD_DBG_GENERIC_ARG msg ep_addr if_nbr arg USBD_DbgArg msg ep_addr if_nbr CPU_INT32U arg USBD_ERR_ NONE define USBD_DBG GENERIC_ARG ERR msg ep addr if_nbr arg err USBD_DbgArg msg ep_addr if_nbr CPU_INT32U arg err eee EE Listing 13 3 Core Level Debug Macros There are subtle yet important differences between each debug macro The first debug macro is the most simple specifying just the debug message endpoint address and interface number as parameters The second and third macros differ in the last parameter where one specifies the error and the other specifies an argument of choice The last macro lets the caller specify all details including both error and argument Furthermore core level debug macros can b
191. ction pointer The details of each device BSP API function are described in section B 2 Device Driver BSP Functions on page 350 6 8 USB DEVICE DRIVER FUNCTIONAL MODEL The USB device controller can operate in distinct modes while transferring data This section describes the common sequence of operations for the receive and transmit API functions in the device driver highlighting potential differences when the controller is operating on FIFO or DMA mode While there are some controllers that are strictly FIFO based or DMA based there are controllers that can operate in both modes depending on hardware characteristics For this type of controller the device driver will employ the appropriate sequence of operations depending for example on the endpoint type 6 8 1 DEVICE SYNCHRONOUS RECEIVE The device synchronous receive operation is initiated by the calls USBD_BulkRx USBD_Ctr1Rx and USBD_IntrRx Figure 6 1 shows an overview of the device synchronous receive operation USBD_EP_Rx pa USBD_DrvEP_RxStart S Le Device Rx 4 4 Tee EE D 6 cat an we 5 P SN Device ISR Handler A wi N Sf 2 USB Device USBD_DrvEP_Rx Ee SS SS eA 3 Figure 6 1 Device Synchronous Receive Diagram 89 Chapter 6 F6 1 1 F6 1 2 F6 1 3 F6 1 4 F6 1 5 F6 1 6 90 The upper layer API s USBD_BulkRx USBD_Ctr1Rx and USBD_IntrRx call USBD_EP_Rx where
192. d p buf DWORD buf len DWORD xfer_len void p_callback_arg DWORD err void p buf void buf_len void xfer_len void p callback_arg if err ERROR_SUCCESS Process the received data else Handle the error Listing 12 6 USBDev_API Asynchronous Read Example 219 Chapter 12 112 6 1 The pipe handle gotten with USBDev_BulkIn_Open is passed to the function to schedule the transfer for the desired pipe L12 6 2 The application provides a receive buffer to store the data sent by the device 112 63 The application provides a callback passed as a parameter Upon completion of the transfer USBDev_API calls this callback so that the application can finalize the transfer by analyzing the transfer result For instance upon read operation completion the application may do a certain processing with the received data L12 6 4 An argument associated to the callback can be also passed Then in the callback context some private information can be retrieved 12 4 USING THE DEMO APPLICATION Micrium provides a demo application that lets you test and evaluate the class implementation Source template files are provided for the device Executable and source files are provided for Windows host PC 12 4 1 CONFIGURING PC AND DEVICE APPLICATIONS The demo used between the host and the device is the Echo demo This demo implements a simple protocol allowing the device to echo the data sent by t
193. d and write synchronous communication synchronous transfer completion 37 28 37 T task execution order model priorities task stack sizes TaskCreate template files trace functions transfer types transmit asynchronous synchronous U uC FS preprocessor constants 178 UpdateAltSetting UpdateRPStatel RE USB class layer core layer data flow device device application device configuration device configuration structure device controller driver configuration a device driver data type eecceeeceeeeeseeeeeeeeeeeeeeneeeeeees device driver functional Model cccceeeeeeeeeeeees 89 device states 0 e ee 25 device structure 22 24 hostoan 2 16 bostapplteetiogg seg 179 USBD_ACM_SerialAdd 123 124 126 129 370 USBD_ACM_SerialCfgAdd 123 124 126 371 USBD_ACM_SERIAL_CFG_MAX_NBR_DEV 76 123 USBD_ACM_Seriallnit A 123 124 369 USBD_ACM_SeriallSConn eeens 373 USPBD ACH Gertal IneCodingtGett 00100100100 127 381 USBD_ACM_SerialLineCodingReg 123 124 127 383 USBD_ACM_SerialLineCodingSet 0 127 382 USBD_ACM_SerialLineCtrlGet eeeee 127 378 USBD_ACM_SerialLineCtrlReg 123 124 127 379 USBD_ACM_SerialLineStateCir w 127 386 USBD_ACM_SerialLineStateSet
194. d complete when E The endpoint transfers exactly the amount of data expected E The endpoint transfers a short packet that is a packet with a payload size less than the maximum E The endpoint transfers a zero length packet 1 3 PHYSICAL INTERFACE AND POWER MANAGEMENT USB transfers data and provides power using four wire cables The four wires are Vpus D D and Ground Signaling occurs on the D and D wires 1 3 1 SPEED The USB 2 0 specification defines three different speeds E Low Speed 1 5 Mb s E Full Speed 12 Mb s E High Speed 480 Mb s 21 Chapter 7 1 3 2 POWER DISTRIBUTION The host can supply power to USB devices that are directly connected to the host USB devices may also have their own power supplies USB devices that use power from the cable are called bus powered devices Bus powered device can draw a maximum of 500 mA from the host USB devices that have alternative source of power are called self powered devices 1 4 DEVICE STRUCTURE AND ENUMERATION Before the host application can communicate with a device the host needs to understand the capabilities of the device This process takes place during device enumeration After enumeration the host can assign and load a specific driver to allow communication between the application and the device During enumeration the host assigns an address to the device reads descriptors from the device and selects a configuration that specifies power an
195. d control requests on time On the other hand for some applications you might want to give the core task a low priority especially if you plan using asynchronous communication and if you know you will have quite a lot of code in your callback functions For more information on the core task see section 4 2 Task Model on page 58 69 Chapter 5 The priority of the debug task should generally be low since it is not critical and the task performed can be executed in the background For the pC OS II and pC OS II RTOS ports the following macros must be configured within app _cfg h E USBD_OS CFG CORE TASK PRIO E USBD_OS CFG TRACE TASK PRIO Note if USBD_CFG DG TRACE EN is set to DEE DISABLED USBD OS CFG TRACE TASK PRIO should not be defined 5 2 2 TASK STACK SIZES For the pC OS II and pC OS III RTOS ports the following macros must be configured within app _cfg h to set the internal task stack sizes E USBD_OS CFG CORE TASK STK SIZE 1000 E USBD_OS CFG TRACE TASK STK SIZE 1000 Note if USBD CFG DBG TRACE EN is set to DEF DISABLED USBD OS CFG TRACE TASK STK SIZE should not be defined The arbitrary stack size of 1000 is a good starting point for most applications The only guaranteed method of determining the required task stack sizes is to calculate the maximum stack usage for each task Obviously the maximum stack usage for a task is the total stack usage along the task s most stack greedy function path plus the
196. d in a generic way that can be adapted to any toolchain The best way to start building a USB based project is to start from an existing project If you are using pC OS I or wC OS IH Micrium provides example projects for multiple development boards and compilers If your target board is not listed on Micrium s web site you can download an example project for a similar board or microcontroller The purpose of the sample project is to allow a host to enumerate your device You will add a USB class instance to both full speed and high speed configurations Gf both are supported by your controller Refer to section 7 1 Class Instance Concept on page 99 for more details about the class instance concept After you have successfully completed and run the sample project you can use it as a starting point to run other USB class demos you may have purchased pC USB Device requires a Real Time Operating System RTOS The following assumes that you have a working example project running on pC OS II or pC OS IIL 2 4 1 UNDERSTANDING MICRIUM EXAMPLES A Micrium example project is usually placed in the following directory structure Micrium Software EvalBoards lt manufacturer gt lt board_name gt lt compiler gt lt project name gt Vi Note that Micrium does not provide by default an example project with the uC USB Device distribution package Micrium examples are provided to customers in specific situations If it happens th
197. d interface requirements In order for the host learns about the device s capabilities the device must provide information about itself in the form of descriptors This section describes the device logical organization from the USB host s point of view 1 4 1 USB DEVICE STRUCTURE From the host point of view USB devices are internally organized as a collection of configurations interfaces and endpoints CONFIGURATION A USB configuration specifies the capabilities of a device A configuration consists of a collection of USB interfaces that implement one or more USB functions Typically only one configuration is required for a given device However the USB specification allows up to 255 different configurations During enumeration the host selects a configuration Only one configuration can be active at a time The device uses a configuration descriptor to inform the host about a specific configuration s capabilities 22 Device Structure and Enumeration INTERFACE A USB interface or a group of interfaces provides information about a function or class implemented by the device An interface can contain multiple mutually exclusive settings called alternate settings The device uses an interface descriptor to inform the host about a specific interface s capabilities Each interface descriptor contains a class subclass and protocol codes defined by the USB IF and the number of endpoints required for a particular class implementa
198. d requests to query and configure the device using the default pipe The default pipe uses endpoint zero EPO F1 2 2 USB pipes allow associations between the host application and the device s endpoints Host applications send and receive data through USB pipes F1 2 3 The host controller is responsible for the transmission reception packing and unpacking of data over the bus F1 2 4 Data is transmitted via the physical media F1 2 65 The device controller is responsible for the transmission reception packing and unpacking of data over the bus The USB controller informs the USB device software layer about several events such as bus events and transfer events F1 2 6 The device software layer responds to the standard request and implements one or more USB functions as specified in the USB class document 20 Physical Interface and Power Management TRANSFER COMPLETION The notion of transfer completion is only relevant for control bulk and interrupt transfers as isochronous transfers occur continuously and periodically by nature In general control bulk and interrupt endpoints must transmit data payload sizes that are less than or equal to the endpoint s maximum data payload size When a transfer s data payload is greater than the maximum data payload size the transfer is split into several transactions whose payload is maximum sized except the last transaction which contains the remaining data A transfer is deeme
199. d star topology The key elements in USB topology are the host hubs and devices as illustrated in Figure 1 1 Each node in the illustration represents a USB hub or a USB device At the top level of the graph is the root hub which is part of the host There is only one host in the system The specification allows up to seven tiers and a maximum of five non root hubs in any path between the host and a device Each tier must contain at least one hub except for the last tier where only devices are present Each USB device in the system has a unique address assigned by the host through a process called enumeration see section 1 4 3 on page 25 for more details on enumeration 15 Chapter 7 The host learns about the device capabilities during enumeration which allows the host operating system to load a specific driver for a particular USB device The maximum number of peripherals that can be attached to a host is 127 including the root hub Host Root Hub Figure 1 1 Bus topology 1 1 2 USB HOST The USB host communicates with the devices using a USB host controller The host is responsible for detecting and enumerating devices managing bus access performing error checking providing and managing power and exchanging data with the devices 1 1 3 USB DEVICE A USB device implements one or more USB functions where a function provides one specific capability to the system Examples of USB functions are keyboards webcam speakers
200. d when the device is properly enumerated before communication begins Once communication begins the task must also keep track of endpoint update statuses to correctly implement the MSC protocol These types of notification are handled by RTOS signals For the MSC RTOS layer there are two semaphores created One for enumeration process and one for communication process By default Micrium will provide RTOS layers for both pC OS II and pC OS III However it is also possible to create your own RTOS layer Please refer to section 10 7 Porting MSC to a RTOS on page 181 to learn how to port to a different RTOS 10 3 1 MASS STORAGE TASK HANDLER The MSC task handler implements the MSC protocol responsible for the communication between the device and the host The task handler is initialized when USBD_MSC_Init is called The MSC protocol is handled by a state machine comprised of 9 states The transition between these states are detailed in Figure 10 3 171 Chapter 10 NONE Device a d Disconnected Sg Device N neea Error Connected Invalid _ Restall Bulk _ Restall Bulk _ BulkINand EP Error cew a N a OUT g OUT Stalls Cleared RESET RECOVERY RESET RECOVERY CEW BULK IN STALL BULK OUT STALL RESETRECOXER E S SCH a A y Valid CBW m with No Data Phase Transfer Error N Bulk OUT Stall Cleared Valid BULK OUT STALL CBW J c Y d P Data Stall DATA _
201. dard vendor or class specific request Standard requests are processed by the core layer Vendor and class specific requests are processed by the class driver in the class layer Task Model 4 2 3 PROCESSING DEBUG EVENTS pC USB Device contains an optional debug and trace feature Debug events are managed in the core layer using a dedicated task Figure 4 5 describes how the core manage the debug events Free Debug Events List F4 5 1 F4 5 2 F4 5 3 F4 5 4 F4 5 5 USB Class Layer 4 1 Core Layer Task Debug Event USB List Driver Layer Application Specific Output 5 Figure 4 5 Processing USB Debug Events The debug and trace module in the core contains a free list of USB debug events The debug events objects contain useful information such as the endpoint number interface number or the layer that generates the events Multiple uC USB Device layers take available debug event objects to trace useful information about different USB related events Trace and debug information events are pushed in the debug event list ggg The debug task is dormant until a new debug event is available in the debug event list The debug task will parse the information contained in the debug event object and it will output it in a human readable format using the application specific output trace function USBD_Trace The application specific output function outputs the debug trace information For more info
202. data and messaging protocol a call to this function will let you configure the device specialization code s Call USBD_PHDC_CfgAdd Finally once the class instance is correctly configured and initialized you will need to add it to a USB configuration This is done by calling USBD_PHDC_CfgAdd_ Configuration Listing 11 1 shows an example of initialization and configuration of a PHDC instance If you need more than one class instance of PHDC for your application refer to section 7 1 Class Instance Concept on page 99 for generic examples of how to build your device CPU BOOLEAN App USBD PHDC Init CPU_INTO8U dev_nbr CPU_INTO8U cfg_hs CPU_INTO8U cfg fs USBD_ERR err CPU_INTO8U class_nbr USBD_PHDC_Init amp err 1 class_nbr USBD_PHDC_Add DEF_YES 2 DEF_YES App_USBD_PHDC_SetPreambleEn 10 amp err latency rely flags USBD_PHDC_ LATENCY _VERYHIGH RELY BEST USBD_PHDC_ LATENCY HIGH RELY BEST USBD_PHDC_ LATENCY MEDIUM RELY BEST USBD_PHDC_RdCfg class_nbr 3 latency rely flags opaque data CS sizeof opaque _data_rx amp err USBD_PHDC_WrCfg class_nbr 3 USBD_PHDC_ LATENCY _VERYHIGH RELY BEST opaque data tz sizeof opaque data Gi amp err USBD_PHDC_11073_ExtCfg class_nbr dev_specialization 1 amp err 4 valid_cfg_hs USBD_PHDC_CfgAdd class_nbr dev_nbr cfg_hs amp err En valid_cfg_fs USBD_PHDC_CfgAdd class_nbr dev_nbr cfg_fs amp err 6 Listi
203. data for low latency pipe USBD_PHDC WrCfg should be called twice Once with all the desired latency reliability flags set except for low latency opaque data passed at this call will be used for the Bulk endpoint metadata descriptor USBD_PHDC WrCfg should then be called once again with only the low latency flag set opaque data passed at this call will be used for interrupt endpoint metadata descriptor 451 Appendix F F 1 7 USBD_PHDC_11073_ExtCfg Configure function extension for given class instance FILES usbd_phdc h usbd_phdc c PROTOTYPE void USBD_PHDC_11073_ExtCfg CPU_INTO8U class_nbr CPU_LINT16U p dev_specialization CPU_LINTO8U nbr_dev_specialization USBD_ERR p err ARGUMENTS class_nbr PHDC instance number p deu specialization Pointer to an array that contains a list of device specializations nbr_dev_specialization Number of device specializations specified in p_dev_ specialization p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_INVALID ARG RETURNED VALUE None CALLERS Application 452 NOTES WARNINGS USBD_PHDC 11073 ExtCfg should be called only if PHDC instance uses 11073 data format USBD_PHDC 11073 ExtCfg should be called after USBD PHDC Init and USBD_PHDC Add but before USBD_PHDC_CfgAdd For more information on 11073 device specialization See Personal Healthcare Device Class specificati
204. dd subclass_nbr dev_nbr cfg_fs amp err 7 Listing 8 2 CDC ACM Subclass Initialization Example 125 Chapter 8 18 2 1 L8 2 2 L8 2 3 18 2 4 L8 2 5 L8 2 6 L8 2 7 Initialize CDC internal structures and variables Initialize CDC ACM internal structures and variables Create a new CDC ACM subclass instance In this example the line state notification interval is 100 ms In the CCI an interrupt IN endpoint is used to asynchronously notify the host of the status of the different signals forming the serial line The line state notification interval corresponds to the interrupt endpoint s polling interval Register the application callback App USBD_CDC_SerialLineCoding It is called by the ACM subclass when the class specific request SET_LINE CODING has been received by the device This request allows the host to specify the serial line settings baud rate stop bits parity and data bits Refer to CDC PSTN Subclass revision 1 2 section 6 3 10 for more details about this class specific request Register the application callback App USBD CDC SerialLineCtrl It is called by the ACM subclass when the class specific request SET CONTROL LINE STATE has been received by the device This request generates RS 232 V 24 style control signals Refer to CDC PSTN Subclass revision 1 2 section 6 3 12 for more details about this class specific request Check if the high speed configuration i
205. de A description of the arguments passed to the function A description of returned value s Specific notes and warnings regarding use of the service 387 Appendix D D 1 HID CLASS FUNCTIONS D 1 1 USBD_HID_Init This function initializes all the internal variables and modules used by the HID class FILES usbd_hid c PROTOTYPE void USBD_HID Init USBD_ERR p err ARGUMENTS p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE RETURNED VALUE None CALLERS Application NOTES WARNINGS The initialization function must be called only once by the application and before calling any other HID API 388 D 1 2 USBD_HID_Add This function adds a new instance of the HID class FILES usbd_hid c PROTOTYPE void USBD_HID Add CPU_INTO8U subclass CPU_INTO8U protocol USBD_HID COUNTRY_CODE country code CPU_INTO8U p report_desc CPU_INT16U report_desc_len CPU_INTO8U p phy desc CPU_INT16U phy_desc_len CPU_INT16U interval_in CPU_INT16U interval_out CPU_BOOLEAN ctrl rd en USBD_HID CALLBACK p hid callback USBD_ERR p err ARGUMENTS subclass Subclass code protocol Protocol code country_code D report desc report _desc_len D Dh desc phy_desc_len interval_in Country code ID Pointer to report descriptor structure Report descriptor length Pointer to physical descriptor structure Physical descriptor length P
206. device This chapter gives you the necessary information in case your intervention is required during the USB device driver loading and in case your application needs to find a device attached to the computer For the moment this chapter describes this process only for the Windows operating system 45 Chapter 3 3 1 MICROSOFT WINDOWS Microsoft offers class drivers for some standard USB classes These drivers can also be called native drivers A complete list of the native drivers can be found in the MSDN online documentation on the page titled Drivers for the Supported USB Device Classes http msdn microsoft com en us library 538820 VS 85 aspx If a connected device belongs to a class for which a native driver exists Windows automatically loads the driver without any additional actions from you If a vendor specific driver is required for the device a manufacturer s INF file giving instructions to Windows for loading the vendor specific driver is required In some cases a manufacturer s INF file may also be required to load a native driver When the device has been recognized by Windows and is ready for communication your application may need to use a Globally Unique IDentifier GUID to retrieve a device handle that allows your application to communicate with the device These sections explain the use of INF files and GUIDs Table 3 1 shows the USB classes to which the information in the following sub sections appl
207. device and load the proper driver for any new connection The process of indicating the INF file may vary according to the Windows operating system version E Windows XP directly opens the Found New Hardware Wizard Follow the different steps of the wizard until the page where you can indicate the path of the INF file E Windows Vista and later won t open a Found New Hardware Wizard It will just indicate that no driver was found for the vendor device You have to manually open the wizard Open the Device Manager the vendor device connected appears under the category Other Devices with a yellow icon Right click on your device and choose Update Driver Software to open the wizard Follow the different steps of the wizard until the page where you can indicate the path of the INF file 225 Chapter 12 The INF file is located in Micrium Software uC USB Device V4 App Host 0S Windows Vendor INF Refer to section 3 1 1 About INF Files on page 46 for more details about how to edit the INF file to match your Vendor and Product IDs Once the driver is successfully loaded the Windows host application is ready to be launched The executable is located in the following folder Micrium Software uC USB Device V4 App Host 0S Windows Vendor Visual Studio 2010 exe There are two executables P EchoSync exe for the Windows application with the synchronous communication API of USBDev_API E E
208. dpoints Standard EPDescGetSize GET_DESCRIPTOR No Callback skipped if no class specific descriptors for one or more endpoints Standard IFReq GET_DESCRIPTOR No Callback skipped if no standard descriptors provided by a class Class ClassReq No Callback skipped if no class specific requests defined by the class specification Vendor VendorReq No Callback skipped if no vendor requests Table 7 2 Class Callbacks and Requests Mapping 113 Chapter 7 114 Chapter Communications Device Class This chapter describes the Communications Device Class CDC class and the associated CDC subclass supported by pC USB Device uC USB Device currently supports the Abstract Control Model ACM subclass which is especially used for serial emulation The CDC and the associated subclass implementation complies with the following specifications E Universal Serial Bus Class Definitions for Communications Devices Revision 1 2 November 3 2010 E Universal Serial Bus Communications Subclass for PSTN Devices revision 1 2 February 9 2007 CDC includes various telecommunication and networking devices Telecommunication devices encompass analog modems analog and digital telephones ISDN terminal adapters etc Networking devices contain for example ADSL and cable modems Ethernet adapters and hubs CDC defines a framework to encapsulate existing communication services standards such as V 250 for modems over
209. dr p_buf buf_len xfer len p_arg 274 CPU_INTO8U ep addr void p buf CPU_INT32U buf_len CPU_INT32U xfer_len void p arg USBD_ERR err Device number Endpoint address Pointer to buffer of data that will be transmitted Buffer length Number of byte transmitted Pointer to function argument err Error status USBD_ERR_NONE USBD_ERR_EP ABORT E If end of transfer is set and transfer length is multiple of maximum packet size a zero length packet is transferred to indicate a short transfer to the host 275 Appendix A A 4 8 USBD_IntrAdd Adds an interrupt endpoint to alternate setting interface FILES usbd_core h usbd_core c PROTOTYPE CPU_INTO8U USBD_IntrAdd CPU_INTO8U dev_nbr CPU_INTO8U cfg nbr CPU_INTO8U if_nbr CPU_INTO8U if alt br CPU_BOOLEAN dir in CPU_INT16U max_pkt_len CPU_INT16U interval USBD_ERR p err ARGUMENTS dev_nbr Device number cfg_nbr Configuration number if_nbr Interface number if_alt_nbr Interface alternate setting number dir_in Endpoint direction DEF_YES IN direction DEF_NO OUT direction max pkt_len Endpoint maximum packet length see Note 1 interval Endpoint interval in frames microframes 276 p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_INVALID ARG USBD_ERR_ DEV INVALID NBR USBD_ERR CFG INVALID NBR USBD_ERR_IF INVALID NBR USBD_ERR_EP NONE AVAIL USBD_
210. e further mapped to other macros to simplify the repetition of endpoint address and interface number parameters Listing 13 4 shows an example of a bus specific debug macro and a standard debug macro found in usbd_core c 235 Chapter 13 define define 236 USBD_DBG_CORE_BUS msg USBD_DBG_CORE_STD msg USBD_DBG _GENERIC msg USBD_EP ADDR NONE USBD_IF_NBR_NONE USBD_DBG GENERIC msg Ou USBD_IF_NBR_NONE Listing 13 4 Mapped Core Tracing Macros Chapter 14 Porting uC USB Device to your RTOS pC USB Device requires a Real Time Operating System RTOS In order to make it usable with nearly any RTOS available on the market it has been designed to be easily portable Micrium provides ports for both pC OS I and pC OS III and recommends using one of these RTOS In case you need to use another RTOS this chapter will explain you how to port C USB Device to your RTOS 237 Chapter 14 14 1 OVERVIEW pC USB Device uses some RTOS abstraction ports to interact with the RTOS Instead of being a simple wrapper for common RTOS service functions TaskCreate SemaphorePost etc those ports are in charge of allocating and managing all the OS resources needed All the APIs are related to the uC USB Device module feature that uses it This offers you a better flexibility of implementation as you can decide which OS services can be used for each specific action Table 14 1 gives an example of comparison bet
211. e interface class specific descriptors Ask the class for the total size of interface class specific descriptors Ask the class to build endpoint class specific descriptors 111 Chapter 7 L7 7 8 Ask the class for the total size of endpoint class specific descriptors L7 7 9 Ask the class to process a standard request whose recipient is an interface L7 7 10 Ask the class to process a class specific request L7 7011 Ask the class to process a vendor specific request A class is not required to provide all the callbacks If a class for instance does not define alternate interface settings and does not process any vendor requests the corresponding function pointer will be a null pointer Listing 7 8 presents the callback structure for that case static USBD CLASS DRV USBD_XXXX_ Drv USBD_XXXX_Conn USBD_XXXX_Disconn 0 USBD_XXXX_UpdateEPState USBD_XXXX_IFDesc USBD_XXXX_IFDescGetSize USBD_XXXX_EPDesc USBD_XXXX_EPDescGetSize USBD_XXXX_IFReq USBD_XXXX_ClassReq 0 H Listing 7 8 Class Callback Structure with Null Function Pointers If a class is composed of one interface then one class callback structure is required If a class is composed of several interfaces then the class may define several class callback structures In that case a callback structure may be linked to one or several interfaces For instance the Communication Device Class CDC is composed of one Communication Interface and one or more Data Interfaces
212. e number CALLERS USBD_HID OutputDataCmp1 IMPLEMENTATION GUIDELINES If the output report transfer completes with an error the task waiting is waken up by aborting the active wait done with USBD_HID OS OutputDataPend The active wait abortion is executed by the Core layer internal task responsible for asynchronous communication 413 Appendix D D 2 11 USBD_HID_OS OutputDataPost Signal that Output report data has been received from the host FILES usbd_hid_os c PROTOTYPE void USBD HID OS OutputDataPost CPU_INTO8U class nbr ARGUMENTS class nbr_ Class instance number CALLERS USBD_HID OutputDataCmp1 IMPLEMENTATION GUIDELINES If the output report transfer completes without an error the task waiting is waken up by posting a semaphore The semaphore post is executed by the Core layer internal task responsible for asynchronous communication 414 D 2 12 USBD_HID_OS TxLock Lock class transmit FILES usbd_hid_os c PROTOTYPE void USBD HID OS TxLock CPU_INTO8U class nr USBD_ERR p err ARGUMENTS class nr Class instance number p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE OS error code s relevant to failure s CALLERS USBD_HID Wr USBD_HID WrAsync IMPLEMENTATION GUIDELINES The lock operation typically consists in pending on a semaphore If the semaphore is free the task continues normally its execution othe
213. e number CALLERS USBD_HID_WrSyncCmp1 IMPLEMENTATION GUIDELINES If the input report transfer completes without an error the task waiting is waken up by posting a semaphore The semaphore post is executed by the Core layer internal task responsible for asynchronous communication 408 D 2 7 USBD_HID_ OS OutputLock Lock class output report FILES usbd_hid_os c PROTOTYPE void USBD HID OS OutputLock CPU_INTO8U class_nbr USBD ERR p err ARGUMENTS class nbr_ Class instance number p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE OS error code s relevant to failure s CALLERS USBD_HID Rd USBD_HID_ RdAsync USBD_HID_ClassReq IMPLEMENTATION GUIDELINES The lock operation typically consists in pending on a semaphore If the semaphore is free the task continues normally its execution otherwise it waits until another task releases the semaphore p err argument should be assigned as described in Table D 3 Operation result Error code to assign No error USBD_ERR_NONE Pend aborted USBD_ERR_OS_ABORT Pend failed for any other reason USBD_ERR_OS FAIL Table D 3 p_err assignment according to the pend operation result 409 Appendix D D 2 8 USBD_HID_OS OutputUnlock Unlock class output report FILES usbd_hid_os c PROTOTYPE void USBD HID OS OutputUnlock CPU_INTO8U class_nbr ARGUMENTS class nbr_ Class instance numbe
214. eap that has been allocated for the Device Controller Driver Refer to pC LIB documentation for more information Specification Configuration Architecture ARM Microcontroller NXP LPC2468 EA Compiler IAR EWARM V6 21 Compiler Optimization High for Size and Speed OS uC OS II Table l 1 Memory Footprint Environment Configuration 531 Appendix Device Configuration Value USBD_CFG OPTIMIZE SPD DEF_DISABLED USBD_CFG MAX NBR DEV 1 USBD_CFG MAX NBR CFG 1 Table l 2 Memory Footprint C USB Device Configuration l 0 1 COMMUNICATIONS DEVICE CLASS The Communication Device Class CDC configuration is presented in Table I 3 and its associated memory footprint table is shown in Table I 4 Configuration Value USBD_CFG MAX NBR_IF 2 USBD_CFG MAX NBR_IF ALT 2 USBD_CFG MAX NBR_IF GRP 1 USBD_CFG MAX NBR_EP DESC 3 USBD_CFG MAX NBR_EP OPEN 5 USBD_CDC_CFG MAX NBR DEV 1 USBD_CDC_CFG MAX NBR_CFG 2 USBD_CDC_CFG MAX NBR DATA IF 1 USBD_ACM SERIAL CFG MAX NBR_DEV 1 532 Table l 3 CDC Configuration for Memory Footprint Module Code kB Constant kB Data kB Device Core 20 62 0 47 Device RTOS Port 0 76 1 39 Device Controller Driver 6 74 0 21 Data allocated from heap CDC 2 55 z 0 07 ACM Subclass 2 20 0 04 Total 32 87 0 21 1 97 Table l 4 CDC Memory Footprint l 0 2 HUMAN INTERFACE DEVICE CLASS The Human Inte
215. eate CPU_INTO8U dev_nbr CPU_LINTO8U ep _ix USBD_ERR p_err ARGUMENTS dev_nbr Device number ep_ix Endpoint index p err Pointer to variable that will receive the return error code from this function RETURNED VALUE None CALLERS Endpoints open functions IMPLEMENTATION GUIDELINES E The purpose of this function is to allocate a signal or a semaphore for the specified endpoint 302 Typically the RTOS layer code should create a two dimensional array to store the signals semaphores handlers The dev_nbr and ep_ix are used to index this array dev_nbr ranges between 0 and USBD_CFG_MAX NBR DEV ep_ix ranges between 0 and USBD_CFG MAX NBR_EP_OPEN In case the creation fails USBD_ERR_OS SIGNAL CREATE should be assigned to p err Otherwise USBD_ERR_NONE should be assigned to p err 303 Appendix A A 5 5 USBD_OS EP SignalDel Deletes a signal semaphore FILES usbd_internal h usbd_os c PROTOTYPE void USBD_OS EP SignalDel CPU_INTO8U dev_nbr CPU_INTO8U ep Lei ARGUMENTS dev_nbr Device number ep_ix Endpoint index RETURNED VALUE None CALLERS Endpoints close functions IMPLEMENTATION GUIDELINES A call to this function should delete the signal semaphore associated to the specified endpoint 304 A 5 6 USBD_OS EP _SignalPend Waits for a signal semaphore to become available FILES usbd_internal h usbd_os c PROTOTYPE void USBD_OS EP SignalPend CPU_INTO8U dev_nbr
216. ects These Visual Studio projects build applications that interact with a USB device They use a device interface class GUID to detect any attached device belonging to the class Table 3 3 shows the Micrium class and the corresponding device interface class GUID used in the class Visual Studio project 51 Chapter 3 Micripm class Device interface class GUID Defined in HID 4d1e55b2 16f 11c 88cb 001111000030 app hid common h PHDC 143f20bd 7bd2 4ca6 9465 8882f2156bd6 usbdev_guid h Vendor 143 20bd 7bd2 4ca6 9465 8882 2156bd6 usbdev_guid h Table 3 3 Micrium Class and Device Interface Class GUID The interface class GUID for the HID class is provided by Microsoft as part of system defined device interface classes whereas the interface class GUID for PHDC and Vendor classes has been generated with Visual Studio 2010 using the utility tool guidgen exe This tool is accessible from the menu Tools and the option Create GUID or through the command line by selecting the menu Tools option Visual Studio Command Prompt and by typing guidgen at the prompt 52 Chapter Architecture pC USB Device was designed to be modular and easy to adapt to a variety of Central Processing Units CPUs Real Time Operating Systems RTOS USB device controllers and compilers Figure 4 1 shows a simplified block diagram of all the uC USB Device modules and their relationships 53 Chapter 4 Application Run
217. ed the assignment of the device address can also be combined with enabling the device address mode P For device controllers that change the device address immediately without waiting the status phase to complete see USBD_DrvAddrEn 329 Appendix B B 1 5 USBD_DrvAddrEn The next function in the device API structure is the device address enable AddrEn function FILES Every device driver s usbd_drv c PROTOTYPE static CPU_BOOLEAN USBD DrvAddrEn USBD Du ap dru CPU_INTO8U dev_addr ARGUMENTS p drv Pointer to USB device driver structure dev_addr Device address assigned by the host RETURNED VALUE None CALLERS USBD_StdReqHandler via p drv_api gt AddrEn NOTES WARNINGS E For device controllers that have hardware assistance to enable the device address after the status stage has completed no operation needs to be performed E For device controllers that change the device address immediately without waiting the status phase to complete the device address must be set and enabled 330 B 1 6 USBD DrvCfgSet Bring device into configured state FILES Every device driver s usbd_drv c PROTOTYPE static CPU BOOLEAN USBD DrvCfgSet USBD DRV p drv CPU_INTO8U cfg val ARGUMENTS p drv Pointer to USB device driver structure cfg_val Configuration value RETURNED VALUE DEF_OK if NO error s DEF_FAIL otherwise CALLERS USBD_CfgOpen via p drv_api gt CfgSet
218. eeeeeeeeeeeeeeeeceeeeeeseeeeeeeseeneeeeeeeeeees 89 Device Asynchronous Receive AER EEN 91 Device Synchronous Transmit ceeceeecesseeeeeeceeeeeeeeeseeeeeeseaneeeeeeeenees 93 Device Asynchronous Transmit ccccccceeeeeeeeeeeeeeeeeeneeeeseeneeneeeeeeeseeeees 95 Device Set Address aera renan raeme maa a aaa danena a daadaa aaaeaii a daaa aa daaa Ea 97 USB Classe eeneg ae Eeer aa adaa ENEE aaa 99 Class Instance Concept ccse seeeeeeeeeee eee eeeeeeeeeaeneeeeeeeseeeesneeeeseeesnanee 99 Class Instance Structures kee 108 Class and Core Layers Interaction through Callbacks sceeee 111 Communications Device Class cccccceeseeseeeseeeeeeeeeeeeeeeeeeeeeneeneaees 115 VOI a eege eege deleng 116 e e 119 eu Uu TE de DE 120 General Configuration ee EEN 120 e Oe EE 121 EE 121 Table of Contents 8 4 2 8 4 3 8 4 4 8 4 5 8 4 6 Chapter 9 9 1 9 1 1 9 2 9 3 9 3 1 9 3 2 9 3 3 9 3 4 9 3 5 9 4 9 4 1 9 4 2 9 5 9 6 Chapter 10 10 1 10 1 1 10 1 2 10 1 3 10 1 4 10 2 10 2 1 10 2 2 10 2 3 10 3 10 3 1 10 4 10 4 1 10 4 2 10 5 6 General Configuration ee EEN EEN 123 Subclass Instance Configuration sccccsesseeeeeeeseneeeeeeeeseeeeeenseeeeees 123 Subclass Notification and Management sseeeeeeeeeeeeeeeeeeeees 127 Subclass Instance COMMUNICATION REENEN 128 Using the Demo Application cceesseeeeeeeeeeeeeeeeeeeeeeesseeeeeeeeeeenes 129 Human Interface Device Class
219. eive the return error code from this function RETURNED VALUE Pointer to core event if no errors Null pointer otherwise CALLERS USBD_CoreTaskHandler IMPLEMENTATION GUIDELINES A call to this function should block until an event is added to queue and return it Table A 1 describes the error codes that should be assigned to p_err depending on the operation result 310 A 5 11 USBD_OS DbgEventRdy Signals debug event handler task FILES usbd_internal h usbd_os c PROTOTYPE void USBD_OS DbgEventRdy void ARGUMENTS None RETURNED VALUE None CALLERS Debug functions IMPLEMENTATION GUIDELINES A call to this function should post the signal semaphore that resume the debug task 311 Appendix A A 5 12 USBD_OS DbgEventWait Waits until a trace event is available FILES usbd_internal h usbd_os c PROTOTYPE void USBD_OS DbgEventWait void ARGUMENTS None RETURNED VALUE None CALLERS USBD_DbgTaskHandler IMPLEMENTATION GUIDELINES A call to this function should pend on the signal semaphore that resume the debug task 312 A 6 DEVICE DRIVERS CALLBACKS FUNCTIONS A 6 1 USBD_EP_RxCmpi Notifies the stack that an OUT transfer is completed FILES usbd_core h usbd_ep c PROTOTYPE void USBD_EP_RxCmpl USBD_DRV p_drv CPU_INTO8U ep _log_nbr ARGUMENTS p drv Pointer to device driver structure ep_log_nbr Endpoint logical number RETURNE
220. ent s 8 USBD_ERR_INVALID_CLASS_STATE Invalid class state H 2 DEVICE ERROR CODES 100 USBD_ERR_DEV_ALLOC Device allocation failed 101 USBD_ERR_DEV_INVALID_NBR Invalid device number 102 USBD_ERR_DEV_INVALID_ STATE Invalid device state 103 USBD_ERR_DEV_INVALID_SPD Invalid device speed H 3 CONFIGURATION ERROR CODES 200 USBD_ERR_CFG ALLOC Configuration allocation failed 201 USBD_ERR_CFG INVALID NBR Invalid configuration number 202 USBD_ERR_ CFG INVALID MAX PWR Invalid maximum power 203 USBD_ERR_CFG SET FAIL Device driver set configuration failed 528 H 4 INTERFACE ERROR CODES 300 USBD_ERR_IF_ALLOC Interface allocation failed 301 USBD_ERR_IF_ INVALID NBR Invalid interface number 302 USBD_ERR_IF_ALT ALLOC Alternate interface setting allocation failed 303 USBD ERR IF ALT INVALID NBR Invalid interface alternate setting number 304 USBD_ERR_IF_GRP_ALLOC Interface group allocation failed 305 USBD_ERR_IF_GRP_NBR_IN_USE Interface group number already in use H 5 ENDPOINT ERROR CODES 400 USBD_ERR_EP_ALLOC Endpoint allocation failed 401 USBD_ERR_EP INVALID ADDR Invalid endpoint address 402 USBD_ERR_EP_ INVALID STATE Invalid endpoint state 403 USBD_ERR_EP INVALID TYPE Invalid endpoint type 404 USBD_ERR_EP_NONE_AVAIL Physical endpoint NOT available 405 USBD_ERR_EP_ABORT Device driver abort transfer for an endpoint failed 406 USBD_ERR_EP_S
221. er therefore reflects the differences when it is one configuration or the other 535 Appendix Configuration Value USBD_CFG OPTIMIZE SPD DEF_DISABLED USBD_CFG MAX NBR_DEV 1 USBD_CFG MAX NBR_CFG 1 USBD_CFG MAX NBR_IF 1 USBD_CFG MAX NBR_IF ALT 1 USBD_CFG MAX NBR_IF GRP 0 USBD_CFG MAX NBR_EP DESC 2 USBD_CFG MAX NBR_EP OPEN 4 USBD_PHDC_CFG MAX NBR DEV 1 USBD_PHDC_CFG MAX NBR CFG 2 USBD_PHDC_ CFG DATA OPAQUE MAX LEN 43 USBD_PHDC_OS CFG SCHED EN DEF_ENABLED DEF_ DISABLED Table 9 PHDC Configuration for Memory Footprint Module Code kB Constant kB Data kB Device Core 19 82 0 85 Device RTOS Port 0 76 1 35 Device Controller Driver 6 74 0 21 Data allocated from heap PHDC 4 70 0 21 PHDC RTOS Port QOS 1 56 1 62 Based Scheduler Enabled PHDC RTOS Port QOS 0 66 0 11 Based Scheduler Disabled Total QOS Based 33 58 32 68 0 21 4 03 2 52 Scheduler Enabled Disabled Table l 10 PHDC Memory Footprint 536 1 0 5 VENDOR CLASS The Vendor Class configuration is presented in Table I 11 and its associated memory footprint table is shown in Table I 12 Note that there is a pair of Interrupt IN OUT endpoints that you may add during Vendor Class initialization that has been omitted in the configuration below Configuration Value USBD_CFG MAX NBR_IF 1 USBD_CFG MAX NBR_IF ALT 1 USBD_CFG MAX NB
222. err Pointer to variable that will receive the return error code from this function USBD_ERR_SCSI_MEDIUM NOTPRESENT USBD_ERR_NONE RETURNED VALUE None CALLERS USBD_SCSI_IssueCmd NOTES WARNINGS None 435 Appendix E E 3 3 USBD_StorageRd Read data from the storage medium FILES usbd_storage h usbd_storage c PROTOTYPE void USBD_StorageRd USBD_STORAGE_ LUN ep storage _lun CPU_INT32U blk_addr CPU_INT32U nbr_blks CPU_INTO8U p data_buf USBD_ERR p err ARGUMENTS p storage lun Pointer to the logical unit storage structure blk_addr Logical Block Address LBA of read block start nbr_blks Number of logical blocks to read p_data_buf Pointer to buffer in which data will be stored p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_SCSI_MEDIUM NOT PRESENT RETURNED VALUE None CALLERS USBD_SCSI_RdData NOTES WARNINGS None 436 E 3 4 USBD_StorageWr Write data to the storage medium FILES usbd_storage h usbd_storage c PROTOTYPE void USBD StorageWr USBD STORAGE LUN p storage lun CPU_INT32U blk_addr CPU_INT32U nbr_blks CPU_INTO8U p data_buf USBD_ERR p err ARGUMENTS p storage lun Pointer to logical unit storage structure blk_addr Logical Block Address LBA of write block start nbr_blks Number of logical blocks to write p_data_buf Pointer to buffer in which data i
223. es E You can copy paste data E You can delete one or more files All of these actions will generate SCSI commands to write and read the mass storage device 10 6 PORTING MSC TO A STORAGE LAYER The storage layer port must implement the API functions summarized in Table 10 10 You can start by referencing to the storage port template located under Micrium Software uC USB Device V4 Class MSC Storage Template Please refer to section E 3 MSC Storage Layer Functions on page 434 for a full listing of the storage layer API 180 Function Name Porting MSC to a RTOS Operation USBD_StorageInit Initializes the storage medium USBD_StorageCapacityGet Gets the capacity of the storage medium USBD_StorageRd Reads data from the storage medium USBD_StorageWr Writes data to the storage medium USBD_StorageStatusGet Gets the status of the storage medium If the storage medium is a removable device such as an SD MMC card this function will return if the storage is inserted or removed Table 10 10 Storage API Functions 10 7 PORTING MSC TO A RTOS The RTOS layer must implement the API functions listed in Table 10 11 You can start by referencing the RTOS port template located under Micrium Software uC USB Device V4 Class MSC 0OS Template Please refer to section E 2 MSC OS Functions on page 428 for a full API description Function Operation USBD MSC OS Init
224. es the maximum number of string descriptors supported Default value is 3 1 Manufacturer string 1 product string and 1 serial number string This value can be increased if for example you plan to add interface specific strings 67 Chapter 5 5 1 5 DEBUG CONFIGURATION Configurations in this section only need to be set if you use the core debugging service For more information on that service see Chapter 13 Debug and Trace on page 231 USBD_CFG_DBG_TRACE EN USBD_CFG _DBG TRACE EN enables or disables the core debug trace engine DEF_ENABLED Core debug trace engine is enabled DEF_DISABLED Core debug trace engine is disabled USBD_CFG_DBG_TRACE NBR_EVENTS USBD_CFG DBG TRACE NBR EVENTS indicates the maximum number of debug trace events that can be queued by the core debug trace engine Default value is 10 This configuration constant has no effect and will not allocate any memory if USBD_CFG DBG TRACE EN is set to DEF_DISABLED 5 1 6 COMMUNICATION DEVICE CLASS CDC CONFIGURATION For information on CDC configuration refer to section 8 3 Configuration on page 120 5 1 7 CDC ABSTRACT CONTROL MODEL ACM SERIAL CLASS CONFIGURATION For information on CDC ACM class configuration refer to section 8 4 2 General Configuration on page 123 5 1 8 HUMAN INTERFACE DEVICE HID CLASS CONFIGURATION For information on HID class configuration refer to Section 9 3 Configuration on page 143 68 A
225. escriptor content the host s HID parser is able to interpret the Input report data sent by the device with an interrupt IN transfer or in response to a GET_REPORT request The Input report data corresponding to the mouse Report descriptor shown in Figure 9 1 is presented in Table 9 3 The total size of the report data is 4 bytes Different types of reports may be sent over the same endpoint For the purpose of distinguishing the different types of reports a 1 byte report ID prefix is added to the data report If a report ID was used in the example of the mouse report the total size of the report data would be 5 bytes Bit offset Bit count Description 0 1 Button 1 left button 1 1 Button 2 right button 2 1 Button 3 wheel button 3 13 Not used 16 8 Position on axis X 24 8 Position on axis Y Table 9 3 Input Report Sent to Host and Corresponding to the State of a 3 Buttons Mouse A Physical descriptor indicates the part or parts of the body intended to activate a control or controls An application may use this information to assign a functionality to the control of a device A Physical descriptor is an optional class specific descriptor and most devices have little gain for using it Refer to Device Class Definition for Human Interface Devices HID Version 1 11 section 6 2 3 for more details about this descriptor 141 Chapter 9 9 2 ARCHITECTURE Figure 9 2 shows the general architecture
226. eseeeeeeeeeeeeeeeeeseeeeesseaneeeeeeeeeeees 333 USBD DIVEP O pein a a ara aa aa Ou Sos ens cas a aaa er A aa aae eee 334 USBD_DrVEP_CloS s ceccccceeeeeeeeeseesssenceeeeseeeesnesesseessaeseeseseeenens 336 USBD2DrvEP RxStart ernia dldti alanat Enean iaiia 337 WSBDIDWVEP RX tee ee eeh 339 USBD_DrVEP_RXZLP c ccccccceceeeeessesssseceeeeseeeeseesessesssanseeseseeenens 341 USBD DIVEP2TX science chia i Seis Ee AE 342 USBD_DrvEP_TxStart cccccccccceceecesssssssscceesesseeeseeseessesssanseesesseenens 344 USBD DER TXZLP a eaaa aaaea aaa cae alee 346 USBD Drw EP Abor earar oaae aa nanena ntaa a Seet Ee deEe eenegen 347 USBD DrvEP Stall aea a aaa ANEN gEes 348 USBD_DrvISR_Handler cccccecceeeeeeeeeeeeeeeeeeeeeeeeeeeeessaneeeeeeeeeeens 349 Device Driver BSP Functions ccccceceseeeeeeeeceseseseeeeeeeaseeaeseeeeeeeees 350 LEET CT e EE 350 USBD_BSP_COmn E A E ETAT 351 USBD BSP DISCONMN eeaeee ninani aiena aaa anaa anaa paanan tah dani aiaiai 352 CDG API ReTErenGe EEEE E EEN T 353 CDG FUNCTIONS nae EE A E E A ee ieee ene 354 USBD GDC TT RE 354 DEEIDIS ee EE 355 TT e R et e RE 358 USBD_CDC_ISCOnN c sc sccecceeeeeeseeeeesseeseeseeseeeseesesssesscnseeseeeeeeees 360 USBD_CDC_DatalF_Add cccccccssssessesssseeceeeeeesesseessseneaeseeseseeenens 361 USBD CDG DataRXx ageet nee deities 363 C 1 7 USBD_CDC_DataT x ccccccccssceeseseeeseeeeesneeessessesneeeseses
227. esseeeeesseas 365 C 1 8 USBD CDO Notify sss ccciscivikivn a oid sd atvasi avidin wea aS 367 C 2 CDC ACM Subclass Functions AANEREN 369 C 2 1 USBD_ACM_Serriallnit 2 cccccceeceseeseeeeeceeeeeeeeeeeeeeseeesseneeeeeeeeeeens 369 C 2 2 USBD_ACM_SerialACd ccccecceeeeeeeeseeeeeeeeeeeeeeseseeeseeeneaneeeeeeeeenens 370 C 2 3 USBD_ACM_SerialCfgAdd scccccesseecceeesseeeeeeeeseeeeeeenseaaeeeeeeeeaes 371 C 2 4 USBD_ACM_SeriallSConn 2 ccecceseeeseeeeeeeeeeeeeeeeseeeeeesseaeeeeeeeeeenens 373 C 2 5 USBD_ACM_SerialRX cccceeeeeeeeeeeeeeeeneeeeeeeeeeeeeeeeeeeeseaeeeeeeeeeenees 374 C 2 6 USBD_ACM_SerialTx cccccccessseeceeeeseeeeeeeeesaeeeeensseaeseeenseaaeeeeeneaaes 376 C 2 7 USBD_ACM_SerialLineCtrlGet c eeeceeceeeeeeeeeeeesseeeeeeeeeeeeees 378 C 2 8 USBD_ACM_SerialLineCtrlReg ee REENEN 379 C 2 9 USBD_ACM_SerialLineCodingGet cccccessseeeeesseeeeeeeeesneeeeeeeeeeees 381 C 2 10 USBD_ACM_SerialLineCodingSet cccccceseeeseessseeeeeseeeeeeeeeeeeeeees 382 C 2 11 USBD_ACM_SerialLineCodingReg sccccesseeceeseseeeseseesneeseeenseeees 383 C 2 12 USBD_ACM_SerialLineStateSet ecccccceseesceeeeeseeeeeeeeseeeeeeenseees 385 C 2 13 USBD_ACM_SerialLineStateClr s eeececeeeeeeeeeeeeeseeeeeeeeeeeeenens 386 Appendix D HID API Reference ou eecececceceeceeeeeeeeeeeeeaeeeseseeeeeaeaeanasaseseeeeeeenes 387 D 1 HID Classi e Ti ere EE 388 D 1 1
228. est with the controls set SetBreak The host sends this request to generate an RS 232 style break For a serial emulation certain serial terminals allow you to send this request Table 8 4 ACM Requests Supported by Micrium Micrium s ACM subclass uses the interrupt IN endpoint to notify the host about the current serial line state The serial line state is a bitmap informing the host about E Data discarded because of overrun PB Parity error E Framing error E State of the ring signal detection E State of break detection mechanism E State of transmission carrier PB State of receiver carrier detection 122 8 4 2 GENERAL CONFIGURATION Table 8 5 shows the constant available to customize the ACM serial emulation subclass This constant is located in the USB device configuration file usbd_cfg h Constant ACM Subclass Description USBD_ACM SERIAL CFG MAX NBR DEV Configures the maximum number of subclass instances The constant value cannot be greater than USBD_CDC_CFG MAX NBR_DEV Unless you plan on having multiple configurations or interfaces using different class instances this can be set to 1 Table 8 5 ACM Serial Emulation Subclass Configuration Constants 8 4 3 SUBCLASS INSTANCE CONFIGURATION Before starting the communication phase your application needs to initialize and configure the class to suit its needs Table 8 6 summarizes the initialization functions provided by the ACM subclass F
229. f a high speed and a full speed configurations with USBD_CfgAdd Listing 7 3 below shows the use USBD_CfgOtherSpeed based on Listing 2 5 Error handling is omitted for clarity CCPU_BOOLEAN App USBD Init void CPU_INTO8U dev_nbr CPU_LINTO8U cfg_0 fs CPU_LINTO8U cfg_0_hs USBD_ERR err 1 if USBD_DrvCfg_ lt controller gt Spd USBD_DEV_SPD_HIGH cfg_0_ hs USBD_CfgAdd dev_nbr 2 USBD_DEV_ ATTRIB SELF POWERED 100u USBD_DEV_SPD_HIGH HS configuration amp err cfg_0 fs USBD_CfgAdd dev_nbr 3 USBD_DEV_ATTRIB SELF POWERED 100u USBD_DEV_SPD FULL FS configuration amp err USBD_CfgOtherSpeed dev_nbr 4 cfg_0_hs cfg_0_ fs amp err return DEF OK Listing 7 3 Use of USBD_CfgOtherSpeed 104 L7 3 1 L7 3 2 L7 3 3 L7 3 4 Class Instance Concept Refer to Listing 2 5 for the beginning of the initialization Create the high speed configuration cfg_0_hs to your high speed capable device Create the full speed configuration cfg_0 fs to your high speed capable device Associate the high speed configuration cfg_0_hs with its other speed counterpart cfg_0 fs Figure 7 3 represents a more complex example A full speed device is composed of two configurations The device has two functions which belong to the same class Each function is described by two interfaces Each interface has a pair of bidirectional endpoints In this example two class instances
230. g_fs 1 2 Listing 8 1 CDC Initialization Example ACM Subclass L8 1 1 Initialize CDC internal structures and variables This is the first function you should call and you should do it only once L8 1 2 Call all the required functions to initialize the subclass es Refer to section 8 4 2 General Configuration on page 123 for ACM subclass initialization 8 4 ACM SUBCLASS The ACM subclass is used by two types of communication devices E Devices supporting AT commands for instance voiceband modems E Serial emulation devices which are also called Virtual COM port devices Micrium s ACM subclass implementation complies with the following specification m Universal Serial Bus Communications Subclass for PSTN Devices revision 1 2 February 9 2007 8 4 1 OVERVIEW The general characteristics of the CDC base class in terms of Communications Class Interface CCI and Data Class Interface DCD were presented in section 8 1 Overview on page 116 In this section a CCI of type ACM is considered It will consist of a default endpoint for the management element and an interrupt endpoint for the notification element A pair of bulk endpoints is used to carry unspecified data over the DCI Several subclass specific requests exists for the ACM subclass They allow you to control and configure the device The complete list and description of all ACM requests can be found in the specification Universal Serial Bus Com
231. ge USB Device Universal Serial Bus Device Stack User s Manual V4 00 Micripm For the Way Engineers Work Micrium 1290 Weston Road Suite 306 Weston FL 33326 USA www micrium com Designations used by companies to distinguish their products are often claimed as trademarks In all instances where Micrium Press is aware of a trademark claim the product name appears in initial capital letters in all capital letters or in accordance with the vendor s capitalization preference Readers should contact the appropriate companies for more complete information on trademarks and trademark registrations All trademarks and registered trademarks in this book are the property of their respective holders Copyright 2012 by Micrium except where noted otherwise All rights reserved Printed in the United States of America No part of this publication may be reproduced or distributed in any form or by any means or stored in a database or retrieval system without the prior written permission of the publisher with the exception that the program listings may be entered stored and executed in a computer system but they may not be reproduced for publication The programs and code examples in this book are presented for instructional value The programs and examples have been carefully tested but are not guaranteed to any particular purpose The publisher does not offer any warranties and does not guarantee the accuracy adequacy or complete
232. gh latency data Very high latency data Bus usage 6 825 1 to add a new item 2 to exit Figure 11 6 Demo Application with five Items Added 11 6 PORTING PHDC TO A RTOS Since PHDC communication functions can be called from different tasks at application level there is a need to protect the resources they use in this case the endpoint Furthermore since it is possible to send data with different QoS using a single bulk endpoint an application might want to prioritize the transfers by their QoS G e medium latency transfers processed before high latency transfers This kind of prioritization can be implemented customized inside the RTOS layer see Section 11 4 RTOS QoS based scheduler on page 196 for more information By default Micrium will provide an RTOS layer for both pC OS II and pC OS III However it is possible to create your own RTOS layer Your layer will need to implement the functions listed in Table 11 15 For a complete API description see Appendix F PHDC API Reference on page 441 203 Chapter 11 Function name Operation USBD_PHDC_OS Init USBD_PHDC_OS_RdLock Initializes all internal members tasks Locks read pipe USBD_PHDC_OS_RdUnlock Unlocks read pipe USBD_PHDC_OS_WrBulkLock Locks write bulk pipe USBD_PHDC_OS WrBulkUnlock Unlocks write bulk pipe USBD_PHDC_OS_WrIntrLock Locks write interrupt pipe USBD_P
233. he function App USBD_Init which initializes the USB stack and class specific demos app_usbd lt class gt c contains a template to initialize and use a certain class This file contains the class demo application In general the class application initializes the class creates a class instance and adds the instance to the full speed and high speed configurations Refer to the chapter s of the class es you purchased for more details about the class demos 33 Chapter 2 usbd_cfg h is a configuration file used to setup wC USB Device stack parameters such as the maximum number of configurations interfaces or class related parameters usbd_dev_cfg c and usbd_dev_cfg h are configuration files used to set device parameters such as vendor ID product ID and device release number They also serve to configure the USB device controller driver parameters such as base address dedicated memory base address and size controller s speed and endpoint capabilities MODIFY DEVICE CONFIGURATION Modify the device configuration file usbd_cfg c as needed for your application See below for details USBD_DEV_CFG USBD DevCfg Template 1 OxFFFE 2 0x1234 0x0100 OEM MANUFACTURER 3 OEM PRODUCT 1234567890ABCDEF USBD_LANG ID ENGLISH_US 4 ti Listing 2 1 Device Configuration Template L2 1 1 Give your device configuration a meaningful name by replacing the word Template L2 1 2 Assign the Vendor ID Product I
234. he host On the device side the demo application file app_usbd_vendor c provided for uC OS II and pC OS II is located in these two folders E Micrium Software uC USB Device V4 App Device 0S uCcOS II E Micrium Software uC USB Device V4 App Device 0S uCOS III app_usbd_vendor c contains the Echo demo available in two versions E The Echo Sync demo exercises the synchronous communication API described in section 12 2 4 Synchronous Communication on page 211 E The Echo Async demo exercises the asynchronous communication API described in section 12 2 5 Asynchronous Communication on page 212 220 Using the Demo Application The use of these constants defined usually in app_cfg h allows you to use the vendor demo application Constant Description APP_CFG_USBD_VENDOR_EN General constant to enable the Vendor class demo application Must be set to DEF_ENABLED APP_CFG _USBD_VENDOR_ECHO SYNC_EN Enables or disables the Echo Sync demo The possible values are DEF_ENABLED or DEF DISABLED APP_CFG _USBD_VENDOR_ECHO ASYNC_EN Enables or disables the Echo Async demo The possible values are DEF_ENABLED or DEF_DISABLED APP_CFG USBD_VENDOR_ECHO SYNC_TASK PRIO Priority of the task used by the Echo Sync demo APP_CFG _USBD_VENDOR_ECHO ASYNC_TASK PRIO Priority of the task used by the Echo Async demo APP_CFG USBD VENDOR_TASK STK SIZE Stack size of the tasks used by Echo Sync and Async demos
235. he information listed in Table 11 3 186 Configuration Offset Field Size bytes Description 0 aSignature 16 Constant used to verify preamble validity Always set to PhdcQoSSignature string 16 bNumTransfers 1 Count of following transfers to which QoS setting applies 17 bQoSEncodingVersion 1 QoS information encoding version Should be 0x01 18 bmLatencyReliability 1 Bitmap that refers to latency reliability bin for data 19 bOpaqueDataSize 1 Length in bytes of opaque data 20 bOpaqueData 0 Optional data usually application specific that is MaxPacketSize 21 opaque to the class 11 2 CONFIGURATION Table 11 3 Metadata Preamble 11 2 1 GENERAL CONFIGURATION Some constants are available to customize the class These constants are located in the usbd cfg h file Table 11 4 shows a description of each of them Constant Description USBD_PHDC_CFG MAX NBR_ DEV Configures the maximum number of class instances Unless you plan having multiple configuration or interfaces using different class instances this can be set to 1 USBD_PHDC_CFG MAX NBR_CFG high speed Configures the maximum number of configuration in which PHDC is used Keep in mind that if you use a high speed device two configurations will be built one for full speed and another for USBD_PHDC_CFG DATA OPAQUE MAX LEN Maximum length in octets that opaque data can be Must always be equ
236. he transfer completion with or without an error A timeout can be specified to avoid waiting forever Listing 12 2 presents a read and write example to receive data from the host using the bulk OUT endpoint and to send data to the host using the bulk IN endpoint CPU_INTO8U rx_buf 2 CPU_INTO8U tx buf 2 USBD_ERR err void USBD_Vendor_Rd class nbr 1 void amp rx_buf 0 2 2u 0u 3 amp err if err USBD_ERR_NONE Handle the error void USBD_Vendor Wr class nbr 1 void amp tx_buf 0 4 2u 0u 3 DEF_FALSE 5 amp err if err USBD_ERR NONE Handle the error Listing 12 2 Synchronous Bulk Read and Write Example L12 2 1 The class instance number created with USBD_Vendor_Add will serve internally to the Vendor class to route the transfer to the proper bulk OUT or IN endpoint L12 2 2 Application must ensure that the buffer provided to the function is large enough to accommodate all the data Otherwise synchronization issues might happen 112 23 In order to avoid an infinite blocking situation a timeout expressed in milliseconds can be specified A value of 0 makes the application task wait forever 211 Chapter 12 L12 2 4 Application provides the initialized transmit buffer 112 265 If this flag is set to DEF_TRUE and the transfer length is multiple of the endpoint maximum packet size the device stack will send a zero length packet to the
237. host to signal the end of transfer The use of interrupt endpoint communication functions USBD_Vendor_IntrRd and USBD_Vendor_IntrWr is similar to bulk endpoint communication functions presented in Listing 12 2 12 2 5 ASYNCHRONOUS COMMUNICATION Asynchronous communication means that the transfer is non blocking Upon function call the application passes the transfer information to the device stack and does not block Other application processing can be done while the transfer is in progress over the USB bus Once the transfer has completed a callback is called by the device stack to inform the application about the transfer completion Listing 12 3 shows an example of asynchronous read and write void App USBD Vendor Comm CPU_INTO8U class_nbr CPU_LINTO8U rx_buf 2 CPU_INTO8U tx buf 2 USBD_ERR err USBD_Vendor_RdAsync class_nbr 1 void amp rx_buf 0 2 2u App_USBD_Vendor_RxCmp1 3 void 0u 4 amp err if err USBD ERR NONE Handle the error ii USBD_Vendor_WrAsync class_nbr 1 void amp tx_buf 0 5 2u App_USBD_Vendor_TxCmp1 3 void 0u 4 DEF_FALSE 6 amp err 212 if err USBD ERR NONE Handle the error static void App USBD Vendor RxCmpl CPU_INTO8U void CPU_INT32U CPU_INT32U void USBD_ERR void class_nbr void p buf void buf_len void xfer_len void p_callback_arg if err USBD ERR NONE Do
238. hronization issues might happen Internally the read operation is done either with the control endpoint or with the interrupt endpoint depending on the control read flag set when calling USBD_HID_Add 153 Chapter 9 L9 4 3 The application provides a callback passed as a parameter Upon completion of the transfer the device stack calls this callback so that the application can finalize the transfer by analyzing the transfer result For instance upon read operation completion the application may do a certain processing with the received data Upon write completion the application may indicate if the write was successful and how many bytes were sent L9 4 4 An argument associated to the callback can be also passed Then in the callback context some private information can be retrieved L9 4 5 The application provides the initialized transmit buffer 9 4 USING THE DEMO APPLICATION Micrium provides a demo application that lets you test and evaluate the class implementation Source template files are provided for the device Executable and source files are provided for Windows host PC 9 4 1 CONFIGURING PC AND DEVICE APPLICATIONS The HID class provides two demos E Mouse demo exercises Input reports sent to the host Each report gives periodically the current state of a simulated mouse E Vendor specific demo exercises Input and Output reports The host sends an Output report or receives an Input report according to your choi
239. i didaa aa 54 CD 119 device driver lt TT HID class 142 host and CDC 119 host and HID class 142 host and Vendor class 206 MS class 169 RTOS interactions 2 0 2 eee eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee 239 Index aSignature asynchronous communication asynchronous read and write asynchronous receive asynchronous transmit eee eee eset eeeeeeeeeeeeeeeeeees B bmLatencyReliability bNumTransfers board support bOpaqueData bOpaqueDataSize bQoSEncodingVersion BSP interface API DUS TOP OlOGY E C callback interactions 111 requests mapping 113 structure 111 112 CDC architecture configuration configuration constants demo device endpoints functions initialization memory footprin serial demo subclasses CDC ACM configuration functions initialization class instance API functions communication communication HID class communication PHDC 192 communication Vendor class configuration HID class configuration MS class configuration PHDC configuration Vendor class control structure i 108 multiple structures class state machine ClassReq ClearCommFeature CLEAR_FEATURE complex composite high speed USB device configuration SUCTUS ipii aea a ance a E sued saad 75 540 composite high speed USB
240. ies Section Micripm classes section 3 1 1 About INF Files on page 46 CDC PHDC and Vendor section 3 1 2 Using GUIDs on page 51 HID PHDC and Vendor Table 3 1 Micrium Classes Concerned by Windows USB Device Management 3 1 1 ABOUT INF FILES An INF file is a setup information file that contains information used by Windows to install software and drivers for one or more devices The INF file also contains information to store in the registry Each of the drivers provided natively with the operating system has an associated INF file stored in C WINDOWS inf For instance when a HID or MSC device is connected to the PC Windows enumerates the device and implicitly finds an INF file associated to a HID or MSC class that permits loading the proper driver INF files for native drivers are called system INF files Any new INF files provided by manufacturers for vendor specific devices are copied into the folder C WINDOWS inf These INF files can be called vendor specific INF files An INF file allows Windows to load one or more drivers for a device A driver can be native or provided by the device manufacturer 46 Microsoft Windows Table 3 2 shows the Windows driver s loaded for each Micrium class Micripm class Windows driver Driver type INF file type CDC ACM usbser sys Native Vendor specific INF file HID Hidclass sys Native System INF file Hidusb sys MSC Usbstor sys Native System INF file PHDC w
241. igned to p err Otherwise USBD_ERR_NONE should be assigned to p_err 307 Appendix A A 5 8 USBD_OS EP _SignalPost Makes a signal semaphore available FILES usbd_internal h usbd_os c PROTOTYPE void USBD_OS_EP_SignalPost CPU_INTO8U dev_nbr CPU_LINTO8U ep ix USBD_ERR p err ARGUMENTS dev_nbr Device number ep_ix Endpoint index p err Pointer to variable that will receive the return error code from this function RETURNED VALUE None CALLERS Endpoints transfer complete functions IMPLEMENTATION GUIDELINES A call to this function should post the signal semaphore associated to the specified endpoint In case the post fail USBD_ERR_OS FAIL should be assigned to p err Otherwise USBD_ERR_NONE should be assigned to p_err 308 A 5 9 USBD_OS CoreEventPut Queues a core event FILES usbd_internal h usbd_os c PROTOTYPE void USBD_OS CoreEventPut void p event ARGUMENTS p_event Pointer to core event RETURNED VALUE None CALLERS Endpoints and bus event handlers IMPLEMENTATION GUIDELINES A call to this function should add the passed event to the core events queue 309 Appendix A A 5 10 USBD_OS CoreEventGet Wait until a core event is ready FILES usbd_internal h usbd_os c PROTOTYPE void USBD_OS CoreEventGet CPU_INT32U timeout_ms USBD_ERR p err ARGUMENTS timeout ms Timeout in milliseconds p err Pointer to variable that will rec
242. iguration communication configuration controller driver configuration driver configuration error codes functions set address States 00 structure and enumeration synchronous receive synchronous transmit device driver architecture BSP functions callbacks functions i functions 324 interface API model Disconn Q endpoint 17 CDC error codes functions Se HID class 136 information table information table configuration management layer MS class PHDC QoS mapping Vendor class enumeration EPDesc EPDescGetSize error codes configuration Se GE WEE E f l speedier a iiaae aie 21 G GetCommFeature GET_DESCRIPTOR D GECHNE CODING ek 132 GetLineCoding GET_PROTOCOL GET_REPORT GUID device interface class Micrium class H hardware abstraction layer HID class architecture communication communication API configuration configuration constants demo application endpoint functions initialization initialization API memory footprint OS functions OS layer API porting high speed host application IFDesc 2113 IFDescGetSize 113 IFReq 113 INF file 46 222 223 example 223 structure mstallatior verzieren inesi atiina arean aeaiiai interface c
243. ile is located in Micrium Software uC USB Device V4 App Host 0S Windows CDC INF Refer to section 3 1 1 About INF Files on page 46 for more details about how to edit the INF file to match your Vendor ID VID and Product ID PID The provided INF files define by default OxFFFE for VID and 0x1234 for PID Once the driver is loaded Windows creates a virtual COM port as shown in Figure 8 3 g Device Manager Lei BR File Action View Help e 9 0 E H ml el ees 4PC JE Computer Disk drives E Display adapters DVD CD ROM drives Ellisys protocol analyzers De Human Interface Devices a IDE ATA ATAPI controllers Imaging devices Keyboards D Mice and other pointing devices amp Monitors SE Network adapters KR Portable Devices Ports COM amp LPT F Micrium CDC Device COM14 YF USB Serial Port COM7 DI Processors Sound video and game controllers pM System devices Universal Serial Bus controllers Figure 8 3 Windows Device Manager and Created Virtual COM Port Figure 8 4 presents the steps to follow to use the serial demo 131 Chapter 8 F8 4 1 F8 4 2 F8 4 3 132 Figure 8 4 Serial Demo Open a serial terminal for instance HyperTerminal Open the COM port matching to your CDC ACM device with the serial settings baud rate stop bits parity and data bits you want This operation will send a series of CDC ACM class specific requests GET LINE C
244. informed when a new event is queued Figure 14 3 describes the core events management within the RTOS port Core layer RTOS port 1 Core event o Put core event f Core Events Queue Fi Core task a Get core event Figure 14 3 Core events management within RTOS port F14 3 1 A core event is added to the queue F14 3 2 The core task of the core layer pends on the queue Whenever an event is added the core task is resumed to process it 14 3 3 DEBUG EVENTS MANAGEMENT The core layer of yC USB Device offers an optional feature to do tracing and debugging For more information on this feature see Chapter 13 Debug and Trace on page 231 This feature requires an OS task For more information on the purpose of this task or on debug events refer to section 4 2 Task Model on page 58 The behavior of this task is similar to 241 Chapter 14 the core task described in Section 14 3 2 The difference is that the RTOS port does not need to manage the queue as it is handled within the core layer The RTOS port only needs to provide a signal that will inform of a debug event insertion 14 4 PORTING THE CORE LAYER TO A RTOS The core RTOS port is located in a separate file named usbd_os c A template file can be found in the following folder Micrium Software uC USB Device V4 0S Template Table 14 3 summarizes all the functions that need to be implemented in the RTOS port file For more information
245. interface 2 or interface 3 L7 4 6 Add the same class instances class_0 and class_1 to the other configuration cfg_1 107 Chapter 7 You can refer to section 5 4 Configuration Examples on page 71 for some configuration examples showing multiple class instances applied to composite devices Composite devices uses at least two different classes provided by the pC USB Device stack The section 5 4 2 Composite High Speed USB device on page 73 gives a concrete example based on Figure 7 2 See section 5 4 3 Complex Composite High Speed USB device on page 74 for a hybrid example that corresponds to Figure 7 2 and Figure 7 3 7 2 CLASS INSTANCE STRUCTURES When a class instance is created a control structure is allocated and associated to a specific class instance The class uses this control structure for its internal operations All the Micrium USB classes define a class control structure data type Listing 7 5 shows the structure declaration with the common fields struct usbd_xxxx_ctrl CPU_INTO8U DevNbr 1 CPU_INTO8U ClassNbr 2 USBD_XXXX_STATE State 3 USBD_XXXX_COMM CommPtr 4 5 Listing 7 5 Class Instance Control Structure L7 5 The device number to which the class instance is associated with L7 5 2 The class instance number L7 5 The class instance state L7 5 4 A pointer to a class instance communication structure This structure holds information regarding the interface s e
246. ints USBD_CFG MAX NBR_EP_ OPEN 4or6 Two control endpoints for device s standard requests Two bulk endpoints and two optional interrupt endpoints USBD_VENDOR_CFG MAX NBR_DEV Only one instance of vendor class is needed USBD_VENDOR_CFG MAX NBR_CFG 72 Vendor class instance will only be used in one configuration Table 5 1 Configuration Example of a Simple Full Speed USB Device Configuration Examples 5 4 2 COMPOSITE HIGH SPEED USB DEVICE Table 5 2 shows the values that should be set for the different configuration constants described earlier if you build a composite high speed USB device using Micrium s PHDC and MSC classes The structure of this device is described in Figure 5 1 ha S x ri Full speed EN A ETE T USB device A a High speed confi SS ee a High speed AN guration P endpoint Sea e p endpoint d endpoint j PHDC instance BW lt PHDC mse interface q interface Wees d Wise Bulk IN H Bulk OUT TY Ainterrupt IN Bulk IN N Etat ae SS A i KEE oint endpoint poy Ly pon p WW MSC instance Endpoint is optional Figure 5 1 Composite High Speed USB Device Structure 13 Chapter 5 Configuration Value Explanation USBD_CFG MAX NBR_CFG 2 One configuration for full low speed and another for high speed USBD_CFG MAX NBR_IF 4 One interface for PHDC and
247. inusb sys for getting Native Vendor specific INF file started purpose only Vendor winusb sys Native Vendor specific INF file Table 3 2 Windows Drivers Loaded for each Micripm Class When a device is first connected Windows searches for a match between the information contained in system INF files and the information retrieved from device descriptors If there is no match Windows asks you to provide an INF file for the connected device An INF file is arranged in sections whose names are surrounded by square brackets Each section contains one or several entries If the entry has a predefined keyword such as Class Signature etc the entry is called a directive Listing 3 1 presents an example of an INF file structure Version Signature Class ClassGuid Version section SWindows NT Ports 4D36E978 E325 11CE BFC1 08002BE10318 Provider ProviderName DriverVer 01 01 2012 1 0 0 0 5 Manufacturer Models sections Manufacturer ProviderName3 DeviceList NTx86 NTamd64 DeviceList SPROVIDER_CDC DriverInstall USB VID_fffe amp PID_1234 amp MI_00 NTx86 1 2 3 47 Chapter 3 DeviceList NTamd64 3 SPROVIDER_CDC DriverInstall USB VID_fffe amp PID_1234 amp MI_00 S Installation sections 4 DriverInstall include mdmcpq inf CopyFiles FakeModemCopyFileSection AddReg LowerFilterAddReg SerialPr
248. invoking the proper status notification API In general the device driver interrupt handler must perform the following functions 1 84 Determine which type of interrupt event occurred by reading an interrupt status register If a receive event has occurred the driver must post the successful completion or the error status to the USB device stack by calling USBD_EP RxCmpl for each transfer received If a transmit complete event has occurred the driver must post the successful completion or the error status to the USB device stack by calling USBD_EP_TxCmp1 for each transfer transmitted If a setup packet event has occurred the driver must post the setup packet data in little endian format to the USB device stack by calling USBD_EventSetup All other events must be posted to the USB device stack by a call to their corresponding status notification API from Table 1 This allows the USB device stack to broadcast these event notifications to the classes Clear local interrupt flags Device Configuration 6 5 DEVICE CONFIGURATION The USB device characteristics must be shared with the USB device stack through configuration parameters All of these parameters are provided through two global structures of type USBD_DRV_CFG and USBD_DEV_CFG These structures are declared in the file usbd_dev_cfg h and defined in the file usbd_dev_cfg c refer to section 2 4 2 Copying and Modifying Template Files on page 33 for an exam
249. ion USBD_ACM SerialRx Receives data from host through a bulk OUT endpoint This function is blocking USBD_ACM SerialTx Sends data to host through a bulk IN endpoint This function is blocking Table 8 8 CDC ACM Communication API Summary USBD_ACM SerialRx and USBD_ACM SerialTx provide synchronous communication which means that the transfer is blocking Upon calling the function the application blocks until transfer completion with or without an error A timeout can be specified to avoid waiting forever Listing 8 3 presents a read and write example to receive data from the host using the bulk OUT endpoint and to send data to the host using the bulk IN endpoint CPU_INTO8U rx_buf 2 CPU_INTO8U tx buf 2 USBD_ERR err void USBD_ACM SerialRx subclass_nbr 21 amp rx_buf 0 2 2u Ou 3 amp err if err USBD_ERR NONE Handle the error void USBD_ACM SerialTx subclass_nbr 1 amp tx_buf 0 4 2u 0u 3 amp err if err USBD_ERR NONE Handle the error Listing 8 3 Serial Read and Write Example 128 L8 3 1 L8 3 2 L8 3 3 L8 3 4 ACM Subclass The class instance number created with USBD_ACM SerialAdd will serve internally to the ACM subclass to route the transfer to the proper bulk OUT or IN endpoint The application must ensure that the buffer provided to the function is large enough to accommodate all the data Otherwise synchronization issues might happe
250. ion and controlling the device s operation and transferring blocks of data in the storage media SCSI commands cover a vast range of device types and functions and as such devices need a subset of these commands In general the following commands are necessary for basic communication m INQUIRY E READ CAPACITY 10 E READ 10 E REQUEST SENSE E TEST UNIT READY E WRITE O Refer to Table 10 3 to see the full list of implemented SCSI commands by pC USB Device 168 Architecture 10 2 ARCHITECTURE 10 2 1 MSC ARCHITECTURE Figure 10 2 shows the general architecture of a USB Host and a USB MSC Device USB Host Mass Storage and SCSI Drivers Host Stack Control 0 Bulk Ine IN and OUT Bulk OUT Endpoint Endpoint Endpoint Mass Storage Class SCSI Layer Storage Layer Storage Medium USB Device Figure 10 2 MSC Architecture On the host side the application communicates with the MSC device by interacting with the native mass storage drivers and SCSI drivers In compliance with the BOT specification the host utilizes the default control endpoint to enumerate the device and the Bulk IN OUT endpoints to communicate with the device 169 Chapter 10 10 2 2 SCSI COMMANDS The host sends SCSI commands to the device via the Command Descriptor Block CDB These commands set specific requests for transfer of
251. ion class instance is connected FILES usbd_acm_serial h usbd_acm_serial c PROTOTYPE CPU_BOOLEAN USBD_ACM SerialIsConn CPU_INTO8U subclass_nbr ARGUMENTS subclass nbr CDC ACM serial emulation subclass instance number RETURNED VALUE DEF_OK If CDC ACM serial emulation subclass instance is connected and device is not in suspended state DEF FAIL otherwise CALLERS Application NOTES WARNINGS None 373 Appendix C C 2 5 USBD_ACM SerialRx Receive data on CDC ACM serial emulation subclass FILES usbd_acm_serial h usbd_acm_serial c PROTOTYPE CPU_INT32U USBD ACM SerialRx CPU_INTO8U subclass_nbr CPU_INTO8U p buf CPU_INT32U buf len CPU_INT16U timeout USBD_ERR whey err ARGUMENTS subclass_nbr Pointer to USB device driver structure p buf Pointer to destination buffer to receive data buf len Number of octets to receive timeout me Timeout in milliseconds p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_INVALID ARG USBD_ERR_ INVALID CLASS STATE USBD_ERR_EP INVALID ADDR USBD_ERR_EP INVALID STATE USBD_ERR_EP INVALID TYPE USBD_ERR_OS TIMEOUT USBD_ERR_OS ABORT USBD_ERR_OS FAIL 374 RETURNED VALUE None CALLERS Numbers of octets received if NO error s 0 otherwise NOTES WARNINGS None 375 Appendix C C 2 6 USBD_ACM SerialTx Send data on CDC ACM serial emulation subclass FILES
252. ion for Human Interface Devices HID Version 1 11 sections 5 3 and 6 2 2 2 for more details about short items format This table content corresponds to the mouse Report descriptor content viewed by a host HID parser in Figure 9 1 L9 2 2 The Generic Desktop Usage Page is used 148 L9 2 3 L9 2 4 L9 2 5 L9 2 6 L9 2 7 L9 2 8 L9 2 9 L9 2 10 L9 2 11 Configuration Within the Generic Desktop Usage Page the usage tag suggests that the group of controls is for controlling a mouse A mouse collection typically consists of two axes X and Y and one two or three buttons The mouse collection is started Within the mouse collection a usage tag suggests more specifically that the mouse controls belong to the pointer collection A pointer collection is a collection of axes that generates a value to direct indicate or point user intentions to an application The pointer collection is started The Buttons Usage Page defines an Input item composed of three 1 bit fields Each 1 bit field represents the mouse s button 1 2 and 3 respectively and can return a value of 0 or 1 The Input Item for the Buttons Usage Page is padded with 13 other bits Another Generic Desktop Usage Page is indicated for describing the mouse position with the axes X and Y The Input item is composed of two 8 bit fields whose value can be between 127 and 127 The pointer collection is closed The mouse collection is closed 14
253. ion functions consult the uC LIB documentation 6 7 CPU AND BOARD SUPPORT The USB device stack supports big endian and little endian CPU architectures The setup packet received as part of a control transfer must provide the content of the setup packet in little endian format to the stack Therefore if the USB device controller provides the content in big endian format device drivers must swap the endianness of the setup packet s content In order for device drivers to be platform independent it is necessary to provide a layer of code that abstracts details such as clocks interrupt controllers general purpose input output GPIO pins and other hardware modules configuration With this board support package BSP code layer it is possible for the majority of the USB device stack to be independent of any specific hardware and for device drivers to be reused on different architectures and bus configurations without the need to modify stack or driver source code These procedures are also referred as the USB BSP for a particular development board A sample device BSP interface API structure is shown below const USBD DRV BSP API USBD DrvBSP_ lt controller gt USBD BSP Init 1 USBD_BSP_Conn 2 USBD_BSP_Disconn 3 Listing 6 7 Device BSP Interface API 88 USB Device Driver Functional Model L6 7 1 Device BSP initialization function pointer L6 7 2 Device BSP connect function pointer L6 7 3 Device BSP disconnect fun
254. it callback end End of transfer flag p_err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_ NULL PTR USBD_ERR_INVALID ARG USBD_ERR_ INVALID CLASS STATE 495 Appendix G USBD_ERR_ DEV INVALID NBR USBD_ERR_EP INVALID NBR USBD_ERR_ DEV INVALID STATE USBD_ERR_EP INVALID TYPE USBD_ERR_EP INVALID STATE RETURNED VALUE Number of octets sent if NO error s 0 otherwise CALLERS Application NOTES WARNINGS If end of transfer flag is set and transfer length is multiple of maximum packet size a zero length packet is transferred to indicate the end of transfer to the host 496 G 2 USBDEV_ API FUNCTIONS USBDev_APTI is a library implemented under Windows operating system Functions return values and parameters use Windows data types such as DWORD HANDLE ULONG Refer to MSDN online documentation for more details about Windows data types http msdn microsoft com en us library aa383751 v VS 85 aspx G 2 1 USBDev_GetNbrDev Get number of devices belonging to the specified GUID FILES usbdev_api c PROTOTYPE DWORD USBDev_GetNbrDev const GUID guid_dev_if DWORD p err ARGUMENTS guid dev_if Device interface class GUID p err Pointer to variable that will receive the return error code from this function ERROR_SUCCESS RETURNED VALUE Number of devices for the provided GUID if NO error s 0 otherwise 497 Appendix G CA
255. ite inf can be modified as shown in Listing 12 7 Let s assume a device with two vendor interfaces MyDevice_WinUSB NTx86 USB MyDevice DeviceDesc USB_Install USB VID_FFFE amp PID_1001 amp MI_00 SUSB MyDevice DeviceDesc USB_Install USB VID_FFFE amp PID_1001 amp MI_01 MyDevice_WinUSB NTamd 4 USB MyDevice DeviceDesc USB_Install USB VID_FFFE amp PID_1001 amp MI_00 SUSB MyDevice DeviceDesc USB_Install USB VID_FFFE amp PID_1001 amp MI_01 MyDevice_WinUSB NTia64 USB MyDevice DeviceDesc USB_Install USB VID_FFFE amp PID_1001 amp MI_00 SUSB MyDevice DeviceDesc USB_Install USB VID_FFFE amp PID_1001 amp MI_01 Listing 12 7 INF File Example for Composite Device Formed of Several Vendor Interfaces You can also modify the Strings section of the INF file in order to add the strings that best describe your device Listing 12 8 shows the editable Strings section common to WinUSB_single inf and WinUSB_composite inf Strings ProviderName Micrium 1 USB MyDevice DeviceDesc Micrium Vendor Specific Device 2 ClassName USB Sample Class 3 Listing 12 8 Editable Strings in the INF File to Describe the Vendor Device 112 801 Specify the name of your company as the driver provider L12 8 2 Write the name of your device 223 Chapter 12 112 8 You can modify this string to give a new name to the device group in which your device will appear under Device Manager In this example Micriu
256. ket size a zero length packet is transferred to indicate a short transfer to the host 286 A 4 13 USBD_EP_RxZLP Receives zero length packet from the host FILES usbd_core h usbd_ep c PROTOTYPE void USBD_EP_RxZLP CPU_INTO8U dev_nbr CPU_INTO8U ep addr CPU_INT16U timeout ms USBD_ERR p err ARGUMENTS dev_nbr Pointer to USB device driver structure ep addr Pointer to buffer of data that will be transmitted timeout_ms Timeout in milliseconds p err Pointer to variable that will receive the return error code from this function USBD_ERR_OS_NONE USBD_ERR DEV INVALID NBR USBD_ERR_ EP INVALID ADDR USBD_ERR_ EP INVALID STATE USBD_ERR_OS TIMEOUT USBD_ERR_OS ABORT USBD_ERR_OS FAIL RETURNED VALUE None 287 Appendix A CALLERS USBD_Ctr1Rx USBD_Ctr1RxStatus USB device class drivers NOTES WARNINGS None 288 A 4 14 USBD_EP_TxZLP Sends zero length packet from the host FILES usbd_core h usbd_ep c PROTOTYPE void USBD_EP_RxZLP CPU_INTO8U dev_nbr CPU_INTO8U ep addr CPU_INT16U timeout ms USBD_ERR p err ARGUMENTS dev_nbr Pointer to USB device driver structure ep addr Pointer to buffer of data that will be transmitted timeout_ms Timeout in milliseconds p err Pointer to variable that will receive the return error code from this function USBD_ERR_OS_NONE USBD_ERR_DEV_INVALID NBR USBD_ERR_ EP INVALID ADDR USBD_ERR_EP INVALID STATE USBD_ERR_OS TIMEOUT U
257. l The code presented in Listing 9 2 is an example of code implementation corresponding to this mouse Report descriptor representation E 2 Collection Usage e Application Mouse AA 3 Collection Usage Physical Pointer Y Y la Y wA Input Report Input Report Input Report Usage X data constant data a Usage Y Usage Min Report Logical Min SR button 1 Count 1 127 Usage Max Report Size Logical Max button 3 13 127 Logical Min Report 0 Count 2 Logical Max Report Size 1 8 Report Count 3 Report Size 1 Ces 4 Usage Page Button G 5 Usage Page Generic Desktop_ A 1 Usage Page Generic Desktop SE Figure 9 1 Report Descriptor Content from a Host HID Parser View 139 Chapter 9 F9 1 1 F9 1 2 F9 1 3 F9 1 4 F9 1 5 140 The Usage Page item function specifies the general function of the device In this example the HID device belongs to a generic desktop control The Collection Application groups Main items that have a common purpose and may be familiar to applications In the diagram the group is composed of three Input Main items For this collection the suggested use for the controls is a mouse as indicated by the Usage item Nested collections may be used to give more details about the use of a single control or group of controls to application
258. lications do not benefit from a RTOS port Hence if you plan to use them with another RTOS than pC OS II or pC OS II you will have to modify them Figure 14 1 summarizes the interactions between the different pC USB Device modules and the RTOS t k Your Application eee kv MSC Port vi l I 4 HID Pont v I I D D au d RTOS CDC 14 PHDC Port vr PHDC HID MSC Vendor acm Class layer l I I I l l i Core Port H Device Core Layer l I RTOS Abstraction Device Controller Driver Layer NE oe Soe ed Software Device Controller Hardware Figure 14 1 pC USB Device architecture with RTOS interactions 14 2 PORTING MODULES TO A RTOS Table 14 2 lists the section of this manual to which you should refer to for an explanation on how to port pC USB Device modules to a RTOS Module Refer to Core layer Section 14 4 Porting The Core Layer to a RTOS on page 242 PHDC Section 11 6 Porting PHDC to a RTOS on page 203 HID Section 9 5 Porting the HID Class to a RTOS on page 160 MSC Section 10 6 Porting MSC to a Storage Layer on page 180 Table 14 2 List of sections to refer to port a module to a RTOS 239 Chapter 14 14 3 CORE LAYER RTOS MODEL The core layer of wC USB Device needs an RTOS for three purposes E Signal the completion of synchronous
259. ller gt BSP lt board name gt L2 3 2 Initialize the USB device stack s internal variables structures and core RTOS port L2 3 3 Specify the address of the device configuration structure that you modified in the section Modify Device Configuration on page 34 36 L2 3 4 12 365 12 3 6 L2 3 7 Building the Sample Application Specify the address of the driver API structure The driver s API structure is defined in the driver s header file named usbd_drv_ lt controller gt h Specify the address of the driver configuration structure that you modified in the section Modify Driver Configuration on page 35 Specify the endpoint information table The endpoint information table should be defined in your USB device controller BSP files If the device controller supports high speed create a high speed configuration for the specified device 2 4 3 INCLUDING USB DEVICE STACK SOURCE CODE First include the following files in your project from the pC USB Device source code distribution as indicated in Figure 2 3 jy uC USB Device V4 A Class Al lt class gt D usbd_ lt class gt c Wl lt controller gt usbd_drv_ lt controller gt c lt board name gt ane os E usbd_bsp lt controller gt c l y lt RTOS gt 7 usbd_os c S usbd_os c K usbd_ep c KE usbd_core c Figure 2 3 puC USB Device Source Code 37 Chapter 2 Second add the following incl
260. ls about this function 163 Chapter 9 164 Chapter 10 Mass Storage Class This section describes the mass storage device class MSC supported by uC USB Device The MSC implementation offered by uC USB Device is in compliance with the following specifications E Universal Serial Bus Mass Storage Class Specification Overview Revision 1 3 Sept 5 2008 E Universal Serial Bus Mass Storage Class Bulk Only Transport Revision 1 0 Sept 31 1999 MSC is a protocol that enables the transfer of information between a USB device and a host The information is anything that can be stored electronically executable programs source code documents images configuration data or other text or numeric data The USB device appears as an external storage medium to the host enabling the transfer of files via drag and drop A file system defines how the files are organized in the storage media The USB mass storage class specification does not require any particular file system to be used on conforming devices Instead it provides a simple interface to read and write sectors of data using the Small Computer System Interface SCSI transparent command set As such operating systems may treat the USB drive like a hard drive and can format it with any file system they like The USB mass storage device class supports two transport protocols P Bulk Only Transport BOT E Control Bulk Interrupt CBD Transport The mass storage device clas
261. m Vendor Specific Device will appear under the USB Sample Class group Refer to Figure 3 1 Windows Device Manager Example for a CDC Device on page 50 for an illustration of the strings use by Windows 12 4 3 RUNNING THE DEMO APPLICATION Figure 12 3 presents the Echo demo with host and device interactions Windows PC USB Device Host 2 Sync task 1 Rx header 2 Rx payload 3 Tx payload 1 Main thread Header Rx header callback gt 3 Async task 2 Rx payload preparation 7 Payload v 1 Rx header gt ail Rx payload callback 1 Tx header 2 Tx payload 3 Rx payload preparation 3 Tx payload preparation Payload y Tx payload callback gt 1 Rx header preparation OR 2 Rx payload preparation Figure 12 3 Echo Demo F12 3 1 The Windows application executes a simple protocol consisting of sending a header indicating the total payload size sending the data payload to the device and receiving the same data payload from the device The entire transfer for data payload is split into small chunks of write and read operations of 512 bytes The write operation is done using a bulk OUT endpoint and the read uses a bulk IN endpoint 224 F12 3 2 F12 3 3 Using the Demo Application On the device side the Echo Sync uses a task that complements the Windows application execution Each step is done synchro
262. m directory count 1 APP_CFG FS _BUF_CNT File system buffer count 2 APP_CFG FS VOL CNT APP_CFG FS _DEV_DRV_CNT File system device driver count 1 APP_CFG FS WORKING DIR CNT File system working directory count 0 APP_CFG FS MAX SEC SIZE File system max sector size 512 APP_CFG FS RAM NBR_SEC File system number of RAM sectors 8192 APP_CFG FS RAM SEC SIZE File system RAM sector size 512 APP_CFG FS _NBR_TEST File system number of tests 10 APP C FG FS IDE EN Enables IDE device in file system DEF_DISABLED APP_CFG FS MSC_EN Enables MSC device in file system DEF_DISABLED APP_CFG FS WOR EN Enables NOR device in file system DEF_DISABLED APP_CFG FS RAN EN Enables RAM device in file system DEF_ENABLED APP_CFG FS SD EN Enables SD device in file system DEF_DISABLED APP_CFG FS_SD CARD EN Enables SD card device in file system DEF_ENABLED 178 Table 10 9 uC FS Preprocessor Constants Using the Demo Application 10 5 2 USB HOST APPLICATION To test the pC USB Device stack with MSC the user can use the Windows Explorer as a USB Host application When the device configured for the MSC demo is connected to the PC Windows loads the appropriate drivers as shown in Figure 10 4 fs Installing device driver software Click here for status Figure 10 4 MSC Device Driver Detection on Windows Host Open a Windows Explorer and a removable disk appears as shown in Figure 10 5
263. mList QoS Pend on scheduler release semaphore Listing 11 6 Pseudocode of QoS Based Scheduler s Task 199 Chapter 11 11 5 USING THE DEMO APPLICATION Micrium provides a demo application that lets you test and evaluate the class implementation Source files are provided for the device for pC OS II and pC OS HI only Executable and source files are provided for the host Windows only 11 5 1 SETUP THE APPLICATION On the target side two applications are available app _usbd_phdc_single c and app_usbd phdc multiple c You should compile only one of these files with your project Table 11 12 provide a description of each one Both files are located in the following folders Micrium Software uC USB Device V4 App Device 0S uCOS II Micrium Software uC USB Device V4 App Device 0S uCOS III File Description app_usbd_phdc_single c Only one task is used to send all data of different QoS Usually used with USBD_PHDC_OS CFG SCHED EN set to DEF_DISABLED app usbd phde multiple c One task per QoS level is used to send data Usually used with USBD_PHDC_OS CFG SCHED EN set to DEF_ENABLED Table 11 12 Device Demo Application Files Several constants are available to customize the demo application on both device and host Windows side Table 11 13 describe device side constants that are located in the app_cfg h file Table 11 14 describe host side constants that are located in the app_phdc c file Constant Descrip
264. mber as follows lt device_driver_name gt lt logical_unit_number gt The logical unit number starts counting from number 0 For example if a device has only one logical unit the lt ogical_unit_number gt specified in this field should be 0 Listing 10 1 shows how the latter functions are called during MSC initialization USBD_ERR err CPU_INT0O8U msc_nbr CPU_BOOLEAN valid USBD_MSC_Init amp err if err USBD_ERR_NONE return DEF_FAIL msc_nbr USBD_MSC_Add amp err if cfg_hs USBD_CFG_NBR_NONE valid USBD_MSC_CfgAdd msc_nbr dev_nbr cfg_hs amp err if valid DEF YES return DEF FAIL if cfg_fs USBD_CFG _NBR_NONE valid USBD_MSC_CfgAdd msc_nbr dev_nbr cfg fs amp err if valid DEF_YES return DEF_FAIL 1 2 3 4 175 Chapter 10 USBD_MSC_LunAdd void ram 0 5 msc_nbr Micrium MSC RamDisk 0x0000 DEF_FALSE amp err if err USBD_ERR_NONE return DEF FAIL return DEF_OK L10 1 1 L10 1 2 L10 168 L10 1 4 L10 1 65 Listing 10 1 MSC Initialization Initialize internal structures and variables used by MSC BOT Add a new instance of the MSC Check if high speed configuration is active and proceed to add an existing MSC interface to the USB configuration Check if full speed configuration is active and proceed to add an existing MSC interface to the USB configuration
265. mmunicate with a driver assigned to devices in a class Refer to section 3 1 2 Using GUIDs on page 51 for more details about the GUID 228 Using the Demo Application Device setup class GUID is used in WinUSB_single inf and WinUSB_composite inf located in Micrium Software uC USB Device V4 App Host 0S Windows Vendor INF These INF files define a new device setup class that will be added in the Windows registry under HKEY LOCAL MACHINE System CurrentControlSet Control Class upon first connection of a vendor device The following entries in the INF file define the new device setup class Class MyDeviceClass Name of the device setup class ClassGuid 11111111 2222 3333 4444 555555555555 Device setup class GUID The INF files allows Windows to register in the registry base all the information necessary to associate the driver Winusb sys with the connected vendor device The Windows Echo application is able to retrieve the attached vendor device thanks to the device interface class GUID WinUSB_single inf and WinUSB_composite inf define the following device interface class GUID 143 20bd 7bd2 4ca6 9465 8882 2156bd6 The Echo application includes a header file called usbdev_guid h This header file defines the following variable GUID USBDev_GUID 0x143f 20bd 0x7bd2 0x4ca6 0x94 0x65 0x88 0x82 0xf2 0x15 0x6b 0xd6 USBDev_GUID is a structure whose fields represent the device interface class GUID defined in WinUSB_single inf
266. mple Application een 31 Understanding Micrium Examples cccceeeceeeeeeeeeeeeeeeneeeeeeeeenes 31 Copying and Modifying Template Files ee 33 Including USB Device Stack Source Code Auen 37 Modifying Application Configuration File REENEN 38 Running the Sample Application een 40 Table of Contents Chapter 3 3 1 3 1 1 3 1 2 Chapter 4 4 1 4 1 1 4 1 2 4 1 3 4 1 4 4 1 5 4 1 6 4 1 7 4 1 8 4 2 4 2 1 4 2 2 4 2 3 Chapter 5 5 1 5 1 1 5 1 2 5 1 3 5 1 4 5 1 5 5 1 6 5 1 7 5 1 8 5 1 9 5 1 10 5 1 11 5 2 5 2 1 5 2 2 5 3 5 4 4 Host Operating Systems ccccccceeseeeeeeeeeneeeeeeeeeeeeeeeeeeeeeeeeaeeeeeeseeneeeenens 45 Microsoft lee EE 46 AboutiINF Bile wescvccciivecestetucideseevevers heeites aaau aeaa aana iaaa Siaa 46 Ee KC UR 51 Architecture es geess ege ASSEN EG 53 Modules Relationship een 55 ee e EE 55 olre Un lE octet Bole A E tan Peastctacatcte veda A E AE 55 USB Class Layer eiaa AAE EN EAEN ea 56 WSB Core Loyer aeaa an raara ra AAAA DEPA EAA OANEI EAn ANE EE AN AEETI A 56 Endpoint Management Layer cescesssesseeeeeeceeeeeeeeeseeeeeeseeaneeeeeeeeeees 56 Real Time Operating System RTOS Abstraction Layer e 57 Hardware Abstraction Layer ceseecceseseeeeeeeeeeeeeeeeeneeeeeseeeesneeeeeneeeeeeees 57 EE EE 58 Task MOGI ebe 58 Sending and Receiving Data ccccceessenceeeeeseeeeeeeeeeeeeeeeeseeeeeeeeeneeeeeeens 59 Processing USB Requests and Bus Events c sssse
267. mum Defines the starting usage associated with an array or bitmap Usage Maximum Defines the ending usage associated with an array or bitmap Designator Index Determines the body part used for a control Index points to a designator in the Physical descriptor Designator Minimum Defines the index of the starting designator associated with an array or bitmap Designator Maximum Defines the index of the ending designator associated with an array or bitmap String Index String index for a String descriptor It allows a string to be associated with a particular item or control String Minimum Specifies the first string index when assigning a group of sequential strings to controls in an array or bitmap String Maximum Specifies the last string index when assigning a group of sequential strings to controls in an array or bitmap Delimiter Defines the beginning or end of a set of local items Table 9 2 Item s Function Description for each Item Type Overview A control s data must define at least the following items E Input Output or Feature Main items E Usage Local item E Usage Page Global item E Logical Minimum Global item E Logical Maximum Global item P Report Size Global item P Report Count Global item Table 9 1 shows the representation of a Mouse Report descriptor content from a host HID parser perspective The mouse has three buttons left right and whee
268. munications Subclass for PSTN Devices revision 1 2 February 9 2007 section 6 2 2 From this list Micrium s ACM subclass supports 121 Chapter 8 Subclass request Description SetCommFeature The host sends this request to control the settings for a particular communications feature Not used for serial emulation GetCommFeature The host sends this request to get the current settings for a particular communications feature Not used for serial emulation ClearCommFeature The host sends this request to clear the settings for a particular communications feature Not used for serial emulation SetLineCoding The host sends this request to configure the ACM device settings in terms of baud rate number of stop bits parity type and number of data bits For a serial emulation this request is sent automatically by a serial terminal each time you configure the serial settings for an open virtual COM port GetLineCoding The host sends this request to get the current ACM settings baud rate stop bits parity data bits For a serial emulation serial terminals send this request automatically during virtual COM port opening SetControlLineState The host sends this request to control the carrier for half duplex modems and indicate that Data Terminal Equipment DTE is ready or not In the serial emulation case the DTE is a serial terminal For a serial emulation certain serial terminals allow you to send this requ
269. n In order to avoid an infinite blocking situation a timeout expressed in milliseconds can be specified A value of 0 makes the application task wait forever The application provides the initialized transmit buffer 8 4 6 USING THE DEMO APPLICATION Micrium provides a demo application that lets you test and evaluate the class implementation Source template files are provided for the device CONFIGURING DEVICE APPLICATION The serial demo allows you to send and or receive serial data to and or from the device through a virtual COM port The demo is implemented in the application file app_usbd_cdc c provided for pC OS II and pC OS III app_usbd_cde c is located in these two folders E Micrium Software uC USB Device V4 App Device 0S uCcOS II E Micrium Software uC USB Device V4 App Device 0S uCOS III 129 Chapter 8 Table 8 9 describes the constants usually defined in app_cfg h which allows you to use the serial demo Constant Description APP_CFG USBD_CDC_EN General constant to enable the CDC ACM demo application Must be set to DEF_ENABLED APP_CFG USBD CDC SERIAL TEST EN Constant to enable the serial demo Must be set to DEF_ENABLED APP CFG USBD CDC _ SERIAL TASK PRIO Priority of the task used by the serial demo APP_CFG USBD CDC SERIAL TASK STK SIZE Stack size of the task used by the serial demo A default value can be 256 Table 8 9 Device Application Configuration Co
270. n error code from this function USBD_ERR_NONE USBD_ERR_ NULL PTR USBD_ERR_INVALID ARG USBD_ERR_ INVALID CLASS STATE 487 Appendix G USBD_ERR_ DEV INVALID NBR USBD_ERR_EP INVALID NBR USBD_ERR_ DEV INVALID STATE USBD_ERR_EP INVALID TYPE USBD_ERR_EP INVALID STATE RETURNED VALUE Number of octets sent if NO error s 0 otherwise CALLERS Application NOTES WARNINGS If end of transfer flag is set and transfer length is multiple of maximum packet size a zero length packet is transferred to indicate the end of transfer to the host 488 G 1 9 USBD Vendor _IntrRd Receive data from host through Interrupt OUT endpoint This function is blocking FILES usbd_vendor c PROTOTYPE CPU_INT32U USBD_Vendor_IntrRd CPU_INTO8U class_nbr void p buf CPU_INT32U buf len CPU_INT16U timeout USBD_ERR rP Err ARGUMENTS class_nbr p_ but buf_len timeout p err Class instance number Pointer to receive buffer Receive buffer length in octets Timeout in milliseconds Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_NULL PTR USBD_ERR_INVALID ARG USBD_ERR_ INVALID CLASS STATE USBD_ERR_ DEV INVALID NBR USBD_ERR_ EP INVALID NBR USBD_ERR DEV INVALID STATE USBD_ERR_EP INVALID TYPE 489 Appendix G RETURNED VALUE Number of octets received if NO error s 0 otherwise CALLERS Application NOTES WARNINGS
271. nction can be described by one interface or by a group of interfaces and belongs to a certain class Each USB class implementation has some configuration and functions in common based on the concept of class instance The common configuration and functions are presented in Table 7 1 In the column heading Constants or Function XXXX below can be replaced by the name of the class CDC HID MSC PHDC or VENDOR Vendor for function names Constant or function Description USBD_XXXX_ CFG MAX NBR DEV Configures the maximum number of class instances USBD_XXXX_CFG MAX NBR CFG Configures the maximum number of configurations per device During the class initialization a created class instance will be added to one or more configurations USBD_XXXX_Add Creates a new class instance USBD_XXXX_CfgAdd_ Adds an existing class instance to the specified device configuration Table 7 1 Constants and Functions Related to the Concept of Multiple Class Instances In terms of code implementation the class will declare a local global table that contains a class control structure The size of the table is determined by the constant USBD_XXXX_CFG MAX NBR DEV This class control structure is associated with one class 99 Chapter 7 instance and will contain certain information to manage the class instance See section 7 2 Class Instance Structures on page 108 for more details about this class control structure The f
272. nd USBD_PHDC Add but before USBD_PHDC_CfgAdd 449 Appendix F F 1 6 USBD_PHDC_ WrCfg Initialize write communication pipe parameters FILES usbd_phdc h usbd_phdc c PROTOTYPE void USBD_PHDC WrCfg CPU_INTO8U class nr LATENCY RELY FLAGS latency rely CPU_INTO8U p data_opaque CPU_INTO8U data_opaque_len USBD_ERR EES ARGUMENTS class_nbr PHDC instance number latency_rely p_data_opaque data_opaque_len 450 Bitmap of transfer Latency reliability that this communication pipe will carry Can be one or more of these values USBD_PHDC_ LATENCY VERYHIGH RELY BEST USBD_PHDC_ LATENCY HIGH RELY BEST USBD_PHDC_ LATENCY MEDIUM RELY BEST USBD_PHDC_ LATENCY MEDIUM RELY BETTER USBD_PHDC_ LATENCY MEDIUM RELY GOOD USBD_PHDC_ LATENCY LOW RELY GOOD Pointer to a buffer that contains opaque data related to this communication pipe Length of opaque data On octets If 0 no metadata descriptor will be written for the endpoint err Pointer to variable that will receive the return error code from this p function USBD_ERR_NONE USBD_ERR NULL PTR USBD_ERR_INVALID ARG RETURNED VALUE None CALLERS Application NOTES WARNINGS USBD_PHDC WrCfg should be called after USBD_PHDC_Init and USBD_PHDC Add but before USBD_PHDC_CfgAdd Since low latency transfers will use a different endpoint it is possible to set different opaque data for that endpoint In case the application need different opaque
273. ndpoints used for data communication Listing 7 6 presents the communication structure L7 5G Class specific fields 108 Class Instance Structures During the communication phase the class communication structure is used by the class for data transfers on the endpoints It allows you to route the transfer to the proper endpoint within the interface There will be one class communication structure per configuration to which the class instance has been added Listing 7 6 presents this structure struct usbd_xxxx_comm USBD_XXXX_CTRL CtrlPtr 1 CPU_INTO8U ClassEpInAddr 2 CPU_INTO8U ClassEpOutAdd2 2 2 ti Listing 7 6 Class Instance Communication Structure L7 6 1 A pointer to the class instance control structure to which the communication relates to L7 6 2 Class specific fields In general this structure stores mainly endpoint addresses related to the class Depending on the class the structure may store other types of information For instance the Mass Storage Class stores information about the Command Block and Status Wrappers Micrium s USB classes define a class state for each class instance created The class state values are implemented in the form of an enumeration typedef enum usbd xxxx state USBD_XXXX_STATE NONE 0 USBD_XXXX_STATE INIT USBD_XXXX_STATE CFG USBD_XXXX_ STATE Figure 7 4 defines a class state machine which applies to all the Micrium classes Three class states are used 1
274. ness of any information herein and is not responsible for any errors or omissions The publisher assumes no liability for damages resulting from the use of the information in this book or for any infringement of the intellectual property rights of third parties that would result from the use of this information Micrium 100 uC USB Device 001 For the Way Engineers Work Chapter 1 1 1 1 1 1 1 1 2 1 1 3 1 2 1 2 1 1 2 2 1 2 3 1 3 1 3 1 1 3 2 1 4 1 4 1 1 4 2 1 4 3 Chapter 2 2 1 2 2 2 3 2 4 2 4 1 2 4 2 2 4 3 2 4 4 2 5 Table of Contents About USB Aish ee nein tlk Sahin teenie tie tae 15 idee He Lu EE 15 BUS ee e VE 15 USB HOSt isi satiie e eege e ein evi ene eee Aa 16 USB DEI EE E E E EE evsvel denen veievesieteleiedt T 16 Data Flow Mod l ciinii a a aaa aa a eaaa ais 17 VAC OMNES ee EATA E E ATTAT 17 EIDEN 18 Transfer TYPOS pisina Eran OA AA AE eO setenv ens seucuceessngesates ssnesere se 18 Physical Interface and Power Management cccceseeeeesseeeeeeeeeeeeeees 21 SPCC EE 21 Power DIStribDUtiOn ee Nee ENEE tee 22 Device Structure and Enumeration cccccccccceeecsssesessssssssseesseeeeeeeeees 22 USB Devic SMU U A isc ege cack even ha heaves Nees 22 Device States divi scien hi nnd etl ania 24 Enumeration stuet a a eege EE dened Niege eebe 25 Getting Started EE 27 Bd UE 28 Downloading the Source Code Files ccccccceeeeeeeseeeeeeeneeeeeeeenes 28 Installing the IEN 30 Building the Sa
275. ng 11 1 PHDC Instance Initialization and Configuration Example L11 1 1 Initialize PHDC internal members and variables L11 1 2 Create a PHDC instance this instance support preambles and ISO IEEE 11073 based data and messaging protocol 191 Chapter 11 111 13 L11 1 4 111 16 111 16 Configure read and write pipes with correct QoS and opaque data Add ISO IEEE 11073 device specialization to PHDC instance Add class instance to high speed configuration Add class instance to full speed configuration 11 3 CLASS INSTANCE COMMUNICATION Now that the class instance has been correctly initialized it s time to exchange data PHDC offers 4 functions for that Table 11 8 summarizes the communication functions provided by the PHDC implementation See Appendix F PHDC API Reference on page 441 for a complete API reference Function name Operation USBD_PHDC_RdPreamble Reads metadata preamble USBD_PHDC_Rd Reads PHDC data USBD_PHDC_WrPreamble Writes metadata preamble USBD_PHDC_Wr Writes PHDC data Table 11 8 PHDC Communication API Summary 11 3 1 COMMUNICATION WITH METADATA PREAMBLE Via the preamble enabled callback the application will be notified once host enables metadata preamble If metadata preambles are enabled you should use the following procedure to perform a read E Call USBD_PHDC_RdPreamble Device expects metadata preamble from the host This function will return
276. ng endpoints E A pair of control IN and OUT endpoints called the default endpoint E An interrupt IN endpoint E An optional interrupt OUT endpoint Table 9 1 describes the usage of the different endpoints Endpoint Direction Usage Control IN Device to host Standard requests for enumeration class specific requests and data communication Input Feature reports sent to the host with GET_REPORT request Control OUT Host to device Standard requests for enumeration class specific requests and data communication Output Feature reports received from the host with SET_REPORT request Interrupt IN Device to host Data communication Input and Feature reports Interrupt OUT Host to device Data communication Output and Feature reports Table 9 1 HID Class Endpoints Usage 9 1 1 REPORT A host and a HID device exchange data using reports A report contains formatted data giving information about controls and other physical entities of the HID device A control is manipulable by the user and operates an aspect of the device For instance a control can be a button on a mouse or a keyboard a switch etc Other entities inform the user about the state of certain device s features For instance LEDs on a keyboard notify the user about the caps lock on about the numeric keypad active etc 136 Overview The format and the use of a report data is understood by the host by analyzing the content of a Report de
277. nously The read and write operation is the opposite of the host side in terms of USB transfer direction Read operation implies a bulk OUT endpoint while a write implies a bulk IN endpoint If the Echo Async is enabled the same steps done by the Sync task is replicated but using the asynchronous API A task is responsible to start the first asynchronous OUT transfer to receive the header The task is also used in case of error during the protocol communication The callback associated to the header reception is called by the device stack It prepares the next asynchronous OUT transfer to receive the payload The read payload callback sends back the payload to the host via an asynchronous IN transfer The write payload callback is called and either prepares the next header reception if the entire payload has been sent to the host or prepares a next OUT transfer to receive a new chunk of data payload Upon the first connection of the vendor device Windows enumerates the device by retrieving the standard descriptors Since Microsoft does not provide any specific driver for the Vendor class you have to indicate to Windows which driver to load using an INF file refer to section 3 1 1 About INF Files on page 46 to for more details about INF The INF file tells Windows to load the WinUSB generic driver provided by Microsoft Indicating the INF file to Windows has to be done only once Windows will then automatically recognize the vendor
278. nsferred to indicate a short transfer to the host E This function can be only called from USB device class drivers during class specific setup request callbacks 262 A 4 2 USBD_CtriRx Receive data on control OUT endpoint FILES usbd_core h usbd_ep c PROTOTYPE CPU_INT32U USBD_Ctr1Rx CPU_INTO8U dev_nbr void p buf CPU_INT32U buf_len CPU_INT16U timeout_ms USBD_ERR p err ARGUMENTS dev_nbr Device number p_buf Pointer to buffer of data that will be sent buf_len Number of octets to transmit timeout_ms Timeout in milliseconds p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR DEV INVALID NBR USBD_ERR DEV INVALID STATE USBD_ERR_ EP INVALID ADDR USBD_ERR_EP INVALID STATE USBD_ERR_EP INVALID TYPE USBD_ERR_OS TIMEOUT USBD_ERR_OS ABORT USBD_ERR_OS FAIL 263 Appendix A RETURNED VALUE Number of octets received If no error s 0 otherwise CALLERS USB device class drivers NOTES WARNINGS This function can be only called from USB device class drivers during class specific setup request callbacks 264 A 4 3 USBD_BulkAdd Adds a bulk endpoint to alternate setting interface FILES usbd_core h usbd_core c PROTOTYPE CPU_INTO8U USBD_BulkAdd CPU_INTO8U CPU_INTO8U CPU_INTO8U CPU_INTO8U CPU_BOOLEAN CPU_INT16U USBD_ERR ARGUMENTS dev_nbr Device number cfg_nbr Configuration number if_nbr Interface number dev_nbr
279. nstants RUNNING THE DEMO APPLICATION In this section we will assume Windows as the host operating system Upon connection of your CDC ACM device Windows will enumerate your device and load the native driver usbser sys to handle the device communication The first time you connect your device to the host you will have to indicate to Windows which driver to load using an INF file refer to section 3 1 1 About INF Files on page 46 for more details about INF The INF file tells Windows to load the usbser sys driver Indicating the INF file to Windows has to be done only once Windows will then automatically recognize the CDC ACM device and load the proper driver for any new connection The process of indicating the INF file may vary according to the Windows operating system version P Windows XP directly opens the Found New Hardware Wizard Follow the different steps of the wizard until you reach the page where you can indicate the path of the INF file E Windows Vista and later won t open a Found New Hardware Wizard It will just indicate that no driver was found for the vendor device You have to manually open the wizard When you open the Device Manager your CDC ACM device should appear with a yellow icon Right click on your device and choose Update Driver Software to open the wizard Follow the different steps of the wizard until the page where you can indicate the path of the INF file 130 ACM Subclass The INF f
280. nt and size E The polling internal for the interrupt IN endpoint E The polling internal for the interrupt OUT endpoint 144 Configuration A flag enabling or disabling the Output reports reception with the control endpoint When the control endpoint is not used the interrupt OUT endpoint is used instead to receive Output reports A structure that contains 4 application callbacks used for class specific requests processing 3 Call USBD HID CfgAdd Finally once the HID class instance has been created you must add it to a specific configuration Listing 9 1 illustrates the use of the previous functions for initializing the HID class static USBD HID CALLBACK App USBD HID Callback ti App_USBD_HID GetFeatureReport App_USBD_HID SetFeatureReport App_USBD_HID_GetProtocol App USBD HID SetProtocol CPU_BOOLEAN App USBD_HID Init CPU_INTO8U dev_nbr CPU_INTO8U cfg_hs CPU_INTO8U cfg_fs USBD_ERR err CPU_INT08U class_nbr USBD_HID Init amp err if err USBD ERR NONE Handle the error 3 1 2 145 Chapter 9 class nr USBD_HID Add USBD_HID SUBCLASS BOOT USBD_HID_PROTOCOL_MOUSE USBD_HID_COUNTRY_CODE NOT SUPPORTED amp App USBD_HID ReportDesc 0 sizeof App USBD_HID ReportDesc CPU_INTO8U 0 Ou 2u 2u DEF_YES K pp USBD HID Callback 3 amp err if err USBD ERR NONE Handle the error if cfg_hs USBD_CFG_NBR_NONE USB
281. ntroller supports only full speed Specify the endpoint information table The endpoint information table should be defined in your USB device controller BSP files Refer to section 6 5 1 Endpoint Information Table on page 86 for more details about the endpoint information table MODIFY USB APPLICATION INITIALIZATION CODE Listing 2 3 shows the code that you should modify based on your specific configuration done previously You should modify the parts that are highlighted by the bold text The code snippet is extracted from the function App USBD Init defined in app usbd c The complete initialization sequence performed by App USBD_Init is presented in Listing 2 5 35 Chapter 2 include lt usbd_bsp template bz CL CPU_BOOLEAN App USBD_Init void CPU_LINTO8U dev_nbr CPU_LINTO8U cfg_fs_nbr USBD_ERR err USBD_Init serr 2 dev_nbr USBD_DevAdd amp USBD_DevCfg_ Template 3 amp App_USBD_BusFncts S8USBD_DrvAPI_Template 4 amp USBD_DrvCfg_Template 5 amp USBD_DrvBSP_Template 6 serr if USBD_DrvCfg_Template Spd USBD_DEV_SPD_HIGH 7 cfg_hs_nbr USBD_CfgAdd dev_nbr USBD_DEV_ATTRIB_SELF_POWERED 100u USBD_DEV_SPD_HIGH HS configuration amp err Listing 2 3 App_USBD_Init in app_usbd c L2 3 1 Include the USB driver BSP header file that is specific to your board This file can be found in the following folder Micrium Software uC USB Device Drivers lt contro
282. o ACM subclass instances are used USBD_VENDOR_CFG MAX NBR DEV 1 Only one vendor class instance is used USBD_VENDOR_CFG MAX NBR CFG 2 The vendor class instance can be used in one full speed and one high speed configuration Table 5 3 Configuration Example of a Complex Composite High Speed USB Device 76 Chapter Device Driver Guide There are many USB device controllers available on the market and each requires a driver to work with pC USB Device The amount of code necessary to port a specific device to uC USB Device greatly depends on the device s complexity If not already available a driver can be developed as described in this chapter However it is recommended to modify an already existing device driver with the new device s specific code following the Micrium coding convention for consistency It is also possible to adapt drivers written for other USB device stacks especially if the driver is short and it is a matter of simply copying data to and from the device 6 1 DEVICE DRIVER ARCHITECTURE This section describes the hardware device driver architecture for pC USB Device including E Device Driver API Definition s E Device Configuration E Memory Allocation E CPU and Board Support Micrium provides sample configuration code free of charge however the sample code will likely require modification depending on the combination of processor evaluation board and USB device controller s 77 Cha
283. o reentrancy When writing your own device driver you can assume that each driver API function accepts a pointer to a structure of the type USBD_DRV as one of its parameters Through this structure you will be able to access the following fields typedef struct usbd_drv USBD_DRV typedef usb drv CPU_INTO8U DevNbr 1 USBD_DRV_API API_Ptr 2 USBD_DRV_CFG CfgPtr 3 void DataPtr 4 USBD_DRV_BSP_API BSP_API Ptr 5 ti Listing 6 2 USB Device Driver Data Type L6 2 1 Unique index to identify device L6 2 2 Pointer to USB device controller driver API L6 2 3 Pointer to USB device controller driver configuration L6 2 4 Pointer to USB device controller driver specific data L6 2 5 Pointer to USB device controller BSP 80 Interrupt Handling 6 4 INTERRUPT HANDLING Interrupt handling is accomplished using the following multi level scheme 1 Processor level kernel aware interrupt handler 2 Device driver interrupt handler During initialization the device driver registers all necessary interrupt sources with the BSP interrupt management code You can also accomplish this by plugging an interrupt vector table during compile time Once the global interrupt vector sources are configured and an interrupt occurs the system will call the first level interrupt handler The first level interrupt handler is responsible for performing all kernel required steps prior to calling the USB device driver interrupt handler
284. oint This function is blocking FILES usbd_vendor c PROTOTYPE CPU_INT32U USBD Vendor Wr CPU_INT08U class_nbr void p buf CPU_INT32U buf_len CPU_INT16U timeout CPU_BOOLEAN end USBD_ERR p err ARGUMENTS class nr Class instance number p_buf Pointer to transmit buffer buf_len Transmit buffer length in octets timeout Timeout in milliseconds end End of transfer flag p_err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR NULL PTR USBD_ERR_INVALID ARG USBD_ERR_ INVALID CLASS STATE USBD_ERR_ DEV INVALID NBR USBD_ERR_ EP INVALID NBR USBD_ERR DEV INVALID STATE USBD_ERR_EP INVALID TYPE 483 Appendix G RETURNED VALUE Number of octets sent if NO error s 0 otherwise CALLERS Application NOTES WARNINGS If end of transfer flag is set and transfer length is multiple of maximum packet size a zero length packet is transferred to indicate the end of transfer to the host 484 G 1 7 USBD_Vendor_RdAsync Receive data from host through Bulk OUT endpoint This function is non blocking It returns immediately after transfer preparation Upon transfer completion a callback provided by the application will be called to finalize the transfer FILES usbd_vendor c PROTOTYPE void USBD_Vendor_RdAsync CPU_INTO8U class_nbr void p buf CPU_INT32U buf_len USBD_VENDOR_ASYNC_FNCT async _fnct void p_ async arg USBD_ERR p err
285. olling interval for input transfers in milliseconds 389 Appendix D interval_out Polling interval for output transfers in milliseconds Used only when read operations are not through control transfers ctrl rd en Enable read operations through control transfers p_hid_callback Pointer to HID descriptor and request callback structure p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_ALLOC USBD_ERR NULL PTR USBD_ERR_INVALID ARG USBD_ERR FAIL RETURNED VALUE Class interface number if NO error s USBD_CLASS NBR NONE otherwise CALLERS Application NOTES WARNINGS None 390 D 1 3 USBD_HID_CfgAdd This function adds HID class instance into USB device configuration FILES usbd_hid c PROTOTYPE CPU_BOOLEAN USBD_HID CfgAdd CPU_INTO8U class_nbr CPU_LINTO8U dev_nbr CPU_INTO8U cfg_nbr USBD_ERR p err ARGUMENTS class nbr_ Class instance number dev_nbr Device number cfg_nbr Configuration index to add class instance to p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_ALLOC USBD_ERR_INVALID ARG USBD_ERR_ NULL PTR USBD_ERR_ DEV INVALID NBR USBD_ERR_ DEV INVALID STATE USBD_ERR CFG INVALID NBR USBD_ERR_IF ALLOC USBD_ERR_IF ALT ALLOC USBD_ERR_EP NONE AVAIL USBD_ERR_IF INVALID NBR USBD_ERR_EP ALLOC 391 Appendix D RETURNED VALUE DEF_YES if NO error s
286. ollowing illustrations present several case scenarios Each illustration is followed by a code listing showing the code corresponding to the case scenario Figure 7 1 represents a typical USB device The device is Full Speed FS and contains one single configuration The function of the device is described by one interface composed of a pair of endpoints for the data communication One class instance is created and it will allow you to manage the entire interface with its associated endpoint FS device Es Configuration 0 Interface 0 Default interface Alternate 0 Endpoint IN Endpoint OUT Class instance 0 Figure 7 1 Multiple Class Instances FS Device 1 Configuration with 1 Interface The code corresponding to Figure 7 1 is shown in Listing 7 1 100 USBD_ERR Class Instance Concept err CPU_INTO8U class_0 USBD_XXXX_Init serr 1 if err USBD_ERR NONE Handle the error class_0 USBD_XXXX_Add S amp err 2 if err USBD_ERR NONE Handle the error USBD_XXXX_CfgAdd class_0 dev_nbr cfg_0 amp err 3 if err USBD_ERR_NONE Handle the error L7 10 L7 1 2 17 16 Listing 7 1 Multiple Class Instances FS Device 1 Configuration with 1 Interface Code Initialize the class Any internal variables structures and class Real Time Operating System RTOS port will be initialized Create the cla
287. on how these functions should be implemented refer to section 14 3 on page 240 and to section A 5 Core OS Functions on page 298 Function name Operation USBD_OS_Init Initializes all internal members tasks USBD_OS_EP_SignalCreate Creates OS signal used to synchronize synchronous transfers USBD_OS_ EP SignalDel Deletes OS signal used to synchronize synchronous transfers USBD_OS_EP_SignalPend Pends on OS signal used to synchronize synchronous transfers USBD_OS_EP_SignalAbort Aborts OS signal used to synchronize synchronous transfers USBD_OS_EP_SignalPost Posts OS signal used to synchronize synchronous transfers USBD_OS_DbgEventRdy Posts signal used to resume debug task USBD_OS_DbgEventWait Pends on signal used to resume debug task USBD_OS CoreEventGet Retrieves the next core event to process USBD_OS CoreEventPut Adds a core event to be processed by the core Table 14 3 Core OS port API summary Note that you must declare at least one task for the core events management within your RTOS port This task should simply call the core function USBD_CoreTaskHandler in an infinite loop Furthermore if you plan using the debugging feature you must also create a 242 Porting The Core Layer to a RTOS task for this purpose This task should simply call the core function USBD_DbgTaskHandler in an infinite loop Listing 14 1 shows how these two task functions body should be im
288. onfiguration error codes functions interrupt handling interrupt exe ISR handler E L low speed 541 Index M memory allocation 88 memory footprint HID class MS class PHDC Vendor class metadata preamble module G vss essere at nes 29 libraries relationship MOUSE demo sses 156 Mouse Report Descriptor Example MS class a architecture 169 configuration 69 173 configuration constants demo application endpoint endpoint usage functions initialization memory footprint OS functions porting protocol requests state machine storage layer functions task handler multiple class instances eeeeeeeeeeeeee 99 103 106 107 N ee E EE 84 O OS layer APPin e eiaa a OEE anean 204 OS layer error codes neeeeeeeseeeeeeeeeeerrreereeresreereens 529 P periodic input reports task 161 162 PHDC 184 535 communication 192 communication API 192 configuration 69 187 191 configuration constants 188 data characteristics 184 demo application 201 202 endpoint functions initialization API instance initialization memory footprint operational model OS layer functions porting read software layers 542 physical interface pipe management porting Core ayem See EEN 242 HID class module
289. onfigurations For instance the following architecture could be created for an high speed device High speed Configuration 0 Interface 0 MSC 0 Configuration 1 Interface 0 MSC 0 Interface 1 MSC 1 In that example there are two instances of MSC MSC 0 and MSC 1 and two possible configurations for the device Configuration 0 and Configuration 1 Configuration 1 is composed of two interfaces Each class instance has an association with one of the interfaces If Configuration 1 is activated by the host it allows the host to access two different functionalities offered by the device 423 Appendix E E 1 4 USBD_MSC LunAdd Add a logical unit number to the MSC interface FILES usbd_msc h usbd_msc c PROTOTYPE void USBD_MSC_LunAdd CPU_CHAR p_store name ARGUMENTS p_store_name class obt p_vend_id p_prod_id prod_rev_level rd_only p_err 424 CPU_LINTO8U class_nbr CPU_CHAR p vend_id CPU_CHAR p prod_id CPU_INT32U prod_rev_level CPU_BOOLEAN rd_only USBD_ERR p err Pointer to logical unit driver MSC instance number Pointer to string containing vendor id Pointer to string containing product id Product revision level Boolean specifying if logical unit is read only or not Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_ INVALID ARG USBD_ERR MSC MAY LUN EXCEED USBD_ERR SCSI _LOG UNIT
290. onfigurations and multiples instances architecture Refer to section 7 1 Class Instance Concept on page 99 for more details about multiple class instances 12 2 3 CLASS INSTANCE COMMUNICATION The Vendor class offers the following functions to communicate with the host For more details about the functions parameters refer to section G 1 Vendor Class Functions on page 474 Function name Operation USBD_Vendor_Rd Receive data from host through bulk OUT endpoint This function is blocking USBD_Vendor_Wr Send data to host through bulk IN endpoint This function is blocking USBD_Vendor_RdAsync Receive data from host through bulk OUT endpoint This function is non blocking USBD_Vendor_WrAsync Send data to host through bulk IN endpoint This function is non blocking USBD_Vendor_IntrRd Receive data from host through interrupt OUT endpoint This function is blocking USBD_Vendor_Intrwr Sends data to host through interrupt IN endpoint This function is blocking USBD_Vendor_IntrRdAsync Receives data from host through interrupt OUT endpoint This function is non blocking USBD_Vendor_IntrWrAsync Sends data to host through interrupt IN endpoint This function is non blocking Table 12 4 Vendor Communication API Summary 210 Configuration 12 2 4 SYNCHRONOUS COMMUNICATION Synchronous communication means that the transfer is blocking Upon function call the applications blocks until t
291. ons Revision 1 0 Appendix A For a list of known device specialization see Nomenclature code annex of ISO IEEE 11073 20601 Specific code are listed in the From Communication infrastructure MDC_PART_INFRA section 453 Appendix F F 1 8 USBD_PHDC_RdPreamble Read metadata preamble This function is blocking FILES usbd_phdc h usbd_phdc c PROTOTYPE CPU_INT08U USBD_PHDC_RdPreamble CPU_INTO08U class_nbr void p buf CPU_INTO8U buf len CPU_LINTO8U p nbr xfer CPU_INT16U timeout USBD_ERR p err ARGUMENTS class_nbr PHDC instance number p buf Pointer to buffer that will contain data from metadata message preamble buf len Opaque data buffer length in octets p_nbr xfer Pointer to a variable that will contain the number of transfer the preamble will apply to After this call USBD_PHDC_Rd shall be called nbr_xfer times by the application timeout Timeout in milliseconds p_err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_ INVALID CLASS STATE USBD_ERR_ INVALID ARG USBD_ERR_ NULL PTR USBD_ERR_ALLOC USBD_ERR_RX 454 USBD_ERR DEV INVALID NBR USBD_ERR_ EP INVALID NBR USBD_ERR DEV INVALID STATE USBD_ERR_EP INVALID TYPE USBD_OS ERR TIMEOUT USBD_OS ERR ABORT USBD_OS ERR FAIL RETURNED VALUE Length of opaque data read from metadata preamble if no error 0 otherwise CALLERS Application NOTES WARNINGS USBD_PHDC RdP
292. opPageAddReg DriverInstall Services include mdmcpq inf AddService usbser 0x00000002 LowerFilter_Service_Inst SerialPropPageAddReg HKR EnumPropPages32 MsPorts d1ll SerialPortPropPageProvider po Strings section Strings 5 ProviderName Micrium PROVIDER_CDC Micrium CDC Device Listing 3 1 Example of INF File Structure 13 11 The section Version is mandatory and informs Windows about the provider the version and other descriptive information about the driver package L3 1 2 The section Manufacturer is mandatory It identifies the device s manufacturer 13 1033 The following two sections are called Models sections and are defined on a per manufacturer basis They gives more detailed instructions about the driver s to install for the device s A section name can use extensions to specify OSes and or CPUs the entries apply to In this example NTx86 and NTamd64 indicate that the driver can be installed on an NT based Windows that is Windows 2000 and later on x86 and x64 based PC respectively L3 1 4 The installation sections actually install the driver s for each device described in the Model section s The driver installation may involve reading existing information from the Windows registry modifying existing entries of the registry or creating new entries into the registry 48 Microsoft Windows 13 165 The section Strings is mandatory and it is
293. opaque data and the number of incoming transfers that the host specified Note that if the host disables preamble while the application is pending on that function it will immediately return with error USBD_ERR_OS ABORT 192 Class Instance Communication P Call USBD_PHDC_Rd a number of times corresponding to the number of incoming transfers returned by USBD_PHDC RdPreamble Application must ensure that the buffer provided to the function is large enough to accommodate all the data Otherwise synchronization issues might happen Note that if the host enables preamble while the application is pending on that function it will immediately return with error USBD_ERR_OS ABORT CPU_LINT16U App USBD PHDC_Rd CPU_INTO8U class_nbr CPU_LINTO8U p data_opaque_buf CPU_INTO8U p data_opaque_len CPU_INTO8U p buf USBD_ERR p err CPU_INTO8U nbr xfer CPU_LINT16U xfer_len p data_opaque_len USBD_PHDC_RdPreamble class_nbr 1 void p data_opaque buf 2 USBD_PHDC_ CFG DATA OPAQUE MAX LEN amp nbr xfer 3 0 4 perr for i 0 i lt nbr_xfers i 5 xfer_len USBD_PHDC_Rd class_nbr void p buf 6 APP_USBD_PHDC_ ITEM DATA LEN MAX 0 4 perr Handle received data return xfer len Listing 11 2 PHDC Read Procedure L11 2 1 The class instance number obtained with USBD_PHDC Add will serve internally to the PHDC class to route the data to the proper endpoints 193 Cha
294. or code from this function USBD_ERR_NONE OS error code s relevant to failure s CALLERS USBD_HID Wr USBD_HID WrAsync USBD_HID ClassReq IMPLEMENTATION GUIDELINES The lock operation typically consists in pending on a semaphore If the semaphore is free the task continues normally its execution otherwise it waits until another task releases the semaphore p err argument should be assigned as described in Table D 1 Operation result Error code to assign No error USBD_ERR_NONE Pend aborted USBD_ERR_OS_ABORT Pend failed for any other reason USBD_ERR_OS FAIL Table D 1 p_err assignment according to the pend operation result 403 Appendix D D 2 3 USBD_HID_OS InputUnlock Unlock class input report FILES usbd_hid_os c PROTOTYPE void USBD_HID OS InputUnlock CPU_INTO8U class_nbr ARGUMENTS class nbr_ Class instance number CALLERS USBD_HID Wr USBD_HID WrAsync USBD_HID_ClassReq IMPLEMENTATION GUIDELINES The unlock operation simply consists in posting a semaphore 404 D 2 4 USBD_HID_OS InputDataPend Wait for input report data to complete FILES usbd_hid_os c PROTOTYPE void USBD HID OS InputDataPend CPU_LINTO8U class nbr CPU _INT16U timeout ms USBD_ERR p err ARGUMENTS class_nbr Class instance number timeout ms Signal wait timeout in milliseconds p err Pointer to variable that will receive the return error code from this function USBD_ERR_NON
295. or more details about the functions parameters refer to section C 2 CDC ACM Subclass Functions on page 369 Function name Operation USBD_ACM SerialInit Initializes ACM subclass internal structures and variables USBD_ACM SerialAdd Creates a new instance of ACM subclass USBD_ACM SerialCfgAdd Adds an existing ACM instance to the specified device configuration USBD_ACM SerialLineCodingReg Registers line coding notification callback USBD_ACM SerialLineCtr1Reg Registers line control notification callback Table 8 6 ACM Subclass Initialization API Summary 123 Chapter 8 You need to call these functions in the order shown below to successfully initialize the ACM subclass 124 Call USBD_ACM SerialInit This function initializes all internal structures and variables that the ACM subclass needs You should call this function only once even if you use multiple class instances Call USBD_ACM SerialAdd This function allocates an ACM subclass instance Internally this function allocates a CDC class instance It also allows you to specify the line state notification interval expressed in milliseconds Call USBD_ACM SerialLineCodingReg This function allows you to register a callback used by the ACM subclass to notify the application about a change in the serial line coding settings that is baud rate number of stop bits parity and number of data bits Call USB
296. ort Not intended for routing and Internet connectivity devices Network Control Model NCM IEEE 802 3 adaptors carrying high speed data bandwidth on 118 network Table 8 2 CDC Subclasses Architecture 8 2 ARCHITECTURE Figure 8 2 shows the general architecture between the host and the device using CDC available from Micrium Host operating system Application USB Host stack pe hag ControlO IN amp OUT Interrupt I B ine CCI EPR ee coc J CDC Subclass S Application USB Device optional Figure 8 2 General Architecture between a Host and Micripm s CDC The host operating system OS enumerates the device using the control endpoints Once the enumeration phase is done the host can configure the device by sending class specific requests to the Communications Class Interface CCI via the control endpoints The class specific requests vary according to the CDC subclasses Micrium s CDC base class offers the possibility to allocate an interrupt endpoint for event notification depending on the subclass needs Following enumeration and configuration of the device the host can start the transmission reception of data to from the device using the bulk endpoints belonging to the Data Class Interface DCI Isochronous endpoints are not suppo
297. ost enables disables metadata message preambles This is useful for the application as the behavior in communication will differ depending on the metadata message preamble state 189 Chapter 11 190 If your application needs to send low latency good reliability data the class will need to allocate an interrupt endpoint The interval of the endpoint will be specified in this call as well Call USBD_PHDC_RdCfg and USBD_PHDC WrCfg The next step is to call USBD_PHDC_RdCfg and USBD_PHDC WrCfg These functions will let you set the latency reliability bins that the communication pipe will carry Bins are listed in Table 11 7 It will also be used to specify opaque data to send within extra endpoint metadata descriptor see USB Device Class Definition for Personal Healthcare Devices Release 1 0 Section 5 for more details on PHDC extra descriptors Name Description USBD_PHDC_LATENCY_VERYHIGH_RELY_ BEST Very high latency best reliability USBD_PHDC_LATENCY_HIGH RELY BEST High latency best reliability USBD_PHDC_LATENCY_MEDIUM_RELY_ BEST Medium latency best reliability USBD_PHDC_LATENCY_MEDIUM_RELY BETTER Medium latency better reliability USBD_PHDC_LATENCY MEDIUM RELY GOOD Medium latency good reliability USBD_PHDC_LATENCY LOW RELY GOOD Low latency good reliability Table 11 7 Listing of QoS Bins Call USBD_PHDC_11073_ExtCfg optional If PHDC instance uses ISO IEEE 11073 based
298. p buf CPU_INT32U buf_len USBD_ASYNC_FNCT async_fnct void p_async_ arg CPU_BOOLEAN end USBD_ERR p err ARGUMENTS dev_nbr Device number ep_addr Endpoint address p_buf Pointer to buffer of data that will be transmitted buf_len Number of octets to transmit async_fnct Function that will be invoked upon completion of transmit operation p_async_arg Pointer to argument that will be passed as parameter of async_fnct end End of transfer flag see Note 2 p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_ DEV INVALID NBR USBD_ERR_ DEV INVALID STATE 284 USBD_ERR_EP INVALID ADDR USBD_ERR_ EP INVALID STATE USBD_ERR_EP INVALID TYPE USBD_ERR_OS TIMEOUT USBD_ERR_OS ABORT USBD_ERR_OS FAIL RETURNED VALUE None CALLERS USB device class drivers NOTES WARNINGS P The callback specified by async_fnct has the following prototype void USB_AsyncFnct CPU_INTO8U dev_nbr CPU_INTO8U ep addr void p buf CPU_INT32U buf_len CPU_INT32U xfer_len void p arg USBD_ERR err Argument s dev_nbr Device number ep addr Endpoint address p_buf Pointer to buffer of data that will be transmitted buf_len Buffer length xfer_len Number of byte transmitted p_arg Pointer to function argument 285 Appendix A err Error status USBD_ERR_NONE USBD_ERR_EP ABORT E If end of transfer is set and transfer length is multiple of maximum pac
299. ple of initialization of these structures These files are distributed as templates and you should modify them to have the proper configuration for your USB device controller The fields of the following structure are the parameters needed to configure the USB device controller driver typedef const struct usb drv cfg CPU_ADDR BaseAddr 1 CPU_ADDR MemAddr 2 CPU_ADDR MemSize 3 USBD_DEV_SPD Spd 4 USBD_DRV_EP_INFO EP_InfoTbl 5 USBD_DRV_CFG Listing 6 3 USB Device Controller Driver Configuration Structure L6 3 1 Base address of the USB device controller hardware registers L6 3 2 Base address of the USB device controller dedicated memory L6 33 Size of the USB device controller dedicated memory L6 3 4 Speed of the USB device controller Can be set to either USBD_DEV_SPD_LOW USBD_DEV_SPD_FULL or USBD_DEV_SPD_HIGH L6 36 USB device controller endpoint information table see section 6 5 1 Endpoint Information Table on page 86 The fields of the following structure are the parameters needed to configure the USB device 85 Chapter 6 typedef const struct usb dev cfg CPU_INT16U VendorID 1 CPU_INT16U Product ID 2 CPU_INT16U DeviceBCD 3 const CPU_CHAR ManufacturerStrPtr 4 const CPU_CHAR ProductStrPtr 5 const CPU_CHAR SerialNbrStrPtr 6 CPU_INT16U LangID 7 1 USBD_DEV_CFG Listing 6 4 USB Device Configuration Structure L6 4 1 Vendor ID L6 4 2 Product ID L
300. plemented static void USBD_OS CoreTask void p arg p_arg p arg while DEF_ON USBD_CoreTaskHandler static void USBD_OS TraceTask void p arg p_arg p_arg while DEF ON USBD_DbgTaskHandler Listing 14 1 Core task and debug task typical implementation 243 Chapter 14 244 Appendix Core API Reference This appendix provides a reference to the wC USB Device core layer API The following information is provided for each of the services A brief description The function prototype The filename of the source code A description of the arguments passed to the function A description of returned value s Specific notes and warnings regarding use of the service 245 Appendix A A 1 DEVICE FUNCTIONS A 1 1 USBD Init Initialize USB device stack This function is called by the application exactly once This function initializes all the internal variables and modules used by the USB device stack FILES usbd_core h usbd_core c PROTOTYPE static void USBD_Init USBD_ERR p err ARGUMENTS p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_ OS INIT FAIL RETURNED VALUE None CALLERS Application NOTES WARNINGS USBD_Init must be called E Only once from a product s application E After product s OS has been initialized E Before product s application calls any USB device stack function
301. plication USB Device Figure 12 1 General Architecture Between Windows Host and Vendor Class On the Windows side the application communicates with the vendor device by interacting with the USBDev_API library This library provided by Micrium offers an API to manage a device and its associated pipes and to communicate with the device through control bulk and interrupt endpoints USBDev_API is a wrapper that allows the use of the WinUSB functions exposed by Winusb dll On the device side the Vendor class is composed of the following endpoints E A pair of control IN and OUT endpoints called the default endpoint E A pair of bulk IN and OUT endpoints E A pair of interrupt IN and OUT endpoints This pair is optional 206 Configuration Table 12 1 indicates the usage of the different endpoints Endpoint Direction Usage Control IN Device to host Standard requests for enumeration and vendor specific requests Control OUT Host to device Bulk IN Device to host Raw data communication Data can be structured according to a Bulk OUT Host to device proprietary protocol Interrupt IN Device to host Raw data communication or notification Data can be structured Interrupt OUT Host to device according to a proprietary protocol Table 12 1 Vendor Class Endpoints Usage The device application can use bulk and interrupt endpoints to send or receive data to or from the host It can only use the defa
302. ponsible for enabling transmit complete ISR s While data is being transmitted the device synchronous transmit operation waits on the device transmit signal The USB device controller triggers an interrupt request when it is finished transmitting the data This invokes the USB device driver interrupt service routine ISR handler directly or indirectly depending on the architecture Inside the USB device driver ISR handler the type of interrupt request is determined as a transmit interrupt USBD_EP_TxCmp1l is called to unblock the device transmit signal On DMaA based controllers the transmit transfer is de queued from a list of completed transfers The device transmit operation iterates through the process until the amount of data transmitted matches the requested amount USB Device Driver Functional Model 6 8 4 DEVICE ASYNCHRONOUS TRANSMIT The device asynchronous transmit operation is initiated by the calls USBD_BulkTxAsync and USBD_IntrTxAsync Figure 6 4 shows an overview of the device asynchronous transmit operation F6 4 1 USBD_EP_Tx Se Ko USBD_DrvEP_Tx P l 1 USBD_DrvEP_TxStart 2 ie D EP Queue Transmit Complete Callback 7 5 4 A SC lt _ _ Core Task lt lt _ T __USBD_EP_TxCmpl K 4 Q yy at 6 ee Es EN 7 x gt Device ISR Handler USBD_DrvEP_Tx USB Device q 4 K Interrupt 3 USBD
303. pplication Specific Configuration 5 1 9 MASS STORAGE CLASS MSC CONFIGURATION For information on MSC configuration refer to Section 10 4 Configuration on page 173 5 1 10 PERSONAL HEALTHCARE DEVICE CLASS PHDC CONFIGURATION For information on PHDC configuration refer to section 11 2 Configuration on page 187 5 1 11 VENDOR CLASS CONFIGURATION For information on vendor class configuration refer to Section 12 2 Configuration on page 207 5 2 APPLICATION SPECIFIC CONFIGURATION This section defines the configuration constants related to pC USB Device but that are application specific All these configuration constants relate to the RTOS For many OSs the pC USB Device task priorities and stack sizes will need to be explicitly configured for the particular OS consult the specific OS s documentation for more information These configuration constants should be defined in an application s app_cfg h file 5 2 1 TASK PRIORITIES As mentioned in section 4 2 Task Model on page 58 WC USB Device needs one core task and one optional debug task for its proper operation The priority of uC USB Device s core task greatly depends on the USB requirements of your application For some applications it might be better to set it at a high priority especially if your application requires a lot of tasks and is CPU intensive In that case if the core task has a low priority it might not be able to process the bus an
304. print or another output such as a text terminal using a serial interface 39 Chapter 2 2 5 RUNNING THE SAMPLE APPLICATION The first step to integrate the demo application into your application code is to call App USBD Init This function is responsible for the following steps P Initializing the USB device stack P Creating and adding a device instance E Creating and adding configurations P Calling USB class specific application code E Starting the USB device stack The App USBD Init function is described in Listing 2 5 CPU_BOOLEAN App USBD Init void CPU_INTO8U dev_nbr CPU_LINTO8U cfg_hs_nbr CPU_LINTO8U cfg_fs_nbr CPU_BOOLEAN ok USBD_ERR err USBD_Init amp err 1 if err USBD_ERR NONE Handle error return DEF_FAIL dev_nbr USBD_DevAdd amp USBD_DevCfg_ lt controller gt 2 amp App_USBD_BusFncts amp USBD_DrvAPI_ lt controller gt amp USBD_DrvCfg_ lt controller gt amp USBD_DrvBSP_ lt board name gt amp err if err USBD_ERR_NONE Handle error return DEF_FAIL cfg_hs_nbr USBD_CFG_NBR_NONE cfg_fs_nbr USBD_CFG_NBR_NONE 40 Running the Sample Application if USBD_DrvCfg_ lt controller gt Spd USBD_DEV_SPD_HIGH cfg_hs_nbr USBD_CfgAdd dev_nbr 3 USBD_DEV_ATTRIB SELF POWERED 100u USBD_DEV_SPD_HIGH HS configuration amp err if err USBD_ERR_NONE Handle error return DEF_FAIL
305. prototype void USB_AsyncFnct CPU_LINTO8U dev_nbr CPU_INTO8U ep addr void p buf CPU_INT32U buf_len CPU_INT32U xfer_len void p arg USBD_ERR err Argument s dev_nbr Device number ep_addr Endpoint address p_buf Pointer to destination buffer to receive data buf_len Buffer length xfer len Number of byte received p_arg Pointer to function argument err Error status USBD_ERR_NONE USBD_ERR_EP ABORT 270 A 4 6 USBD_BulkTx Sends data on bulk IN endpoint FILES usbd_core h usbd_ep c PROTOTYPE CPU_INT32U USBD_BulkTx CPU_INTO8U dev_nbr CPU_INTO8U ep_addr void p buf CPU_INT32U buf_len CPU_INT16U timeout_ms CPU_BOOLEAN end USBD_ERR p err ARGUMENTS dev_nbr Device number ep_addr Endpoint address p buf Pointer to buffer of data that will be transmitted buf_len Number of octets to transmit timeout ms Timeout in milliseconds end End of transfer flag see Note 2 p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR DEV INVALID NBR USBD_ERR DEV INVALID STATE USBD_ERR_EP INVALID ADDR USBD_ERR_EP INVALID STATE USBD_ERR_EP INVALID TYPE 271 Appendix A USBD_ERR_OS TIMEOUT USBD_ERR_OS ABORT USBD_ERR_OS FAIL RETURNED VALUE Number of octets transmitted If no error s 0 otherwise CALLERS USB device class drivers NOTES WARNINGS This function blocks until All data is transmitted or An error occur
306. provided is large enough to accommodate the incoming transfer Otherwise synchronization with metadata preambles might be lost If host enable preamble while application is pending on this function the call will immediately return with error USBD_OS ERR ABORT 457 Appendix F F 1 10 USBD_PHDC_Wrpreamble Write metadata preamble This function is blocking FILES usbd_phdc h usbd_phdc c PROTOTYPE void USBD_PHDC_WrPreamble CPU_INTO8U class_nbr void p data_opaque CPU_INT16U data_opaque_len LATENCY_RELY_FLAGS latency_rely CPU_INTO8U nbr_xfers CPU_INT16U timeout USBD_ERR p err ARGUMENTS class_nbr PHDC instance number p_data_opaque Pointer to buffer that will supply opaque data data_opaque_len Length of opaque data buffer in octets latency rely Latency reliability of related transfers nbr_xfers Number of transfers this preamble will apply to timeout Timeout in milliseconds p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_INVALID ARG USBD_ERR NULL PTR USBD_ERR_TX USBD_ERR_ DEV INVALID NBR 458 USBD_ERR DEV INVALID STATE USBD_ERR_ EP INVALID ADDR USBD_ERR_EP INVALID STATE USBD_ERR_EP INVALID TYPE USBD_OS ERR TIMEOUT USBD_OS ERR ABORT USBD_OS ERR FAIL RETURNED VALUE None CALLERS Application NOTES WARNINGS USBD_PHDC WrPreamble should always be called before USBD_PHDC Wr if metadata message pre
307. pter 11 L11 2 2 L11 2 3 L11 2 4 L11 2 5 L11 2 6 Buffer that will contain opaque data Application must ensure that the buffer provided is large enough to accommodate all the data Otherwise synchronization issues might happen Variable that will contain the number of following transfers to which this preamble applies In order to avoid infinite blocking situation a timeout expressed in milliseconds can be specified A value of 0 makes the application task wait forever Read all the USB transfers to which the preamble applies Buffer that will contain the data Application must ensure that the buffer provided is large enough to accommodate all the data Otherwise synchronization issues might happen You should use the following procedure to perform a write E Call USBD_PHDC_WrPreamble Host expects metadata preamble from the device Application will have to specify opaque data transfer s QoS see Table 11 7 and a number of following transfers to which the selected QoS applies P Call USBD_PHDC_Wr a number of times corresponding to the number of transfers following the preamble CPU_INT16U App _USBD_PHDC_Wr CPU_INTO8U class_nbr LATENCY _RELY_ FLAGS latency_rely CPU_INTO8U nbr_xfer CPU_INTO8U p data_opaque_buf CPU_INTO8U data_opaque_buf_len CPU_INTO8U p buf CPU_INTO8U buf_len USBD_ERR p err 194 Class Instance Communication void USBD_PHDC_WrPreamb1e class_nbr 1 void p
308. pter 6 6 2 DEVICE DRIVER MODEL No particular memory interface is required by uC USB Device s driver model Therefore the USB device controller may use the assistance of a Direct Memory Access DMA controller to transfer data or handle the data transfers directly 6 3 DEVICE DRIVER API All device drivers must declare an instance of the appropriate device driver API structure as a global variable within the source code The API structure is an ordered list of function pointers utilized by uwC USB Device when device hardware services are required A sample device driver API structure is shown below const USBD DRV_API USBD DrvAPI_ lt controller gt USBD Drvinit 1 USBD_DrvStart 2 USBD_DrvStop 3 USBD_DrvAddrSet 4 USBD_DrvAddrEn 5 USBD_DrvCfgSet 6 USBD_DrvCfgClr 7 USBD_DrvGetFrameNbr 8 USBD_DrvEP Open 9 USBD_DrvEP_ Close 10 USBD_DrvEP_RxStart 11 USBD_DrvEP_Rx 12 USBD_DrvEP_RxZLP 13 USBD_DrvEP_Tx 14 USBD_DrvEP_TxStart 15 USBD_DrvEP_TxZLP 16 USBD_DrvEP_ Abort 17 USBD_DrvEP_ Stall 18 USBD_DrvISR_Handler 19 ti Listing 6 1 Device Driver Interface API Note It is the device driver developers responsibility to ensure that all of the functions listed within the API are properly implemented and that the order of the functions within the API structure is correct The different function pointers are 78 L6 1 1 16 1 2 L6 1 3 L6 1 4 L6 1 5 L6 1 6 L
309. r CALLERS USBD_HID Rd USBD_HID_RdAsync USBD_HID_ClassReq IMPLEMENTATION GUIDELINES The unlock operation simply consists in posting a semaphore 410 D 2 9 USBD_HID_OS OutputDataPend Wait for Output report data read completion FILES usbd_hid_os c PROTOTYPE void USBD HID OS OutputDataPend CPU_INTO8U class nr CPU _INT16U timeout ms USBD ERR p err ARGUMENTS class_nbr Class instance number timeout ms Signal wait timeout in milliseconds p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE OS error code s relevant to failure s CALLERS USBD HID Rd IMPLEMENTATION GUIDELINES The wait operation typically consists of pending on a semaphore When the output report transfer is complete the task is woken up by the Core layer internal task responsible for asynchronous communication The p err argument should be assigned as described in Table D 2 411 Appendix D Operation result Error code to assign No error USBD_ERR_NONE Pend aborted USBD_ERR_OS_ ABORT Pend failed for any other reason USBD_ERR_OS FAIL Table D 4 p_err assignment according to the pend operation result 412 D 2 10 USBD_HID_OS OutputDataPendAbort Abort the wait for Output report data read completion FILES usbd_hid_os c PROTOTYPE void USBD HID OS OutputDataPendAbort CPU_INTO8U class_nbr ARGUMENTS class nbr_ Class instanc
310. r better performance or for smallest code size by configuring USBD_CFG_OPTIMIZE_SPD DEF_ENABLED Optimizes pC USB Device for best speed performance DEF_DISABLED Optimizes pC USB Device for best binary image size USBD_CFG_MAX_NBR_DEV USBD_CFG MAX NBR_DEV configures the maximum number of devices This value should be set to the number of device controllers used on your platform Default value is 1 5 1 2 USB DEVICE CONFIGURATION USBD_CFG_MAX_NBR_CFG USBD_CFG MAX NBR CFG sets the maximum number of USB configurations used by your device Keep in mind that if you use a high speed USB device controller you will need at least two USB configurations one for low and full speed and another for high speed Refer to the Universal Serial Bus specification Revision 2 0 section 9 2 3 for more details on USB configuration Default value is 2 5 1 3 INTERFACE CONFIGURATION USBD_CFG_MAX_NBR_IF USBD_CFG MAX NBR_IF configures the maximum number of interfaces available This value should at least be equal to USBD_CFG MAX NBR_CFG and greatly depends on the USB class es used Each class instance requires at least one interface while CDC ACM requires two Refer to the Universal Serial Bus specification Revision 2 0 section 9 2 3 for more details on USB interfaces Default value is 2 66 Static Stack Configuration USBD_CFG_MAX_NBR_IF_ALT USBD_CFG MAX NBR_IF_ ALT defines the maximum number of alternate interfaces alternate setting
311. rd deviation The monitor will also show the data and opaque data that you specified At startup the application will always send a default item with a periodicity of 100 ms This item will send the device CPU usage and the value of a counter that is incremented each time the item is sent The default item uses low latency good reliability as QoS Figure 11 5 shows the demo application at startup 8 C PHDC exe PHDC MONITOR Items Latency Reliability Period Mean Opaque data data WER lt ms gt Cb Low Good 166 166 Counter CPU Bus usage 6 661 to add a new item 2 to exit Figure 11 5 Demo Application at Startup At this point you have the possibility to add a new item by pressing 1 You will be prompted to specify the following values P Periodicity of the transfer E QoS Latency reliability of the transfer E Opaque data Cif QoS is not low latency good reliability E Data 202 Porting PHDC to a RTOS Figure 11 6 shows the demo application with a few items added o m3 CAPHDC exe PHDC MONITOR Latency Reliability Period Mean Opaque data data Cms Cms lt bytes gt Low Good 166 166 a Counter 2074 CPU 4 Low Good 16 10 Low latency data Medium Good 100 100 Item 2 Medium latency data Medium latency data Medium latency data d Le Medium Better 166 166 Item 3 Medium Best 166 166 Item 4 High Best 1000 1001 Item 5 Very high Best 4600 4606 Item 6 Hi
312. read is in charge of informing the application about a completed asynchronous IN transfer Upon completion of an asynchronous transfer the thread is waken up and calls the application callback provided to USBDev_APT library using the callback argument USBDev_APTI library allows to queue several asynchronous IN transfers for the same pipe 525 Appendix G 526 Appendix Error Codes This appendix provides a brief explanation of pC USB Device error codes defined in usbd_core h Any error codes not listed here may be searched in usbd_core h for both their numerical value and usage Each error has a numerical value The error codes are grouped The definition of the groups are Error code group Numbering series GENERIC 0 DEVICE 100 CONFIGURATION 200 INTERFACE 300 ENDPOINT 400 OS LAYER 500 527 Appendix H H 1 GENERIC ERROR CODES 0 USBD_ERR_NONE No error 1 USBD_ERR_SHORT_XFER Short transfer detected 2 USBD_ERR FAIL Hardware error occurred 3 USBD_ERR_RX Generic receive error A problem has occurred during read transfer preparation or after data has been received 4 USBD_ERR_TX Generic transmit error A problem has occurred during write transfer preparation No data transmitted or data transmitted with a certain problem 5 USBD_ERR_ALLOC Object memory allocation failed 6 USBD_ERR_NULL_PTR Pointer argument s passed NULL pointer s 7 USBD_ERR_INVALID_ARG Invalid argum
313. reamble should always be called before USBD_PHDC_Rd if metadata message preambles are enabled by the host Application should then call USBD_PHDC_Rd p_nbr xfer times If host disable preamble while application is pending on this function the call will immediately return with error USBD_OS_ERR_ ABORT 455 Appendix F F 1 9 USBD_PHDC RO Read PHDC data This function is blocking FILES usbd_phdc h usbd_phdc c PROTOTYPE CPU_INTO8U USBD_PHDC_Rd CPU_INTO8U class_nbr ARGUMENTS class obt p_buf buf_len timeout p_err 456 void p buf CPU_INT16U buf len CPU_INT16U timeout USBD_ERR p err PHDC instance number Pointer to buffer that will contain opaque data from metadata message preamble Opaque data buffer length in octets Timeout in milliseconds Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_ INVALID CLASS STATE USBD_ERR_INVALID ARG USBD_ERR NULL PTR USBD_ERR_RX USBD_ERR DEV INVALID NBR USBD_ERR_EP INVALID NBR USBD_ERR DEV INVALID STATE USBD_ERR_EP INVALID TYPE USBD_OS ERR TIMEOUT USBD_OS ERR ABORT USBD_OS ERR FAIL RETURNED VALUE Number of octets received if no error s 0 otherwise CALLERS Application NOTES WARNINGS USBD_PHDC Rd should always be called after USBD_PHDC RdPreamble if metadata message preambles are enabled by the host Application should ensure that the length of the buffer
314. received by the serial task and sent back to the host The serial task can receive a maximum of 512 characters m Micrium CDC Serial Demo HyperTerminal File Edit Vie View Call Transfer Help De 28 f USB CDC ACH Serial Emulation Demo 1 Echo 1 demo 2 Echo N demo Option Connected 0 00 33 Auto detect 2400 8 N 1 NUM Figure 8 5 CDC Serial Demo Menu in HyperTerminal To support the two demos the serial task implements a state machine as shown in Figure 8 6 Basically the state machine has two paths corresponding to the user choice in the serial terminal menu Figure 8 6 Serial Demo State Machine 133 Chapter 8 F8 6 1 F8 6 2 F8 6 3 Once the DTR signal has been received the serial task is in the MENU state If you choose the menu option 1 the serial task will echo back any single character sent by the serial terminal as long as Ctrl C is not pressed If you choose the menu option 2 the serial task will echo all the received characters sent by the serial terminal as long as Ctrl C is not pressed Table 8 10 shows four possible serial terminals which you may use to test the CDC ACM class Terminal DTR set clear Menu option s usable HyperTerminal Yes properly set DTR signal automatically sent upon COM port 1and2 opening Hercules Yes a checkbox in the GUI allows you to set clear DTR 1 and2 RealTerm Yes Set Clear DTR buttons in the
315. red Transfer does not complete in the period specified by timeout_ms E If end of transfer is set and transfer length is multiple of maximum packet size a zero length packet is transferred to indicate a short transfer to the host 272 A 4 7 USBD_BulkTxAsync Receives data on bulk OUT endpoint asynchronously FILES usbd_core h usbd_core c PROTOTYPE void USBD_BulkTxAsync CPU_INT08U dev_nbr CPU_INTO8U ep_addr void p buf CPU_INT32U buf_len USBD_ASYNC_FNCT async_fnct void p_async_ arg CPU_BOOLEAN end USBD_ERR p err ARGUMENTS dev_nbr Device number ep_addr Endpoint address p buf Pointer to buffer of data that will be transmitted buf len Number of octets to transmit async_fnct Function that will be invoked upon completion of transmit operation p_async_arg Pointer to argument that will be passed as parameter of async_fnct end End of transfer flag see Note 2 p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_ DEV INVALID NBR USBD_ERR_ DEV INVALID STATE 273 Appendix A USBD_ERR_EP INVALID ADDR USBD_ERR_ EP INVALID STATE USBD_ERR_EP INVALID TYPE USBD_ERR_OS TIMEOUT USBD_ERR_OS ABORT USBD_ERR_OS FAIL RETURNED VALUE None CALLERS USB device class drivers NOTES WARNINGS P The callback specified by async_fnct has the following prototype void USB_AsyncFnct CPU_INTO8U dev_nbr Argument s dev_nbr ep_ad
316. rface Device HID Class configuration is presented in Table I 5 and its associated memory footprint table is shown in Table I 6 Note that there is an optional Interrupt OUT endpoint that you may add during HID initialization that has been omitted in the configuration below Also note that the Data size shown for HID class does not take into account memory allocated for input report buffer s output report and feature report buffers from the heap You can use memory functions from uC LIB to determine the amount of heap that has been allocated for these HID reports Refer to wC LIB documentation for more information Configuration Value USBD_CFG MAX NBR_IF 1 USBD_CFG MAX NBR_IF ALT 1 USBD_CFG MAX NBR_IF GRP 0 USBD_CFG MAX NBR_EP DESC 1 USBD_CFG MAX NBR_EP OPEN 3 USBD_HID CFG MAX NBR DEV 1 USBD_HID CFG MAX NBR CFG 2 USBD_HID CFG MAX NBR_REPORT_ID 16 USBD_HID CFG MAX NBR_REPORT PUSHPOP 0 Table l 5 HID Configuration for Memory Footprint 533 Appendix Module Code kB Constant kB Data kB Device Core 19 17 0 78 Device RTOS Port 0 76 1 31 Device Controller 6 74 0 21 Data allocated from heap Driver HID 6 29 0 52 Input Output and or Feature Report buffers allocated from heap Refer to section I 0 2 Human Interface Device Class on page 533 for details HID RTOS Port 1 05 1 39 Total 34 01 0 21 4 00 l 0 3 MASS STORAGE CLASS The Mass Storage Cl
317. rimary Commands documentation for the full command description REQUEST SENSE Requests a structure containing sense data Refer to SCSI Primary Commands documentation for the full command description PREVENT ALLOW MEDIA REMOVAL Requests the device to prevent or allow users to remove the storage media from the device Refer to SCSI Primary Commands documentation for the full command description Table 10 3 SCSI Commands 170 RTOS Layer 10 2 3 STORAGE LAYER AND STORAGE MEDIUM The storage layer is the interface between the pC USB MSC Device and the file system storage medium The storage layer is responsible of initializing reading and writing to the storage medium as well as obtaining information regarding its capacity and status By default Micrium will provide a storage layer implementation named RAMDisk by utilizing the hardware s platform memory as storage medium Aside from this implementation you have the option to use Micrium s uC FS or even utilize a file system storage medium of your own In the event you use a file system storage medium of your own you will need to create a storage layer port to communicate your storage medium to the pC USB MSC Device Please refer to section 10 6 Porting MSC to a Storage Layer on page 180 to learn how to implement this storage layer 10 3 RTOS LAYER MSC device communication relies on a task handler that implements the MSC protocol This task handler needs to be notifie
318. rity 106 Class Instance Concept USBD_ERR err CPU_INTO8U class_0 CPU_INTO8U class_1 USBD_XXXX_Init amp err 1 class_0 USBD_XXXX_Add err 2 class_1 USBD_XXXX_Add err 3 USBD_XXXX_CfgAdd class_0 dev_nbr cfg_0 amp err 4 USBD_XXXX_CfgAdd class_1 dev_nbr cfg_0 amp err 5 USBD_XXXX_CfgAdd class_0 dev_nbr cfg_1 amp err 6 USBD_XXXX_CfgAdd class_1 dev_nbr cfg_1 amp err 6 Listing 7 4 Multiple Class Instances FS Device 2 Configurations and Multiple Interfaces Code L7 4 1 Initialize the class Any internal variables structures and class RTOS port will be initialized L7 4 2 Create the class instance class_0 The function USBD_XXXX_Add allocates a class control structure associated to class_0 L7 4 Create the class instance class_1 The function USBD_XXXX_Add allocates another class control structure associated to class_1 L7 4 4 Add the class instance class_0 to the configuration cfg_0 USBD_XXXX_CfgAdd will create the interface 0 interface 1 alternate interfaces and the associated endpoints IN and OUT The class instance number class_0 will be used for any data communication on interface 0 or interface 1 L7 4 5 Add the class instance class_1 to the configuration cfg_0 USBD_XXXX_CfgAdd will create the interface 2 interface 3 and their associated endpoints IN and OUT The class instance number class_1 will be used for any data communication on
319. rium s vendor class in its second configuration See Figure 5 2 for a graphical description of this USB device 74 E e High speed USB device Configuration Examples p R BW 2 Communication Interrupt INN is _ E Bulk OUT N ag N k D BW U endpoint _ Data interface A 7 y Bulk IN gt Wa EE endpoint _ EES CDC ACM class instance 1 Full speed 3 configuration A ee es Interrupt IN N is end oint y HD N atl P a S interface Ce High speed EN Po g OUT configuration endpoint Ig ef SS dh int _ GE HID class instance Configuration 1 WW S Communication E interrupt i 8 interface N endpoint a L EE E Bulk OUT Leen Deg LY Data Interface I SS aa Bulk IN gt e y e Full Ge CDC ACM class instance 2 keau H 0 P Bulk IN 5 enol e Eug High speed Lage _ configuration Bulk OUT N WS ege d p D kickt Configuration 2 A Vendor he interface i GEN Dsg eg endpoint P nterrupt OUT KEE Vendor class instance Endpoint is optional Figure 5 2 Complex Composite High Speed USB Device Structure 75 Chapter 5 Configuration Value Explanation USBD_CFG MAX NBR_CFG 4 Two configurations for full ow speed and two others for high speed USBD_CFG MAX NBR_IF 7 First configuration
320. rmation on the debug and trace module see Chapter 13 Debug and Trace on page 231 63 Chapter 4 64 Chapter Configuration Prior to usage uC USB Device must be properly configured There are three groups of configuration parameters P Static stack configuration E Application specific configuration E Device and device controller driver configuration This chapter explains how to setup all these groups of configuration The last section of this chapter also provides examples of configuration following examples of typical usage 5 1 STATIC STACK CONFIGURATION pC USB Device is configurable at compile time via approximately 20 defines in the application s copy of usbd_cfg h uC USB Device uses defines when possible because they allow code and data sizes to be scaled at compile time based on enabled features and the configured number of USB objects This allows the Read Only Memory ROM and Random Access Memory RAM footprints of uC USB Device to be adjusted based on application requirements It is recommended that the configuration process begins with the recommended or default configuration values which in the next sections will be shown in bold The sections in this chapter are organized following the order in upC USB Device s template configuration file usbd_cfg h 65 Chapter 5 5 1 1 GENERIC CONFIGURATION USBD_CFG_OPTIMIZE SPD Selected portions of pC USB Device code may be optimized for eithe
321. rom the host Self powered devices are in the Powered state after port attachment Default After the device has been powered it should not respond to any request or transactions until it receives a reset signal from the host The device enters in the Default state when it receives a reset signal from the host In the Default state the device responds to standard requests at the default address 0 Address During enumeration the host assigns a unique address to the device When this occurs the device moves from the Default state to the Address state 24 Device Structure and Enumeration Device States Description Configurated After the host assigns an address to the device the host must select a configuration After the host selects a configuration the device enters the Configured state In this state the device is ready to communicate with the host applications Suspended The device enters in Suspended state when no traffic has been seen in the bus for a specific period of time The device retains the address assigned by the host in the Suspended state The device returns to the previous state after traffic is present in the bus Table 1 2 USB Device States 1 4 3 ENUMERATION Enumeration is the process where the host configures the device and learns about the device s capabilities The host starts enumeration after the device is attached to one of the root or external hub ports The host learns about the device
322. rted in the current implementation The CDC base class enables you to have several DCIs along with the CCI The application can communicate with the host using the communication API offered by the CDC subclass 119 Chapter 8 8 3 CONFIGURATION 8 3 1 GENERAL CONFIGURATION Some constants are available to customize the CDC base class These constants are located in the USB device configuration file usbd_cfg h Table 8 3 shows their description Constant Description USBD_CDC_CFG MAX NBR_DEV Configures the maximum number of class instances Each associated subclass also defines a maximum number of subclass instances The sum of all the maximum numbers of subclass instances must not be greater than USBD_CDC_CFG MAX NBR_DEV USBD_CDC_CFG MAX NBR_CFG USBD_CDC_CFG MAX NBR DATA IF Configures the maximum number of configurations in which CDC class is used Keep in mind that if you use a high speed device two configurations will be built one for full speed and another for high speed Configures the maximum number of Data interfaces The minimum value is 1 Table 8 3 CDC Class Configuration Constants Listing 8 1 shows the App USBD_CDC_Init function defined in the application template file app_usbd_cdc c This function performs CDC and associated subclass initialization CPU_BOOLEAN App USBD_CDC Init CPU_INTO8U deu par USBD_ERR err USBD_CDC_Init amp err 120 CPU_INTO8U cfg_hs CPU_INTO8U cf
323. rwise it waits until another task releases the semaphore p err argument should be assigned as described in Table D 5 Operation result Error code to assign No error USBD_ERR_NONE Pend aborted USBD_ERR_OS_ABORT Pend failed for any other reason USBD_ERR_OS FAIL Table D 5 p_err assignment according to the pend operation result 415 Appendix D D 2 13 USBD_HID_OS TxUnlock Unlock class transmit FILES usbd_hid_os c PROTOTYPE void USBD HID OS TxUnlock CPU_INTO8U class_nbr ARGUMENTS class nbr_ Class instance number CALLERS USBD_HID Wr USBD_HID WrAsync IMPLEMENTATION GUIDELINES The unlock operation simply consists in posting a semaphore 416 D 2 14 USBD_HID_OS TmrTask Process periodic input reports according to idle duration set by the host with the SET_IDLE request FILES usbd_hid_os c PROTOTYPE static void USBD_HID OS TmrTask void p arg ARGUMENTS p arg Pointer to task initialization argument CALLERS This is a task IMPLEMENTATION GUIDELINES The task body is usually implemented as an infinite loop The task should perform the following steps E Delay for 4 ms This delay corresponds to the 4 ms unit used to express the idle duration transported by the SET_IDLE request P Call USBD_HID_Report_TmrTaskHandler function defined in the HID parser module This function implements the periodic input reports processing 417 Appendix D 418 Appendi
324. s MS class PHDC power distribution 0 0 2 eee eeeeeeeeeeeeeeeeeaeeeaeeteeeeeeeeeaees power management preprocessor constants s processing USB requests 0 00 0 eee eee eee 61 62 Q QoS bins endpoint mapping levels description Ge QoS based schedule cccceccesseeeseeeseeeseeeesees 196 199 QoS based scheduler API 2 ceceeeeeeeeeeeeeeeeeeeeeeteae 198 R RAM disk EEN 177 receive asynchronous synchronous report ooo eee descriptor content items oo mouse state RTOS port QoS based scheduler S sample application building SCSI SCSI commands SemaphorePost serial demo state machine serial read and write Serial terminal AE SetBreak SetCommFeature SET_CONFIGURATION SET_CONTROL_LINE_STATE SetControlLineState A SET_FEATURE SET_IDLE SET INTERFACE EN 113 SET_LINE_CODING 132 SetLineCoding 122 127 SET_PROTOCOL SET_REPORT simple full speed USB device sl configuration source code downloading including speed state machine static stack configuration status notification API storage API storage layer functions storage medium String configuration 2 eee eeeeeeeeeeteeeeeeeeeeeeeeeeeeeeaeeeneeees subclass TE ln sessir eeevetis dapena siidi iaaa 127 NOTIFICATION E 127 subclass instance COMMUNICATION v 28 cis Beene 128 configuration synchronous bulk rea
325. s In this example the Collection Physical nested into the Collection Application is composed of the same 3 Input items forming the Collection Application The Collection Physical is used for a set of data items that represent data points collected at one geometric point In the example the suggested use is a pointer as indicated by the Usage item Here the pointer usage refers to the mouse position coordinates and the system software will translate the mouse coordinates in movement of the screen cursor Nested usage pages are also possible and give more details about a certain aspect within the general function of the device In this case two Inputs items are grouped and correspond to the buttons of the mouse One Input item defines the three buttons of the mouse right left and wheel in terms of number of data fields for the item Report Count item size of a data field Report Size item and possible values for each data field Usage Minimum and Maximum Logical Minimum and Maximum items The other Input item is a 13 bit constant allowing the Input report data to be aligned on a byte boundary This Input item is used only for padding purpose Another nested usage page referring to a generic desktop control is defined for the mouse position coordinates For this usage page the Input item describes the data fields corresponding to the x and y axis as specified by the two Usage items Overview After analyzing the previous mouse Report d
326. s available This value should at least be equal to USBD_CFG_MAX NBR_IF Refer to the Universal Serial Bus specification Revision 2 0 section 9 2 3 for more details on alternate settings Default value is 2 USBD_CFG_MAX_NBR_IF_GRP USBD_CFG MAX NBR TE CRP sets the maximum number of interface groups or associations available For the moment Micrium offers only one USB class CDC ACM that requires interface groups Refer to the Interface Association Descriptors USB Engineering Change Notice for more details about interface associations Default value is 0 should be equal to the number of instances of CDC ACM USBD_CFG_MAX_NBR_EP_DESC USBD_CFG MAX NBR ER DESC sets the maximum number of endpoint descriptors available This value greatly depends on the USB class es used For information on how many endpoints are needed for each class refer to the class specific chapter Keep in mind that control endpoints do not need any endpoint descriptors Default value is 2 USBD_CFG_MAX_NBR_EP_OPEN USBD_CFG MAX NBR_EP OPEN configures the maximum number of opened endpoints per device If you use more than one device set this value to the worst case This value greatly depends on the USB class es used For information on how many endpoints are needed for each class refer to the class specific chapter Default value is 4 2 control plus 2 other endpoints 5 1 4 STRING CONFIGURATION USBD_CFG_MAX_NBR_STR USBD_CFG MAX NBR STR configur
327. s active and proceed to add the ACM subclass instance to this configuration Check if the full speed configuration is active and proceed to add the ACM subclass instance to this configuration Listing 8 2 also illustrates an example of multiple configurations The functions USBD_ACM SerialAdd and USBD_ACM SerialCfgAdd allow you to create multiple configurations and multiple instances architecture Refer to section 7 1 Class Instance Concept on page 99 for more details about multiple class instances 126 8 4 4 SUBCLASS NOTIFICATION AND MANAGEMENT You have access to some functions provides in the ACM subclass which relate to the ACM requests and the serial line state previously presented in section 8 4 1 Overview on page 121 Table 8 7 shows these functions Refer to section C 2 CDC ACM Subclass ACM Subclass Functions on page 369 for more details about the functions parameters Function Relates to Description USBD_ACM SerialLineCodingGet SetLineCoding Application can get the current line coding settings set either by the host with SetLineCoding requests or by USBD_ACM SerialLineCodingSet USBD_ACM SerialLineCodingSet USBD_ACM SerialLineCodingReg GetLineCoding SetLineCoding Application can set the line coding The host can retrieve the settings with the GetLineCoding request Application registers a callback called by the ACM subclass upon reception of the
328. s function sets alternate setting number for WinUSB internal use It does not send a SET_INTERFACE request to the device To send SET_INTERFACE request to the device the function USBDev_CtrlReq must be used 505 Appendix G G 2 7 USBDev_GetCurAltSetting Get the current alternate setting for the specified interface FILES usbdev_api c PROTOTYPE UCHAR USBDev_GetCurAltSetting HANDLE dev UCHAR if_nbr DWORD p err ARGUMENTS dev General handle to device if_nbr Interface number p err Pointer to variable that will receive the return error code from this function ERROR_SUCCESS ERROR INVALID HANDLE ERROR INVALID PARAMETER RETURNED VALUE Current alternate setting number if NO error s 0 otherwise CALLERS Application 506 NOTES WARNINGS This function gets the current alternate setting number used internally by WinUSB and set by the function USBDev_SetAltSetting It does NOT send a GET_INTERFACE request to the device To send GET_INTERFACE request to the device the function USBDev_Ctr1Req must be used 507 Appendix G G 2 8 USBDev_IsHighSpeed Specify if the device attached to PC is high speed or not FILES usbdev_api c PROTOTYPE BOOL USBDev IsHighSpeed HANDLE dev DWORD p err ARGUMENTS dev General handle to device p err Pointer to variable that will receive the return error code from this function ERROR_SUCCESS ERROR INVALID HANDLE ERROR INVALID PAR
329. s stored p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_SCSI_MEDIUM NOTPRESENT RETURNED VALUE None CALLERS USBD_SCSI_WrData 437 Appendix E NOTES WARNINGS None 438 E 3 5 USBD_StorageStatusGet Get the presence of the storage medium FILES usbd_storage h usbd_storage c PROTOTYPE void USBD StorageStatusGet USBD STORAGE LUN ap storage lun USBD_ERR p err ARGUMENTS p storage lun Pointer to logical unit storage structure p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_SCSI_MEDIUM NOTPRESENT USBD_ERR_SCSI_MEDIUM NOT bm TO RDY USBD_ERR_SCSI_MEDIUM RDY TO NOT RDY RETURNED VALUE None CALLERS USBD_SCSI_IssueCmd NOTES WARNINGS None 439 Appendix E 440 Appendix PHDC API Reference This appendix provides a reference to the Personal Healthcare Device Class PHDC API Each user accessible service is presented following a category order i e initialization communication and RTOS layer categories The following information is provided for each of the services A brief description The function prototype The filename of the source code A description of the arguments passed to the function A description of returned value s Specific notes and warnings regarding use of the service 441 Appendix F F 1 PHDC F
330. s supported by wC USB Device implements the SCSI transparent command set using the BOT protocol only which signifies that only bulk endpoints will be used to transmit data and status information 165 Chapter 10 10 1 OVERVIEW 10 1 1 MASS STORAGE CLASS PROTOCOL The MSC protocol is composed of three phases E The Command Transport E The Data Transport P The Status Transport Mass storage commands are sent by the host through a structure called the Command Block Wrapper CBW For commands requiring a data transport stage the host will attempt to send or receive the exact number of bytes from the device as specified by the length and flag fields of the CBW After the data transport stage the host attempts to receive a Command Status Wrapper CSW from the device detailing the status of the command as well as any data residue Gf any For commands that do not include a data transport stage the host attempts to receive the CSW directly after CBW is sent The protocol is detailed in Figure 10 1 g 3 gt Ready lt d a Command Transport CBW Data Out from Host Data In to Host WS Status Transport CSW Figure 10 1 MSC Protocol 166 10 1 2 ENDPOINTS On the device side in compliance with the BOT specification the MSC is composed of the following endpoints E A pair of control IN and OUT endpoints called default endpoint A p
331. s_nbr USBD_ACM SERIAL LINE CODING p line coding USBD_ERR p err ARGUMENTS subclass obt CDC ACM serial emulation subclass instance number p_line coding Pointer to the structure where the current line coding will be stored p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_INVALID ARG USBD_ERR_ NULL PTR RETURNED VALUE None CALLERS Application NOTES WARNINGS None 381 Appendix C C 2 10 USBD_ACM_SerialLineCodingSet Set a new line coding FILES usbd_acm_serial h usbd_acm_serial c PROTOTYPE void USBD_ACM SerialLineCodingSet CPU_INTO8U subclass_nbr USBD_ACM SERIAL LINE CODING p line coding USBD_ERR p err ARGUMENTS subclass obt CDC ACM serial emulation subclass instance number p_line coding Pointer to the structure where that contains the new line coding p_err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_INVALID ARG USBD_ERR NULL PTR RETURNED VALUE None CALLERS Application NOTES WARNINGS None 382 C 2 11 USBD_ACM_SerialLineCodingReg Register line coding change notification callback FILES usbd_acm_serial h usbd_acm_serial c PROTOTYPE void USBD_ACM SerialLineCodingReg CPU_INTO8U subclass_nbr USBD_ACM SERIAL LINE CODING CHNGD line_coding_chngd void p arg USBD_ERR p err ARGUMENTS subclass obt CDC ACM serial emulation
332. scriptor Analyzing the content is done by a parser The Report descriptor describes the data provided by each control in a device It is composed of items An item is a piece of information about the device and consists of a 1 byte prefix and variable length data Refer to Device Class Definition for Human Interface Devices HID Version 1 11 section 5 6 and 6 2 2 for more details about the item format There are three principal types of items E Main item defines or groups certain types of data fields E Global item describes data characteristics of a control Local item describes data characteristics of a control Each item type is defined by different functions An item function can also be called an item An item function can be seen as a sub item that belongs to one of the 3 principal item types Table 9 2 gives a brief overview of the item s functions in each item type For a complete description of the items in each category refer to Device Class Definition for Human Interface Devices HID Version 1 11 section 6 2 2 Item type Item function Description Main Input Describes information about the data provided by one ore more physical controls Output Describes data sent to the device Feature Describes device configuration information sent to or received from the device which influences the overall behavior of the device or one of its components Collection Group related items Input Output or Feat
333. se you have to develop it yourself yC USB Device Vendor Class Optional Available only if you purchased Vendor class yC USB Device MSC Optional Available only if you purchased Mass Storage Class MSC yuC USB Device HID Class Optional Available only if you purchased Human Interface Device HID class yuC USB Device CDC ACM Optional Available only if you purchased Communication Device Class CDC with the Abstract Control Model ACM subclass yC USB Device PHDC Optional Available only if you purchased Personal Healthcare Device Class PHDC uC CPU Core YES yuC CPU Port YES Available only if Micrium has support for your target architecture ARM AVR32 MSP430 etc yC LIB Core YES Micrium run time library yC LIB Port Optional Available only if Micrium has support for your target architecture ARM AVR32 MSP430 etc yuC OS II Core Optional Available only if your application is using uC OS II yC OS II Port Optional Available only if Micrium has support for your target architecture ARM AVR32 MSP430 etc yuC OS III Core Optional Available only if your application is using uC OS III yC OS III Port Optional Available only if Micrium has support for your target architecture ARM AVR32 MSP430 etc Table 2 1 uC USB Device Module Dependency Table 2 1 indicates that all the uC USB Device classes are optional because there is no mandatory class to purchase with the pC USB Device Core and Driver The class you will have p
334. seeeceeeeseeeeeeessaeeeeesneaeeeeeeseaaeeeeenenees 511 Table of Contents G 2 12 G 2 13 G 2 14 G 2 15 G 2 16 G 2 17 G 2 18 G 2 19 G 2 20 Appendix H H 1 H 2 H 3 H 4 H 5 H 6 Appendix I l 0 1 1 0 2 1 0 3 1 0 4 1 0 5 USBDev_IntrOut_Open c ccccessssceeeesseeeceeeeseeeeeeeeeseaeeeeesseaeeeeeeneaes 512 USBDev_PipeGetAdd lr cccccccecceseeeseeeeceeeeeeeeeseseeeeeesseeneeeeeeeeeeees 513 USBDev PipeClose f asoini a a aa AARE RAA 514 USBD y PipeSt ll i iii enai aaan aeaaea danaa ainda aaa iadaa inaia waada 515 USBDev PipeAbort sis vcsssccsece cece cetvecsceveascnaecetteae cee ceeveesvnastucteciecreuezeens 516 USBDev CtrlReg EE 517 USBDev Pipe Wri a irenstean eii aaaeeeaa KENEN AAA Naa ANEA 520 USBDev PipeRd gees ee EE E ENEE SEENEN niaaa 522 USBDev_PipeRGASynC cccccesseccceeesseeeeeeesseeeeeeeesaeeeesnesnaeeeeenseaes 524 Error GOdeS e a E eck ce ceesk he svacave hontai th cacti AT 527 Generic Error COGS cescessceeeeeeeee cece eee eenenesseaeeeeeeeeeeeeeeseeeeesseeneeees 528 Device Error COdeS isisisi niine inaakusahan SEENEN ven 528 Configuration Error Codes ccccccecceseeeeeeeeeeneeeeeeeeeeeeeeeeeeesseeaneeees 528 Interface Error Goes areeni aaaea ea een aea reana aka Eea aaa ar EEan 529 Endpoint Error Codes ccccececeeeeeeeeseeeeeeeeeeeeeeeeeeeeseeeseeeneeeeeeeenees 529 OS Layer Error Codes aisina aet aeaa iste hte aiaa aiae aan EE ia 529 Memory Foo
335. sents the execution T 5 C Micrium Software uC USB Device V4 App Host OS Windows Vendor Visual Studio 2010 exe x ES umber of devices attached 1 Device 1 open Device 1 WinUSB internal alternate setting set Device 1 1 interface s gt default IF associated interfaces Device 1 attached is FULL SPEED Device 1 CIF gt Bulk IN pipe open Device 1 IF gt Bulk OUT pipe open Sending Receiving bytes 0OK Sending Receiving bytes OK Sending Receiving bytes 0OK Sending Receiving bytes 0OK Sending Receiving bytes 0OK Sending Receiving bytes OK Sending Receiving bytes Sending Receiving bytes Sending Receiving bytes Sending Receiving 10 bytes 0OK gt Device 1 CIF gt communication successful Do you want to continue CYES y or Y NO n or ND y gt Specify the number of transfers 2545 Figure 12 5 Demo Application Execution Single Device The demo will propose to do a new execution Figure 12 5 shows the example of a single device with 1 vendor interface The demo is able to communicate with each vendor interface in the case of a composite device In that case the demo will open bulk IN and OUT pipes for each interface You will be asked the maximum number of transfers for each interface composing the device Figure 12 6 shows an example of composite device 227 Chapter 12 Number of devices attached 1 gt gt Device 1 open g
336. sesseeeeeeeeeeees 61 Processing Debug Events ccccccecceeeeeseeeeeeneeeeeeeeeseeeeesseaneeeeeeeeeees 63 COMTI ATION EE 65 Static Stack Configuration c ecceeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeneeees 65 Generic Configuration ccccccseeeeceeeesneeceeeesneeeseeeeseeeeeeeeeseeeseeseseeneeeeessees 66 USB Device Configuration ssssnsusssnunnennnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn nnmnnn na 66 Interface Conftouration REENEN EEN EEEEEE En 66 tee elle UTC e E 67 Debug Configuration cccseecccessseeeceeeseeeeeesessneeeeesessneeeeesesneeesesessneees 68 Communication Device Class CDC Configuration ees 68 CDC Abstract Control Model ACM Serial Class Configuration 68 Human Interface Device HID Class Configuration en 68 Mass Storage Class MSC Configuration ccccesseesseeseeneeeeeeeeeeees 69 Personal Healthcare Device Class PHDC Configuration 69 Vendor Class Configuration ccccceecceseseneeeeeeeeeeeeeeseeeeeeneaseeeeeeneeeeees 69 Application Specific Configuration ENEE 69 PASK ten Heger dee ee E A Een 69 TASK SACK EE 70 Device and Device Controller Driver Configuration s eccesseeeeee 71 Configuration Examples cecceeceeeeeeeeeeeeeeeeaneeeeeeeeeeeeseeeeeeeeeeneeees 71 5 4 1 5 4 2 5 4 3 Chapter 6 6 1 6 2 6 3 6 4 6 4 1 6 4 2 6 4 3 6 4 4 6 4 5 6 5 6 5 1 6 6 6 7 6 8 6 8 1 6 8 2 6 8 3 6 8 4 6 8 5 Chapter 7 7 1 7 2 7 3
337. soft s MSDN online documentation at http msdn microsoft com en us library f 540207 v VS 85 aspx 12 3 1 DEVICE AND PIPE MANAGEMENT USBDev_API offers the following functions to manage a device and its function s pipes Function name Operation USBDev_GetNbrDev Gets number of devices belonging to a specified Globally Unique IDentifier GUID and connected to the host Refer to section 12 4 4 GUID on page 228 for more details about the GUID USBDev_Open Opens a device USBDev_Close Closes a device USBDev_BulkIn Open Opens a bulk IN pipe USBDev_BulkOut_Open Opens a bulk OUT pipe USBDev_IntIn_Open Opens an interrupt IN pipe USBDev_IntOut_Open Opens an interrupt OUT pipe USBDev_PipeClose Closes a pipe Table 12 5 USBDev_API Device and Pipe Management API 215 Chapter 12 Listing 12 4 shows an example of device and pipe management The steps to manage a device typically consist in E Opening the vendor device connected to the host E Opening required pipes for this device E Communicating with the device via the open pipes P Closing pipes P Closing the device HANDLE dev_handle HANDLE bulk_in handle HANDLE bulk _out_handle DWORD err DWORD nbr dev nbr dev USBDev_GetNbrDev USBDev_GUID amp err 1 if err ERROR SUCCESS Handle the error dev_handle USBDev_Open USBDev_ GUID 1 amp err 2 if dev_handle INVALID_HANDLE
338. some processing else Handle the error static void App _USBD_Vendor_TxCmpl CPU_INTO8U void CPU_INT32U CPU_INT32U void USBD_ERR void class_nbr void p buf void buf_len void xfer_len void p callback arg if err USBD ERR NONE Do some processing else Handle the error Configuration 3 class_nbr p buf buf_len xfer len p_callback_arg err 4 3 class_nbr p buf buf_len xfer len p_ callback arg err 4 Listing 12 3 Asynchronous Bulk Read and Write Example 213 Chapter 12 L12 3 1 The class instance number serves internally to the Vendor class to route the transfer to the proper bulk OUT or IN endpoint L12 3 2 Application must ensure that the buffer provided to the function is large enough to accommodate all the data Otherwise synchronization issues might happen L12 3 3 The application provides a callback passed as a parameter Upon completion of the transfer the device stack calls this callback so that the application can finalize the transfer by analyzing the transfer result For instance upon read operation completion the application may do a certain processing with the received data Upon write completion the application may indicate if the write was successful and how many bytes were sent L12 3 4 An argument associated to the callback can be also passed Then in the callback context some pri
339. ss instance class_0 The function USBD_XXXX_Add allocates a class control structure associated to class_0 Depending on the class besides the parameter for an error code USBD_XXXX Add may have additional parameters representing class specific information stored in the class control structure Add the class instance class_0 to the specified configuration number cfg_0 USBD_XXXX_CfgAdd will create the interface 0 and its associated endpoints IN and OUT Hence the class instance encompasses the interface 0 and its endpoints Any communication done on the interface 0 will use the class instance number class_0 Figure 7 2 represents an example of a high speed capable device The device can support High Speed HS and Full Speed FS The device will contain two configurations one valid if the device operates at full speed and another if it operates at high speed In each configuration interface 0 is the same but its associated endpoints are different The difference will be the endpoint maximum packet size which varies according to the speed 101 Chapter 7 If a high speed host enumerates this device by default the device will work in high speed mode and thus the high speed configuration will be active The host can learn about the full speed capabilities by getting a Device Qualifier descriptor followed by an Other_Speed_Configuration descriptor These two descriptors describe a configuration of a high speed capable de
340. ssociatedlF Get number of associated interfaces with the default interface That is all the interfaces besides the default interface managed by WinUSB sys and registered under the same GUID FILES usbdev_api c PROTOTYPE UCHAR USBDev_GetNbrAssociatedIF HANDLE dev DWORD p err ARGUMENTS dev General handle to device p err Pointer to variable that will receive the return error code from this function ERROR_SUCCESS ERROR INVALID HANDLE RETURNED VALUE Number of associated interfaces if NO error s 0 otherwise CALLERS Application NOTES WARNINGS Let s assume that a device has three interfaces managed by WinUSB sys driver and belonging to the same GUID Interface 0 1 and 2 Interface 0 is the default interface Interfaces 1 and 2 are the associated interfaces In that example calling USBDev_GetNbrAssociatedIF will return 2 associated interfaces 503 Appendix G G 2 6 USBDev_SetAltSetting Set the alternate setting of an interface FILES usbdev_api c PROTOTYPE void USBDev_SetAltSetting HANDLE dev UCHAR Lelio UCHAR alt_set DWORD p err ARGUMENTS dev General handle to device if_nbr Interface number alt_set Alternate setting number p err Pointer to variable that will receive the return error code from this function ERROR_SUCCESS ERROR INVALID HANDLE ERROR INVALID PARAMETER RETURNED VALUE None CALLERS Application 504 NOTES WARNINGS Thi
341. start reception and transmission of USB packets how to read and write USB packets how to report USB events to the core etc The USB device driver controller functions are encapsulated and implemented in the usbd_drv_ lt controller gt c file 57 Chapter 4 In order to have independent configuration for clock gating interrupt controller and general purpose I O a USB device controller driver needs an additional file This file is called a Board Support Package BSP The name of this file is usbd_bsp_ lt controller gt c This file contains all the details that are closely related to the hardware on which the product is used This file also defines the endpoints information table This table is used by the core layer to allocate endpoints according to the hardware capabilities 4 1 8 CPU LAYER uC USB Device can work with either an 8 16 32 or even 64 bit CPU but it must have information about the CPU used The CPU layer defines such information as the C data type corresponding to 16 bit and 32 bit variables whether the CPU has little or big endian memory organization and how interrupts are disabled and enabled on the CPU CPU specific files are found in the uC CPU directory and are used to adapt pC USB Device to a different CPU 4 2 TASK MODEL pC USB Device requires two tasks One core task and one optional task for tracing debug events The core task has three main responsibilities E Process USB bus events Bus events such
342. t gt Device 1 WinUSB internal alternate setting set gt gt Device 2 interfaceCs gt default IF 1 associated interface lt s gt gt gt Device attached is FULL SPEED 7 gt gt Device CIF gt Bulk IN pipe open gt gt Device CIF gt Bulk OUT pipe open Device CIF1i gt Bulk OUT pipe open OUT pipe open E C Micrium Software uC USB Device V4 App Host OS Windows Vendor Visual Studio 2010 exe x t gt Specify the number of transfers 1 bytes 0K 2 bytes 0K 3 bytes OK 4 bytes 0K 5 bytes 0K gt Device 1 IF gt communication successful gt Specify the number of transfer 1 bytes 0K 2 bytes OK 3 bytes 0K 4 bytes 0K 5 bytes 0K Steier A Device 1 IF1 gt communication successful Do you want to continue lt YES y or Y NO n or ND Figure 12 6 Demo Application Execution Composite Device 12 4 4 GUID A Globally Unique IDentifier GUID is a 128 bit value that uniquely identifies a class or other entity Windows uses GUIDs for identifying two types of devices classe Nn E Device setup class E Device interface class A device setup GUID encompasses devices that Windows installs in the same way and using the same class installer and co installers Class installers and co installers are DLLs that provide functions related to the device installation A device interface class GUID provides a mechanism for applications to co
343. t 0S Windows HID Visual Studio 2010 exe The two executables have been generated with a Visual Studio 2010 project available in Micrium Software uC USB Device V4 App Host 0S Windows HID Visual Studio 2010 E HID Control exe for the vendor specific demo utilizing the control endpoints to send Output reports or receive Input reports E HID Interrupt exe for the vendor specific demo utilizing the interrupt endpoints to send Output reports or receive Input reports Figure 9 4 presents the vendor specific demo with the host and device interactions 157 Chapter 9 F9 4 1 F9 4 2 F9 4 3 F9 4 4 158 Windows PC USB Device Host 1 Control menu 3 Read task Receive or Receive Output write reports report from to device Output report 2 Interrupt menu Input Report 4 Write task Receive or Send Input write reports report from to device Figure 9 4 HID Vendor Specific Demo A menu will appear after launching HID Control exe You will have three choices 1 Sent get report 2 Send set report and 3 Exit Choice 1 will send a GET_REPORT request to obtain an Input report from the device The content of the Input report will be displayed in the console Choice 2 will send a SET REPORT request to send an Output report to the device A menu will appear after launching HID Interrupt exe You will have three choices
344. t the device is in configured state and that the PHDC instance is ready for communication The following code illustrates a typical example CPU_BOOLEAN conn conn USBD_PHDC_IsConn class_nbr while conn DEF_YES OSTimeDlyHMSM 0 0 0 250 conn USBD_PHDC_IsConn class_nbr Once the connected status is DEF_YES the communication can start 447 Appendix F F 1 5 USBD_PHDC_RdCfg Initialize read communication pipe parameters FILES usbd_phdc h usbd_phdc c PROTOTYPE void USBD_PHDC_RdCfg CPU_INTO8U class_nbr LATENCY RELY FLAGS latency _rely CPU_INTO8U p data_opaque CPU_INTO8U data_opaque_len USBD_ERR EES ARGUMENTS class_nbr PHDC instance number latency_rely p_data_opaque data_opaque_len p_err 448 Bitmap of transfer latency reliability that this communication pipe will carry Can be one or more of these values USBD_PHDC_ LATENCY VERYHIGH RELY BEST USBD_PHDC LATENCY HIGH RELY BEST USBD_PHDC_ LATENCY MEDIUM RELY BEST Pointer to a buffer that contains opaque data related to this communication pipe Length of opaque data Gin octets If 0 no metadata descriptor will be written for the endpoint Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_ NULL PTR USBD_ERR_ INVALID ARG RETURNED VALUE None CALLERS Application NOTES WARNINGS USBD_PHDC_RdCfg should be called after USBD_PHDC_Init a
345. telephone network and Ethernet for local area network devices using a USB link A communication device is in charge of device management call management when needed and data transmission CDC defines seven major groups of devices Each group belongs to a model of communication which may include several subclasses Each group of devices has its own specification besides the CDC base class The seven groups are P Public Switched Telephone Network PSTN devices including voiceband modems telephones and serial emulation devices E Integrated Services Digital Network ISDN devices including terminal adaptors and telephones 115 Chapter 8 E Ethernet Control Model ECM devices including devices supporting the IEEE 802 family for instance cable and ADSL modems WiFi adaptors E Asynchronous Transfer Mode ATM devices including ADLS modems and other devices connected to ATM networks workstations routers LAN switches E Wireless Mobile Communications WMC devices including multi function communications handset devices used to manage voice and data communications E Ethernet Emulation Model EEM devices which exchange Ethernet framed data E Network Control Model NCM devices including high speed network devices High Speed Packet Access modems Line Terminal Equipment 8 1 OVERVIEW A CDC device is composed of several interfaces to implement a certain function that is communication capability It is formed by the
346. terrupt IN endpoint FILES usbd_core h usbd_ep c PROTOTYPE CPU_INT32U USBD_IntrTx CPU_INTO8U dev_nbr CPU_INTO8U ep_addr void p buf CPU_INT32U buf_len CPU_INT16U timeout_ms CPU_BOOLEAN end USBD_ERR p err ARGUMENTS dev_nbr ep_addr p_buf buf_len timeout me end p_err 282 Device number Endpoint address Pointer to buffer of data that will be transmitted Number of octets to transmit Timeout in milliseconds End of transfer flag see Note 2 Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR DEV INVALID NBR USBD_ERR DEV INVALID STATE USBD_ERR_EP INVALID ADDR USBD_ERR_EP INVALID STATE USBD_ERR_EP INVALID TYPE USBD_ERR_OS TIMEOUT USBD_ERR_OS ABORT USBD_ERR_OS FAIL RETURNED VALUE Number of octets transmitted If no error s 0 otherwise CALLERS USB device class drivers NOTES WARNINGS This function blocks until All data is transmitted or An error occurred Transfer does not complete in the period specified by timeout_ms m If end of transfer is set and transfer length is multiple of maximum packet size a zero length packet is transferred to indicate a short transfer to the host 283 Appendix A A 4 12 USBD_IntrTxAsync Receives data on interrupt OUT endpoint asynchronously FILES usbd_core h usbd_core c PROTOTYPE void USBD_IntrTxAsync CPU_INTO8U dev_nbr CPU_INT08U ep_addr void
347. the calls USBD_BulkTx USBD_CtrlTx and USBD IntrTx Figure 6 3 shows an overview of the device synchronous transmit operation USBD_EP_1x E 1 USBD_DrvEP_Tx 2 USBD_DrvEP_TxStart P Jo S SE Gees w EN 8 A USBD_EP_TxCmpl _ 6 ignal S P ia i e x Device ISR Handler A A Z USB Device ee Interrupt 4 Figure 6 3 Device Synchronous Transmit Diagram F6 3 1 The upper layer API s USBD_BulkTx USBD_Ctr1lTx and USBD_IntrTx call USBD_EP_Tx where USBD_DrvEP_Tx is invoked On DMA based controllers this device driver API is responsible for preparing the transmit transfer descriptor and returning the amount of data to transmit In case the DMA based controller requires the buffered data to be placed in a dedicated USB memory region the contents of the application buffer area must be transferred into the dedicated memory region On FIFO based controllers this device driver API is responsible for writing the amount of data to transfer into the FIFO and returning the amount of data to transmit 93 Chapter 6 F6 3 2 F6 3 3 F6 3 4 FO 3 5 F6 3 6 94 The USBD_DrvEP_TxStart API starts the transmit process On DMaA based controllers this device driver API is responsible for queuing the DMA transmit descriptor and enabling DMA transmit complete ISR s On FIFO based controllers this device driver API is res
348. thin the device API structure is the device Stop function This function is called once each time a device is stopped FILES Every device driver s usbd_drv c PROTOTYPE static void USBD DrvStop USBD_DRV p dreit ARGUMENTS p drv Pointer to USB device driver structure RETURNED VALUE None CALLERS USBD_DevStop via p drv_api gt Stop NOTES WARNINGS Typically the Stop function performs the following operations E Disable the controller P Clear and locally disable interrupts on the hardware device E Disconnect from the USB host e g reset the pull up on the D pin This is generally performed via the device s BSP function pointer Disconn implemented in usbd_bsp c see section B 2 3 on page 352 328 B 1 4 USBD_DrvAddrSet The next API function to implement is the device address set AddrSet function The device address set function is called while processing a SET_ADDRESS setup request FILES Every device driver s usbd_drv c PROTOTYPE static CPU_BOOLEAN USBD DrvAddrSet USBD_DRV p_drv CPU_INTO8U dev _addr ARGUMENTS p_drv Pointer to USB device driver structure dev_addr Device address assigned by the host RETURNED VALUE DEF_OK if NO error s DEF_FAIL otherwise CALLERS USBD_StdReqDev via p_drv_api gt AddrSet NOTES WARNINGS P For device controllers that have hardware assistance to enable the device address after the status stage has complet
349. this layer four classes defined by the USB IF are implemented In case you need to implement a vendor specific class a fifth class the vendor class is available This class provides functions for simple communication via endpoints The classes that uC USB Device currently supports are the following E Communication Device Class CDC CDC Abstract Control Model ACM subclass E Human Interface Device Class HID E Mass Storage Class MSC E Personal Healthcare Device Class PHDC E Vendor Class You can also create other classes defined by the USB IF Refer to Chapter 7 USB Classes on page 99 for more information on how a USB class interacts with the core layer 4 1 4 USB CORE LAYER USB core layer is responsible for creating and maintaining the logical structure of a USB device The core layer manages the USB configurations interfaces alternate interfaces and allocation of endpoints based on the application or USB classes requirements and the USB controller endpoints available Standard requests bus events reset suspend connect and disconnect and enumeration process are also handled by the Core layer 4 1 5 ENDPOINT MANAGEMENT LAYER The endpoint management layer is responsible for sending and receiving data using endpoints Control interrupt and bulk transfers are implemented in this layer This layer provides synchronous API for control bulk and interrupt I O operations and asynchronous API for bulk and interrupt I O
350. tion APP_CFG _USBD_PHDC_EN Set to DEF_ENABLED to enable the demo application APP_CFG USBD_PHDC_TX COMM TASK PRIO Priority of the write task APP_CFG USBD_PHDC_RX COMM TASK PRIO Priority of the read task APP CFG USBD PHDC TASK STK SIZE Stack size of both read and write tasks Default value is 512 APP CFG USBD PHDC ITEM DATA LEN MAX Set this constant to the maximum number of bytes that can be transferred as data Must be gt 5 APP CFG USBD PHDC ITEM NBR MAX Set this constant to the maximum number of items that the application should support Must be gt 1 Table 11 13 Device Side Demo Application s Configuration Constants 200 Constant Using the Demo Application Description APP ITEM DATA LEN MAX Set this constant to the maximum number of bytes that can be transferred as data Must be gt 5 APP_ITEM DATA OPAQUE LEN MAX Set this constant to the maximum number of bytes that can be transferred as opaque data Must be lt MaxPacketSize 21 APP ITEM NBR MAX Set this constant to the maximum number of items that the application should support Must be gt 1 APP STAT COMP PERIOD Set this constant to the period in ms on which the statistic of each transfer mean and standard deviation should be computed APP ITEM PERIOD MIN Set this constant to the minimum period in ms that a user can specify for an item APP ITEM PERIOD MAX
351. tion ALTERNATE SETTINGS Alternate settings are used by the device to specify mutually exclusive settings for each interface The default alternate settings contain the default settings of the device The device also uses an interface descriptor to inform the host about an interface s alternate settings ENDPOINT An interface requires a set of endpoints to communicate with the host Each interface has different requirements in terms of the number of endpoints transfer type direction maximum packet size and maximum polling interval The device sends an endpoint descriptor to notify the host about endpoint capabilities Figure 1 3 shows the hierarchical organization of a USB device Configurations are grouped based on the device s speed A high speed device might have a particular configuration in both high speed and low full speed 23 Chapter 1 High Speed Low Full Sped Structure Structure Other configuration Interfaces Alternate Settings Endpoints Figure 1 3 USB device structure 1 4 2 DEVICE STATES The USB 2 0 specification defines six different states and are detailed in Table 1 2 Device States Description Attached The device is in the Attached state when it is connected to the host or a hub port The hub must be connected to the host or to another hub Powered A device is considered in the Powered state when it starts consuming power from the bus Only bus powered devices use power f
352. tprint c seeeceecceeeceeeeeeeeseeneeeeeeeeeeeeeseeeessseaeeeeeeeeeeeens 531 Communications Device Class uk EEEEE EEN 532 Human Interface Device ClaSS ecceeseeeseeeceeeeeeeeeeeeeeeeeeneneeeeeeeeeees 533 Mass Storage Class ccc sceeceeeceeeeeeeeeeeeeseeseeeseeeeeeeeeseseeeesceaneeseeeeeaees 534 Personal Healthcare Device Class s esceeceeeeeeeeeeeeneeeeneeeeeeeeeees 535 Ve eier 537 Chapter About USB This chapter presents a quick introduction to USB The first section in this chapter introduces the basic concepts of the USB specification Revision 2 0 The second section explores the data flow model The third section gives details about the device operation Lastly the fourth section describes USB device logical organization The full protocol is described extensively in the USB Specification Revision 2 0 at http www usb org 1 1 INTRODUCTION The Universal Serial Bus USB is an industry standard maintained by the USB Implementers Forum USB IF for serial bus communication The USB specification contains all the information about the protocol such as the electrical signaling the physical dimension of the connector the protocol layer and other important aspects USB provides several benefits compared to other communication interfaces such as ease of use low cost low power consumption and fast and reliable data transfer 1 1 1 BUS TOPOLOGY USB can connect a series of devices using a tiere
353. transfer is greater than this maximum it will be split into one or more transactions to fulfill the action CONTROL TRANSFERS Control transfers are used to configure and retrieve information about the device capabilities They are used by the host to send standard requests during and after enumeration Standard requests allow the host to learn about the device capabilities for example how many and which functions the device contains Control transfers are also used for class specific and vendor specific requests A control transfer contains three stages Setup Data and Status These stages are detailed in Table 1 1 18 Data Flow Model Stage Description Setup The Setup stage includes information about the request This SETUP stage represents one transaction Data The Data stage contains data associated with request Some standard and class specific request may not require a Data stage This stage is an IN or OUT directional transfer and the complete Data stage represents one ore more transactions Status The Status stage representing one transaction is used to report the success or failure of the transfer The direction of the Status stage is opposite to the direction of the Data stage If the control transfer has no Data stage the Status stage always is from the device IN Table 1 1 Control Transfer Stages BULK TRANSFERS Bulk transfers are intended for devices that exchange large amounts of data where the
354. try mechanisms The seven major models of communication encompass several subclasses A subclass describes the way the device should use the CCI to handle the device management and call management Table 8 2 shows all the possible subclasses and the communication model they belong to Communication Subclass Example of devices using this subclass model Direct Line Control Model PSTN Modem devices directly controlled by the USB host Abstract Control Model PSTN Serial emulation devices modem devices controlled through a serial command set Telephone Control Model PSTN Voice telephony devices Multi Channel Control Model ISDN Basic rate terminal adaptors primary rate terminal adaptors telephones CAPI Control Model ISDN Basic rate terminal adaptors primary rate terminal adaptors telephones Ethernet Networking Control ECM DOC SIS cable modems ADSL modems that support Model PPPoE emulation Wi Fi adaptors IEEE 802 11 family IEEE 802 3 adaptors ATM Networking Control ATM ADSL modems Model Wireless Handset Control WMC Mobile terminal equipment connecting to wireless devices Model Device Management WMC Mobile terminal equipment connecting to wireless devices Mobile Direct Line Model WMC Mobile terminal equipment connecting to wireless devices OBEX WMC Mobile terminal equipment connecting to wireless devices Ethernet Emulation Model EEM Devices using Ethernet frames as the next layer of transp
355. ude paths to your project settings Micrium Software uC USB Device Source Micrium Software uC USB Device Class lt class gt Micrium Software uC USB Device Drivers lt controller gt Micrium Software uC USB Device Drivers lt controller gt BSP lt board name gt 2 4 4 MODIFYING APPLICATION CONFIGURATION FILE The USB application initialization code templates assume the presence of app _cfg h The following defines must be present in app_cfg h in order to build the sample application define APP _CFG USBD_EN DEF_ENABLED 1 define USBD_OS CFG CORE TASK PRIO 6u 2 define USBD OS CFG TRACE TASK PRIO 7u define USBD_OS_CFG CORE TASK STK SIZE 256u define USBD OS CFG TRACE TASK PRIO 256u define APP CFG USBD_XXXX_EN DEF_ENABLED 3 define LIB MEM CFG OPTIMIZE ASM EN DEF_DISABLED 4 define LIB MEM CFG ARG CHK EXT EN DEF_ENABLED define LIB MEM CFG ALLOC EN DEF_ENABLED define LIB MEM CFG HEAP SIZE 1024u define TRACE LEVEL OFF 0u 5 define TRACE LEVEL INFO lu define TRACE LEVEL DBG 2u define APP _CFG TRACE LEVEL TRACE LEVEL DBG 6 define APP CFG TRACE printf 7 define APP_TRACE INFO x A APP_CFG_TRACE LEVEL gt TRACE LEVEL_INFO void APP_CFG TRACE x void 0 define APP_TRACE_DBG x APP_CFG_TRACE LEVEL gt TRACE LEVEL DBG 3 void APP_CFG TRACE x void 0 Listing 2 4 Application Configuration defines 38 L2 4 1 L2 4 2 L2 4 3 L2 4 4 L2 4 5 L2 4 6 L2 4 7
356. ult endpoint to decode vendor specific requests sent by the host The standard requests are managed internally by the Core layer of pC USB Device 12 2 CONFIGURATION 12 2 1 GENERAL CONFIGURATION Some constants are available to customize the class These constants are located in the USB device configuration file usbd_cfg h Table 12 2 shows their description Constant Description USBD_VENDOR_CFG MAX NBR_DEV Configures the maximum number of class instances Unless you plan on having multiple configurations or interfaces using different class instances this can be set to 1 USBD_VENDOR_CFG MAX NBR CFG Configures the maximum number of configuration in which Vendor class is used Keep in mind that if you use a high speed device two configurations will be built one for full speed and another for high speed Table 12 2 General Configuration Constants Summary 207 Chapter 12 12 2 2 CLASS INSTANCE CONFIGURATION Before starting the communication phase your application needs to initialize and configure the class to suit its needs Table 12 3 summarizes the initialization functions provided by the Vendor class For more details about the functions parameters refer to section G 1 Vendor Class Functions on page 474 Function name Operation USBD_Vendor_Init Initializes Vendor class internal structures and variables USBD_Vendor_Add Creates a new instance of Vendor class USBD
357. um packet size used by the USB device stack is validated to follow the USB standard guidelines An example of an endpoint information table for a high speed capable device is provided below const USBD DV Ep INFO USBD DrvEP InfoTbl lt controller gt USBD_EP_INFO TYPE CTRL USBD_EP_INFO DIR OUT 0u 64u USBD_EP_INFO TYPE CTRL USBD_EP INFO DIR_IN Ou 64u USBD_EP_INFO TYPE BULK USBD_EP INFO TYPE INTR USBD EP INFO DIR OUT lu 1024u USBD_EP_INFO TYPE BULK USBD_EP INFO TYPE INTR USBD EP INFO DIR IN lu 1024u DEF_BIT_NONE Oa 0u 1 ti L6 6 1 Listing 6 6 Example of Endpoint Information Table Configuration The last entry on the endpoint information table must be an empty entry to allow the USB device stack to determine the end of the table 87 Chapter 6 6 6 MEMORY ALLOCATION Memory allocation in the driver can be simplified by the use of memory allocation functions available from uC LIB pC LIB s memory allocation functions provide allocation of memory from dedicated memory space e g USB RAM or general purpose heap The driver may use the pool functionality offered by uC LIB Memory pools use fixed sized blocks that can be dynamically allocated and freed during application execution Memory pools may be convenient to manage objects needed by the driver The objects could be for instance data structures mandatory for DMA operations For more information on using pC LIB memory allocat
358. upport all latency reliability combinations Here is a list of supported combinations E Low latency good reliability E Medium latency good reliability P Medium latency better reliability P Medium latency best reliability P High latency best reliability E Very high latency best reliability 184 These combinations are called quality of service QoS Overview QoS Raw info Transfer g Scat Be Latency f S Typical use Latency reliability rate direction s Low good lt 20ms 50 bits sec to IN Real time monitoring with fast 1 2M bits sec analog sampling rate Medium good lt 200ms 50 bits sec to IN 1 2M bits s Medium better lt 200ms 10s of byte IN Data from measured parameter range collected off line and replayed or sent real time Medium best lt 200ms 10s of byte IN OUT Events notifications request range control and status of physiological and equipment functionality High best lt 2s 10s of byte IN OUT Physiological and equipment range alarms Very high best lt 20s 10s of byte IN OUT Transfer reports histories or off line range to collection of data gigabytes of data 11 1 2 OPERATIONAL MODEL Table 11 1 QoS Levels Description The requirements for data transfer QoS in personal healthcare devices can be accomplished by PHDC using bulk endpoints and optionally an interrupt endpoint Table 11 2 and Figure 11 1 show the mapping between QoS and endpoint t
359. uration No data phase printf ERROR d SET_INTERFACE 1 request failed n err 20 Sy 20 Ki the More details about USB device requests can be found in Universal Serial Bus Specification Revision 2 0 April 27 2000 section 9 3 519 Appendix G G 2 18 USBDev_PipeWr Write data to device over the specified pipe FILES usbdev_api c PROTOTYPE DWORD USBDev PipeWr HANDLE pipe UCHAR p buf DWORD buf_len DWORD timeout DWORD p err ARGUMENTS pipe Pipe handle p buf Pointer to transmit buffer buf len Transmit buffer length timeout Timeout in milliseconds A value of 0 indicates a wait forever p err Pointer to variable that will receive the return error code from this function ERROR_SUCCESS ERROR INVALID HANDLE ERROR INVALID USER BUFFER ERROR BAD PIPE ERROR INVALID PARAMETER ERROR HOT ENOUGH MEMORY ERROR _SEM TIMEOUT 520 RETURNED VALUE Number of bytes written if NO error s 0 otherwise CALLERS Application NOTES WARNINGS None 521 Appendix G G 2 19 USBDev PipeRd Read data from device over the specified pipe FILES usbdev_api c PROTOTYPE DWORD USBDev PipeRd HANDLE pipe UCHAR p buf DWORD buf_len DWORD timeout DWORD p err ARGUMENTS pipe Pipe handle p buf Pointer to receive buffer buf len Receive buffer length timeout Timeout in milliseconds A value of 0 indicates a wait forever p err Pointer to varia
360. urchased will depend on your needs But don t forget that you need a class to build a complete USB project Table 2 1 also indicates that pC OS II and II Core and Port are optional Indeed pC USB Device stack does not assume a specific real time operating system to work with but it still requires one 29 Chapter 2 2 3 INSTALLING THE FILES Once all the distribution packages have been downloaded to your host machine extract all the files at the root of your C drive for instance The package may be extracted to any location After extracting all the files the directory structure should look as shown in Figure 2 1 In the example all Micrium products sub folders shown in Figure 2 1 will be located in C Micrium Software lt Architecture gt y UCOS II III eg Ports A lt Architecture gt zz Source a uC USB Device V4 Weg App Cfg penne Jy Class eee CDC ja M HID MSC i PHDC i pvr Vendor dl Doc EN Drivers os o Led Sources Figure 2 1 Directory Tree for phC USB Device 30 Building the Sample Application 2 4 BUILDING THE SAMPLE APPLICATION This section describes all the steps required to build a USB based application The instructions provided in this section are not intended for any particular toolchain but instead are describe
361. ure End of Collection Closes a collection 137 Chapter 9 Item type Item function Description Global Usage Page Identifies a function available within the device Logical Minimum Defines the lower limit of the reported values in logical units Logical Maximum Defines the upper limit of the reported values in logical units Physical Minimum Defines the lower limit of the reported values in physical units that is the Logical Minimum expressed in physical units Physical Maximum Defines the upper limit of the reported values in physical units that is the Logical Maximum expressed in physical units Unit Exponent Indicates the unit exponent in base 10 The exponent ranges from 8 to 7 Unit Indicates the unit of the reported values For instance length mass temperature units etc Report Size Indicates the size of the report fields in bits Report ID Indicates the prefix added to a particular report Report Count Indicates the number of data fields for an item Push Places a copy of the global item state table on the CPU stack Pop Replaces the item state table with the last structure from the stack Local Usage Represents an index to designate a specific Usage within a Usage Page It 138 indicates the vendor s suggested use for a specific control or group of controls A usage supplies information to an application developer about what a control is actually measuring Usage Mini
362. usbd_core h usbd_core c PROTOTYPE void USBD_IntrRxAsync CPU_INT08U dev_nbr cPU_INTO8U ep_addr void p buf CPU_INT32U buf_len USBD_ASYNC_FNCT async_fnct void p_async_ arg USBD_ERR p err ARGUMENTS dev_nbr Device number ep addr Endpoint address p buf Pointer to destination buffer to receive data buf len Number of octets to receive async_fnct Function that will be invoked upon completion of receive operation p_async_arg Pointer to argument that will be passed as parameter of async_fnct p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_ DEV INVALID NBR USBD_ERR DEV INVALID STATE USBD_ERR_ EP INVALID ADDR USBD_ERR_ EP INVALID STATE USBD_ERR_EP INVALID TYPE USBD_ERR_OS TIMEOUT USBD_ERR_OS ABORT USBD_ERR_OS FAIL 280 RETURNED VALUE None CALLERS USB device class drivers NOTES WARNINGS The callback specified by async_fnct has the following prototype void USB_AsyncFnct CPU_LINTO8U dev_nbr CPU_INTO8U ep addr void p buf CPU_INT32U buf_len CPU_INT32U xfer_len void p arg USBD_ERR err Argument s dev_nbr Device number ep_addr Endpoint address p_buf Pointer to destination buffer to receive data buf_len Buffer length xfer_len Number of byte received p_arg Pointer to function argument err Error status USBD_ERR_NONE USBD_ERR_EP ABORT 281 Appendix A A 4 11 USBD_IntrTx Sends data on in
363. used to define each string key token indicated by string name in the INF file Refer to the MSDN online documentation on this web page for more details about INF sections and directives http msdn microsoft com en us library f f 549520 aspx You will be able to modify some sections in order to match the INF file to your device characteristics such as Vendor ID Product ID and human readable strings describing the device The sections are P Models section E Strings section To identify possible drivers for a device Windows looks in the Models section for a device identification string that matches a string created from information in the device s descriptors Every USB device has a device ID that is a hardware ID created by the Windows USB host stack from information contained in the Device descriptor A device ID has the following form USB Vid_xxxx amp Pid_yyyy XXXKX yyyy represent the value of the Device descriptor fields idVendor and idProduct respectively refer to the Universal Serial Bus Specification revision 2 0 section 9 6 1 for more details about the Device descriptor fields This string allows Windows to load a driver for the device You can modify xxxx and yyyy to match your device s Vendor and Product IDs In Listing 2 1 the hardware ID defines the Vendor ID 0xFFFE and the Product ID 0x1234 Composite devices formed of several functions can specify a driver for each function In this case the
364. vate information can be retrieved 112 36 Application provides the initialized transmit buffer L12 3 6 If this flag is set to DEF_TRUE and the transfer length is a multiple of the endpoint maximum packet size the device stack will send a zero length packet to the host to signal the end of transfer The use of interrupt endpoint communication functions USBD_Vendor_IntrRdAsync and USBD Vendor IntrWrAsync is similar to bulk endpoint communication functions presented in Listing 12 3 12 3 USBDev_API Windows application communicates with a vendor device through USBDev_API The latter is a wrapper developed by Micrium allowing the application to access the WinUSB functionalities to manage a USB device Windows USB WinUSB is a generic driver for USB devices The WinUSB architecture consists of a kernel mode driver Winusb sys and a user mode dynamic link library Winusb d11 that exposes WinUSB functions USBDev_API eases the use of WinUSB by providing a comprehensive API refer to section G 2 USBDev_API Functions on page 497 for the complete list Figure 12 2 shows the USBDev_API library and WinUSB 214 USBDev_AP Windows PC Host Application DA USBDev_API SZ Winusb dll User space Kernel space Winusb sys Windows host stack II USB Vendor device Figure 12 2 USBDev_API and WinUSB For more about WinUSB architecture refer to Micro
365. vice driver s usbd_drv c PROTOTYPE static void USBD DrvInit USBD DEU ap deu USBD_ERR p err Note that since every device driver function is accessed only by function pointer via the device driver s API structure they do not need to be globally available and should therefore be declared as static ARGUMENTS p drv Pointer to USB device driver structure p err Pointer to variable that will receive the return error code from this function RETURNED VALUE None 324 CALLERS USBD_DeviInit via p drv_api gt Init NOTES WARNINGS The Init function generally performs the following operations however depending on the device being initialized functionality may need to be added or removed Configure clock gating to the USB device configure all necessary I O pins and configure the host interrupt controller This is generally performed via the device s BSP function pointer Init implemented in usbd_bsp c see section B 2 1 USBD_BSP_InitO on page 350 Reset USB controller or USB controller registers Disable and clear pending interrupts should already be cleared Set the device address to zero For DMA devices Allocate memory for all necessary descriptors This is performed via calls to pC LIB s memory module If memory allocation fails set p err to USBD_ERR_ALLOC and return Set p_err to USBD_ERR_NONE if initialization proceeded as expected Otherwise set p_err to an appropriate de
366. vice error code 325 Appendix B B 1 2 USBD_DrvStart The second function is the device driver Start function This function is called once each time a device is started FILES Every device driver s usbd_drv c PROTOTYPE static void USBD DrvStart USBD_DRV p_ drv USBD_ERR p err ARGUMENTS p drv Pointer to USB device driver structure p err Pointer to variable that will receive the return error code from this function RETURNED VALUE None CALLERS USBD_DevStart via p drv_api gt Start NOTES WARNINGS The Start function performs the following items P Typically activates the pull up on the D pin to simulate attachment to host Some MCUs MPUs have an internal pull up that is activated by a device controller register for others this may be a general purpose I O pin This is generally performed via the device s BSP function pointer Conn implemented in usbd_bsp c see section B 2 2 on page 351 The device s BSP ConnQ is also responsible for enabling the host interrupt controller P Clear all interrupt flags 326 Locally enable interrupts on the hardware device The host interrupt controller should have already been configured within the device driver Init function Enable the controller Set p_err equal to USBD_ERR_NONE if no errors have occurred Otherwise set p_err to an appropriate device error code 327 Appendix B B 1 3 USBD_DrvStop The next function wi
367. vice if it were operating at its other possible speed refer to Universal Serial Bus 2 0 Specification revision 2 0 section 9 6 for more details about these descriptors In our example the host may want to reset and enumerate the device again in full speed mode In this case the full speed configuration is active Whatever the active configuration the same class instance is used Indeed the same class instance can be added to different configurations A class instance cannot be added several times to the same configuration Configuration 0 HS FS device Configuration 0 D full speed high speed Interface 0 Interface 0 Default interface Default interface Alternate 0 Alternate 0 Endpoint IN Endpoint OUT Endpoint IN Endpoint OUT Class instance 0 Class instance 0 lt d Figure 7 2 Multiple Class Instances HS FS Device 2 Configurations and 1 Single Interface The code corresponding to Figure 7 2 is shown in Listing 7 2 102 Class Instance Concept USBD_ERR err CPU_INTO8U class_0 USBD_XXXX_Init serr 1 if err USBD_ERR NONE Handle the error class_0 USBD_XXXX Add serr 2 if err USBD ERR NONE Handle the error USBD_XXXX_CfgAdd class_0 dev_nbr cfg_0 fs amp err 3 if err USBD_ERR_NONE Handle the error USBD_XXXX_CfgAdd class_0 dev_nbr cfg_0_hs amp err
368. ween a simple RTOS functions wrapper port and a features oriented RTOS port o ti Example of feature oriented function Equivalent function in a simple wrapper eration p current implementation not used Create a task The stack is not in charge of creating tasks USBD_OS_TaskCreate The stack would need This should be done in the RTOS to explicitly create the needed tasks and to abstraction layer within a USBD_OS_Init manage them function for example Create a signal USBD_OS_EP SignalCreate You are free USBD_OS SemCreate The stack would need for an endpoint to use another OS service than a typical to explicitly choose the OS service to use Semaphore Put a core event USBD_OS_CoreEventPut If you prefer not USBD_OS_Q Post Again the stack would in a queue using typical OS queues you could still need to explicitly choose the OS service to use implement it using a chained list and a semaphore for instance Table 14 1 Comparison between a wrapper and a features oriented RTOS port Because of the features oriented RTOS port design some pC USB Device modules will need their own OS port These modules are listed here E wC USB Device core layer E Personal Healthcare Device Class PHDC E Human Interface Device Class HID E Mass Storage Class MSC 238 Porting Modules to a RTOS Moreover all the demo applications for each USB class that Micrium provides interact with the RTOS The demo app
369. will receive the return error code from this function USBD_ERR_NONE USBD_ERR_INVALID ARG USBD_ERR_ALLOC RETURNED VALUE Class instance number if NO error s USBD_CLASS NBR_NONE otherwise 475 Appendix G CALLERS Application NOTES WARNINGS None 476 G 1 3 USBD_Vendor_CfgAdd Add a Vendor class instance into the specified configuration The Vendor class instance was previously created by the function USBD_Vendor_Add FILES usbd_vendor c PROTOTYPE void USBD_Vendor_CfgAdd CPU_INTO8U class_nbr CPU_INTO8U dev_nbr CPU_INTO8U cfg_nbr USBD_ERR p err ARGUMENTS class nbr_ Class instance number dev_nbr Device number cfg_nbr Configuration index to add Vendor class instance to p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_INVALID ARG USBD_ERR_ALLOC USBD_ERR NULL PTR USBD_ERR_ DEV INVALID NBR USBD_ERR_ DEV INVALID STATE USBD_ERR CFG INVALID NBR USBD_ERR_IF ALLOC USBD_ERR_IF ALT ALLOC USBD_ERR_IF INVALID NBR USBD_ERR_EP NONE AVAIL USBD_ERR_EP ALLOC 477 Appendix G RETURNED VALUE None CALLERS Application NOTES WARNINGS USBD_ Vendor CfgAdd basically adds an Interface descriptor and its associated Endpoint descriptor s to the Configuration descriptor One call to USBD_Vendor_CfgAdd builds the Configuration descriptor corresponding to a Vendor specific device with the following format Configur
370. x USBD_CtrlTx USBD_Dbg USBD_DbgArg USBD_DbgTaskHandler USBD_DevAdd USBD_DEV_CFG usbd_dev_cfg c usbd_dev_cfg h USBD_DevGetState USBD_DEV_SPD_FULL USBD_DEV_SPD_HIGH USBD_DEV_SPD_LOW USBD_DevStart USBD_DevStop USBD_DrvAddrEn USBD_DrvAddrSet USBD_DRV_CFG USBD_DrvCfgCir USBD_DrvCfgSet USBD_DrvEP_Abort USBD_DrvEP_Close USBD_DrvEP_Open USBD_DrvEP_Rx USBD_DrvEP_RxStart USBD_DrvEP_RxZLP USBD_DrvEP_Stall USBD_DrvEP_Tx USBD_DrvEP_TxStart USBD_DrvEP_TxZLP USBD_DrvGetFrameNbr USBD_DrvInit USBD_DrvISR_Handler USBD_DrvStart USBD_DrvStop USBD_EP_Abort USBD_EP_GetMaxNbrOpen USBD_EP_GetMaxPhyNbr USBD_EP_GetMaxPktSize USBD_EP_INFO_DIR USBD_EP_INFO_DIR_IN USBD_EP_INFO_DIR_OUT USBD_EP_INFO_TYPE USBD_EP_INFO_TYPE_BULK USBD_EP_INFO_TYPE_CTRL USBD_EP_INFO_TYPE_INTR USBD_EP_INFO_TYPE_ISOC USBD_EP_IsStalled USBD_EP_Process USBD_EP_Rx USBD_EP_RxCmpl ooeec 242 300 34 35 55 85 156 34 55 85 249 544 USPD ER BxvZL P 287 USBD_EP_Stall AE 292 HESPER TX ra Gileveecaisrarae tention 93 95 96 USBD_EP_TxCmplqQ 84 94 96 314 USBD_EP_TxZLP USBD OV APD ce siecctitsssenieprvnninaasarenaonewninnsedereaccncmmnainp eax USBDev_API and WinUSB cece 215 USBDev_API Asynchronous Read Example s 0 219
371. x MSC API Reference This appendix provides a reference to the mass storage class API Each user accessible service is presented following a category order i e initialization and communication categories The following information is provided for each of the services E A brief description E The function prototype E The filename of the source code E A description of the arguments passed to the function E A description of returned value s E Specific notes and warnings regarding use of the service 419 Appendix E E 1 MASS STORAGE CLASS FUNCTIONS E 1 1 USBD_MSC Init Initialize internal structures and local global variables used by the MSC bulk only transport FILES usbd_msc h usbd_msc c PROTOTYPE void USBD_MSC_Init USBD ERR p err ARGUMENTS p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE RETURNED VALUE None CALLERS Application NOTES WARNINGS None 420 E 1 2 USBD_MSC Add Create a new instance of the MSC FILES usbd_msc h usbd_msc c PROTOTYPE CPU_INTO8U USBD MSC Add USBD_ERR ap err ARGUMENTS p err Pointer to variable that will receive the return error code from this function USBD_ERR_NONE USBD_ERR_ALLOC RETURNED VALUE Class instance number if NO error s USBD_CLASS NBR_NONE otherwise CALLERS Application NOTES WARNINGS None 421 Appendix E E 1 3 USBD_MSC_CfgAdd
372. y reliability parameter after a call to USBD_PHDC WrPreamble 461 Appendix F F 1 12 USBD_ PHDC Reset Reset PHDC instance FILES usbd_phdc h usbd_phdc c PROTOTYPE void USBD_PHDC_ Reset CPU_INTO8U class_nbr ARGUMENTS class_nbr PHDC instance number RETURNED VALUE None CALLERS USBD_PHDC_Disconn and Application NOTES WARNINGS USBD_PHDC Reset should be used to reset internal variables like the transmit priority queue of the PHDC instance This function should be called when the data layer above PHDC request to terminate communication For instance USBD_PHDC_Reset should be called when the host send an 11073 Association abort request 462 F 2 PHDC OS LAYER FUNCTIONS F 2 1 USBD_PHDC_OS Init Initialize PHDC OS layer FILES usbd_phdc_os h usbd_phdc_os c PROTOTYPE void USBD_PHDC OS Init USBD ERR p err ARGUMENTS p err Pointer to variable that will receive the return error code from this function RETURNED VALUE None CALLERS USBD_PHDC Init IMPLEMENTATION GUIDELINES This function should be used to initialize all RTOS layer s internal variables tasks of every class instances It will be called only once In case creation of semaphore mutex or other signal fails the function should assign USBD_ERR OS SIGNAL CREATE to p err and return immediately If any other error occurs USBD_ERR OS INIT FAIL should be assigned to p_err Otherwise USBD
373. ypes Endpoint Usage Bulk OUT All QoS host to device data transfers Bulk IN Very high high and medium latency device to host data transfers Interrupt IN Low latency device to host data transfers Table 11 2 Endpoint QoS Mapping 185 Chapter 11 DEVICE HOST Medium good Medium better Medium best N Medium best High best Bulk OUT High best Very high best USB Connection Very high best Low good I gt Interrupt IN J Figure 11 1 QoS Endpoint Mapping PHDC does not define a protocol for data and messaging It is only intended to be used as a communication layer Developers can use either data and messaging protocol defined in ISO IEFE 11073 20601 base protocol or a vendor defined protocol Figure 11 2 shows the different software layers needed in a personal healthcare device Personal healthcare application Data messaging and protocol layer ex ISO IEEE 11073 based or vendor defined USB Personal Healthcare Device Class layer Figure 11 2 Personal Healthcare Device Software Layers Since transfers having different QoS will have to share a single bulk endpoint host and device need a way to inform each other what is the QoS of the current transfer A metadata message preamble will then be sent before a single or a group of regular data transfers This preamble will contain t
Download Pdf Manuals
Related Search
Related Contents
Horloge murale radio pilotée LUNA 3 ダウンロード ModemUSB/E12 Mode d`emploi Manual de instrucciones MC-MM1002 - Binatone Copyright © All rights reserved.
Failed to retrieve file