Home
STM32Cube USB device library
Contents
1. int8 t GetState USBD AUDIO ItfTypeDef void Each audio hardware interface driver should provide a structure pointer of type USBD AUDIO ItfTypeDef The functions and constants pointed by this structure are listed in the following sections If a functionality is not supported by a given memory interface the relative field is set as NULL value usbd audio if c h This driver manages the low layer audio hardware usbd audio if c h driver manages the Audio Out interface from USB to audio speaker headphone user can call lower layer Codec driver i e stm324xg eval audio c h for basic audio operations play pause volume control This driver provides the structure pointer extern USBD AUDIO ItfTypeDef USBD AUDIO fops 2 DoclD025934 Rev 3 45 59 USB device library class module UM1734 Note 6 4 3 46 59 Table 24 usbd audio if c h files Functions static int8 t Audio Init uint32 t AudioFreq uint32 t Volume uint32 t options Description Initializes the audio interface static int8 t Audio Delnit uint32 t options De initializes the audio interface and free used resources static int8 t Audio PlaybackCmd uint8 t pbuf uint32 t size uint8 t cmd Handles audio player commands play pause static int8 t Audio VolumeCtl uint8 t vol Handles audio player volume control static int8 t Audio MuteCtl uint8 t cmd Handles audio player
2. DoclD025934 Rev 3 MS34129V1 33 59 USB device library class module UM1734 The following table shows the supported SCSI commands Table 14 SCSI commands Command e Command Remark specification SCSI PREVENT REMOVAL SCSI START STOP UNIT SCSI TEST UNIT READY SCSI INQUIRY SCSI READ CAPACITY10 SCSI SCSI READ FORMAT CAPACITY SCSI MODE SENSE6 SCSI MODE SENSE10 SCSI READ10 SCSI WRITE10 SCSI VERIFY10 READ FORMAT CAPACITY 0x23 is an UFI command As required by the BOT specification the Bulk only mass storage reset request class specific request is implemented This request is used to reset the mass storage device and its associated interface This class specific request should prepare the device for the next CBW from the host To generate the BOT Mass Storage Reset the host must send a device request on the default pipe of e bmRequestType Class interface host to device e bRequest field set to 255 FFh e wValue field set to O e windex field set to the interface number e wLength field set to 0 6 2 2 Get Max MUN class specific request The device can implement several logical units that share common device characteristics The host uses bCBWLUN to indicate which logical unit of the device is the destination of the CBW The Get Max LUN device request is used to determine the number of logical units supported by the device To generate a Get Max LUN
3. The USB device library is based on the generic USB low level driver It has been developed to work in Full speed and High speed mode It implements the USB device library machines as defined by Universal Serial Bus Specification revision 2 0 The library functions are covered by the files located in the Core folder within the USB device library firmware package see Figure 5 The USB class module is the class layer built in compliance with the protocol specification Figure 5 USB device library directory structure gt STM32 USB Device Library E Class J CustomHID DFU J HID A A 2 00 000 MSC Template Core J Inc usbd_conf_template h usbd_core h usbd ctlreq h usbd def h usbd_ioreg h B h Src usbd conf template c usbd core c usbd ctlreq c usbd ioreq c 2 Release Notes html Q 0 0 E USB device library description USB device library flow Handling control endpoint The USB specification defines four transfer types control interrupt bulk and isochronous The USB host sends requests to the device through the control endpoint in this case control endpoint is endpoint 0 The requests are sent to the device as SETUP packets These requests can be classified into three categories standard class specific and vendor specific Since the standard requests are generic and common to all USB devices the library receives and handles all the sta
4. These aspects can be enriched or modified for a specific user application DoclD025934 Rev 3 47 59 USB device library class module UM1734 6 5 1 6 5 2 6 5 3 6 5 4 6 5 5 48 59 This driver does not implement the following aspects of the specification but it is possible to manage these features with some modifications on this driver e Any class specific aspect relative to communication classes should be managed by user application e All communication classes other than PSTN are not managed Communication The CDC core uses two endpoint transfer types e Bulk endpoints for data transfers 1 OUT endpoint and 1 IN endpoint e Interrupt endpoints for communication control CDC requests 1 IN endpoint Data transfers are managed differently for IN and OUT transfers Data IN transfer management from device to host The data transfer is managed periodically depending on host request the device specifies the interval between packet requests For this reason a circular static buffer is used for storing data sent by the device terminal i e USART in the case of Virtual COM Port terminal Data OUT transfer management from host to device In general the USB is much faster than the output terminal i e the USART maximum bitrate is 115 2 Kbps while USB bitrate is 12 Mbps for Full speed mode and 480 Mbps in High speed mode Consequently before sending new packets the host has to wait until the device has fi
5. UM1734 USB device library overview 2 Table 9 usbd_core c h files continued Functions USBD_StatusTypeDef USBD_Start USBD_HandleTypeDef pdev Description Starts the device library process USBD StatusTypeDef USBD Stop USBD HandleTypeDef pdev Stops the device library process and frees related resources USBD StatusTypeDef USBD LL SetupStage USBD HandleTypeDef pdev uint8 t psetup Handles setup stage from ISR USBD StatusTypeDef USBD LL DataOutStage USBD HandleTypeDef pdev uint8 t epnum uint8 t pdata Handles data out stage from ISR USBD StatusTypeDef USBD LL DatalnStage USBD HandleTypeDef pdev uint8 t epnum uint8 t pdata Handles data IN stage USBD StatusTypeDef USBD LL Reset USBD HandleTypeDef pdev Handles USB Reset from ISR USBD StatusTypeDef USBD LL SetSpeed USBD HandleTypeDef pdev USBD SpeedTypeDef speed USBD StatusTypeDef USBD LL Suspend USBD HandleTypeDef pdev Sets USB Core Speed Handles Suspend Event USBD StatusTypeDef USBD LL Resume USBD HandleTypeDef pdev Handles Resume event USBD StatusTypeDef USBD LL SOF USBD HandleTypeDef pdev USBD StatusTypeDef USBD LL IsolNIncomplete USBD HandleTypeDef pdev uint8 t epnum Handles Start Of Frame Event Handles Incomplete ISO IN transaction Event USBD StatusTypeDef USBD LL IsoOUTIncomplete USBD HandleTypeDef pdev uint8 t epnum USBD StatusTypeDef
6. eee 19 5 1 3 Core interface with low level driver a 20 5 1 4 USB device library interfacing model 21 5 1 5 Configuring the USB device firmware library 22 5 1 6 USB control functions eres 23 5 2 USB device library functions 0c ee ee 24 5 3 USB device class interface ee 27 6 USB device library class module aan 30 6 1 HID Class na been KANA KA ws Gee NG ad bate edad ara 31 6 1 1 HID class implementation ooo 31 6 1 2 HID user interface 0 lees 31 6 1 3 HID Class Driver APIS 22222 llle 32 2 59 DocID025934 Rev 3 Ly UM1734 Contents 6 2 Mass storage class MM 32 6 2 1 Mass storage class implementation n on anaana 32 6 2 2 Get Max MUN class specific request ooooocooooo oo 34 6 2 3 MSC Core files ees 35 6 2 4 Disk operation structure definition ee 37 6 2 5 Disk operation functions liliis 38 6 3 Device firmware upgrade DFU class 00 38 6 3 1 Device firmware upgrade DFU class implementation 39 6 3 2 Device firmware upgrade DFU Class core files 41 6 4 Audio class YA 43 6 4 1 Audio class implementation eee e eee eee 43 6 4 2 Audio core files 2 cece eee 44 6 4 3 How to use this driver 2 cece ee eee 46 6 4 4 Audio known limitations o 47 6 5 Communication device class CDC
7. 00 47 6 5 1 Communication a 2 xa ama ue med rea AEG A adu deua 48 6 5 2 Data IN transfer management from device to host 48 6 5 3 Data OUT transfer management from host to device 48 6 5 4 Command request management a 48 6 5 5 Command device class CDC core files 48 6 5 6 How to use 2 sss 51 6 5 7 CDC known limitations e 52 6 6 Adding a custom class Xx aa sake eR RR ER REX REX RR TERR d 52 6 7 Library footprint optimization ooo o 53 7 Frequently asked questions llle 56 8 REVISION hiStOry cesos rias AA 58 Ky DoclD025934 Rev 3 3 59 List of tables UM1734 List of tables Table 1 Table 2 Table 3 Table 4 Table 5 Table 6 Table 7 Table 8 Table 9 Table 10 Table 11 Table 12 Table 13 Table 14 Table 15 Table 16 Table 17 Table 18 Table 19 Table 20 Table 21 Table 22 Table 23 Table 24 Table 25 Table 26 Table 27 Table 28 Table 29 Table 30 4 59 LISTOMETMS a A A ew 0G A ANNA Ludo rip UE a 6 USB device status o o o ooooooo 14 Standard requests o 16 DXEUtigjsbEPFETCCTPTPP I 20 Low level Event Callback functions 0000 eee 22 USB library configuration RII II 22 USB device core files oooooococconrocorr eh hs 24 Class drivers TOS ue gg aaa ed arg KANG Rr arm RAT RU ENG ARR e PERO dlc e e mor 24 USDA core CIT
8. Cus UM1734 WI life qugmented User manual STM32Cube USB device library Note May 2015 Introduction STMCube initiative was originated by STMicroelectronics to ease developers life by reducing development efforts time and cost STM32Cube covers STM32 portfolio STM32Cube Version 1 x includes e The STM32CubeMX a graphical software configuration tool that allows to generate C initialization code using graphical wizards e A comprehensive embedded software platform delivered per series such as STM32CubeF4 for STM32F4 series The STM32Cube HAL an STM32 abstraction layer embedded software ensuring maximized portability across STM32 portfolio Aconsistent set of middleware components such as RTOS USB TCP IP Graphics All embedded software utilities coming with a full set of examples The Universal Serial Bus USB is the most successful interconnect in the history of personal computing which is used to connect devices like mouse game pads and joysticks scanners digital cameras and printers USB has also migrated into consumer electronics and mobile products This user manual describes the STM32Cube USB device library which is part of the STM32Cube firmware package that can be downloaded free from ST website http www st com stm32cube It is intended for developers who use STM32Cube firmware on STM32 microcontrollers It describes how to start and implement a USB device applications for most
9. Handles USB Errors on the control pipe DoclD025934 Rev 3 Ly UM1734 USB device library overview Table 11 usbd ctrlq c h files functions continued Functions uint16 t len void USBD GetString uint8 t desc uint8 t unicode Description Converts ASCII string into unicode one static uint8 t USBD GetLen uint8 t buf Returns the string length void USBD ParseSetupRequest USBD SetupReqTypedef req uint8 t pdata Copies request buffer into setup structure 5 3 USB device class interface USB Class callback structure The USB class is chosen during the USB device library initialization by selecting the corresponding class callback structure The class structure is defined as follows Figure 10 USB Class callback structure typedef struct Device cb uint8 t Init struct USBD HandleTypeDef pdev uint8 t cfgidx uint8 t Delnit struct USBD HandleTypeDef pdev uint8 t cfgidx Control Endpoints uint8 t Setup struct USBD HandleTypeDef pdev USBD SetupReqTypedef req uint8 t EPO TxSent struct USBD HandleTypeDef pdev uint8 t EPO RxReady struct USBD HandleTypeDef pdev Class Specific Endpoints uint8 t DataIn struct USBD HandleTypeDef pdev uint8 t epnum uint8 t DataOut struct USBD HandleTypeDef pdev uint8 t epnum uint8 t SOF struc
10. CDC Communication Device Class DFU Device Firmware Upgrade FS Full Speed 12 Mbps HID Human Interface Device Mbps Megabit per second MSC Mass Storage Class OTG On The Go An OTG peripheral can switch HOST DEVICE role on the fly PID USB Product Identifier SCSI Small Computer System Interface SOF Start Of Frame VID USB Vendor Identifier USB Universal Serial Bus Additional Information In addition to this document STMicroelectronics provides several other resources related to the USB e USB Host library user manual UM1720 e Description of STM32F4xx HAL drivers UM1725 where you can find the two USB generic drivers description HCD for Host and PCD for Device References e Universal Serial Bus Specification Revision 2 0 http www usb org USB device class specifications Audio HID MSC etc http www usb org d DoclD025934 Rev 3 UM1734 USB device library description 2 2 1 2 USB device library description Overview STMicroelectronics offers to its customers new USB stacks device stack and host stack that support all STM32 MCUs together with many development tools such as Atollic TrueSTUDIO IAR Embedded Workbench for ARM o and Keil uVision This document focuses on USB device stack For the host stack please refer to the related users manual The USB device library is generic for all STM32 microcontrollers only the HAL layer is adapted to each STM32 device The USB device l
11. UM1734 USB device library class module 6 1 6 1 1 6 1 2 2 HID class HID class implementation This module manages the HID class V1 11 following the Device Class Definition for Human Interface Devices HID Version 1 11 June 27 2001 The HID specification can be found searching for hidpage on www st com This driver implements the following aspects of the specification e The boot interface subclass e The mouse protocol e Usage page generic desktop e Usage joystick e Collection application HID user interface Input reports are sent only via the Interrupt In pipe HID mouse example Feature and Output reports must be initiated by the host via Control pipe or an Interrupt Out pipe Custom HID example The USBD HID SendReport can be used by the HID mouse application to send HID reports the HID driver in this release handles only IN traffic An example of use of this function is shown below Figure 12 Example of USBD HID SendReport function static IO uint32 t counter 0 HAL IncTick check Joystick state every 10ms if counter 10 GetPointerData HID Buffer send data though IN endpoint if HID Buffer 1 0 HID Buffer 2 0 USBD HID SendReport amp USBD Device HID Buffer 4 j counter 0 j Toggle Leds DoclD025934 Rev 3 31 59 USB device library class module UM1734 6 1 3 6 2 6 2 1 32 59 HID Class
12. USBD StatusTypeDef USBD CtlContinueSendData USBD StatusTypeDef USBD CtlPrepareRx USBD StatusTypeDef USBD CtlContinueRx USBD StatusTypeDef USBD CtlSendStatus USBD StatusTypeDef USBD CtlReceiveStatus USBD GetRxCount USBD GetRxCount v usbd core c HAL PCD EP Transmit HAL PCD EP Receive HAL PCD EP Open HAL PCD EP Transmit HAL PCD EP Close HAL PCD EP Receive stm32fxxx hal pcd c MS34128V1 Core interface with low level driver As mentioned before the USB device library interfaces with the STM32Cube HAL low layer drivers using a low level interface layer which acts as a link layer with the STM32Cube HAL The low level interface implements low level API functions and calls some library core callback functions following some USB events In the STM32Cube package the implementation of the low level interface is provided as part of the USB device examples since some parts of the low level interface are board and system dependent Table 4 lists the low level API functions These APIs are provided by the USB Device Configuration file usbd conf c They should be implemented in the user files and adapted to the USB Device Controller Driver The user can start from the usbd conf c file provided within STM32Cube package This file can also be copied to the application folder and modified depending on the application needs Table 4 API description API Description USBD LL Init
13. BOT data IN Stage void MSC BOT DataOut USBD HandleTypeDef pdev uint8 t epnum static void MSC BOT CBW Decode USBD HandleTypeDef pdev Handles the BOT data OUT Stage Decodes the CBW command and sets the BOT state machine accordingly static void MSC BOT SendData USBD HandleTypeDef pdev uint8 t buf uint16 tlen void MSC BOT SendCSW USBD HandleTypeDef pdev uint8 t CSW Status Sends the requested data Sends the Command Status Wrapper static void MSC BOT Abort USBD HandleTypeDef pdev Aborts the current transfer void MSC BOT OplCIrFeature USBD HandleTypeDef pdev uint8 t epnum Completes the Clear Feature request DoclD025934 Rev 3 35 59 USB device library class module UM1734 36 59 Table 17 usbd_msc_scsi c h Functions int8 t SCSI_ProcessCmd USBD_HandleTypeDef pdev uint8 tlun uint8 t params Description Processes the SCSI commands static int8 t SCSI TestUnitReady USBD HandleTypeDef pdev uint8 tlun uint8 t params Processes the SCSI Test Unit Ready command static int8 t SCSI Inquiry USBD HandleTypeDef pdev uint8_t lun uint8 t params Processes the Inquiry command static int8 t SCSI ReadCapacity10 USBD HandleTypeDef pdev uint8 t lun uint8 t params Processes the Read Capacity 10 command static int8 t SCSI ReadFormatCapacity USBD HandleTypeDef pdev uint8 t lun uint8 t params Processe
14. USBD LL DevConnected USBD HandleTypeDef pdev Handles Incomplete ISO OUT transaction Event Notifies about device connection from ISR USBD StatusTypeDef USBD LL DevDisconnected USBD HandleTypeDef pdev Notifies about device disconnection from ISR Table 10 usbd ioreq c h files functions Functions USBD StatusTypeDef USBD CtlSendData USBD HandleTypeDef pdev uint8 t pbuf uint16 tlen DoclD025934 Rev 3 Description Sends the data on the control pipe 25 59 USB device library overview UM1734 26 59 Table 10 usbd ioreq c h files functions continued Functions USBD StatusTypeDef USBD CtlContinueSendData USBD HandleTypeDef pdev uint8 t pbuf uint16 tlen Description Continues sending data on the control pipe USBD StatusTypeDef USBD CtlPrepareRx USBD HandleTypeDef pdev uint8 t pbuf uint16 t len Prepares the core to receive data on the control pipe USBD StatusTypeDef USBD CtlContinueRx USBD HandleTypeDef pdev uint8 t pbuf uint16 tlen Continues receiving data on the control pipe USBD StatusTypeDef USBD CtlSendStatus USBD HandleTypeDef pdev Sends a zero length packet on the control pipe USBD StatusTypeDef USBD CtlReceiveStatus USBD HandleTypeDef pdev Receives a zero length packet on the control pipe uintG t USBD GetRxCount USBD HandleTypeDef pdev uint8 tep addr Returns the re
15. amp USBD Device amp MSC Desc 0 amp USBD MSC HAL PCD IRQHandler amp hpcd MS34127V1 1 The red text identifies the USB device configuration As shown in the Figure 7 USB device library process flowchart only the following modules are necessary for USB programming USB library USB Device class and main application 18 59 DocID025934 Rev 3 Ly UM1734 USB device library overview Note 5 1 2 2 The main application executes the user defined program main c stm32fxx it c usbd_conf c and usbd_desc c together with their header files are the main files mandatory for the application that the user needs to develop his own application The user can modify them according to his application requirements class driver Only simple APIs are called They allows interfacing between the application layer and the USB library module which handles the USB initialization and getting the current status of the USB To initialize the USB HAL driver the USB device library and the hardware on the used board BSP and to start the library the user application must call these three APIs e USBD Init This function initializes the device stack and loads the class driver The device descriptor is stored in the usbd desc c and usbd desc h used for the configuration descriptor type files e USBD RegisterClass This function links the class driver to the device core e USBD_Sta
16. can return the correct descriptor buffer relative to the application index using a switch case statement 2 How can the mass storage class driver support more than one logical unit LUN In the usbd msc storage template c file all the APIs needed to use physical media are defined Each function comes with the LUN parameter to select the addressed media The number of supported LUNs can be changed using the define STORAGE LUN NBR in the usbd msc storage xxx c file where xxx is the medium to be used For the inquiry data the STORAGE Inquirydata buffer contains the standard inquiry data for each LUN Example 2 LUNs are used const int8 t STORAGE Inquirydata LUN 0 0x00 0x80 0x02 0x02 USBD STD INQUIRY LENGTH 5 0x00 0x00 0x00 Sg STe SM Ryo Hg Kou e E UU A Manufacturer 8 bytes TM tux EE TEN LONG Torp Dt tot A Product 16 Bytes EE ETSI Gut Cp IE de Ws E tt UO 0 Version 4 Bytes LUN O 0x00 0x80 0x02 0x02 USBD STD INQUIRY LENGTH 5 0x00 0x00 0x00 Sh Me MOS E 4 Kg E E ty Wo Manufacturer 8 bytes 2 56 59 DoclD025934 Rev 3 UM1734 Frequently asked questions 2 UNS a Mine Lar 1 Y t E mn NG Product 16 Bytes UE ME UEM a tar a i 111 CO 0 Version 4 Bytes NG Where endpoints address are defined Endpoints address are defined in the he
17. device address Non All 80 00 01 00 00 0 Gets the device descriptor EIER IIBER Sei temen GET DESCRIPTOR 9 Gets the string descriptor where N is the All 80 N 03 LangiD Non valid string index This request is valid O only when the string descriptor is supported GET CONFIGURATION A C 80 00 00 00 00 1 Gets the device configuration SET CONFIGURATION lA 680 N o0 oo oo og 55 the device configuration where N is the valid configuration number GET_INTERFACE C 81 00 00 N 00 4 Cels the alternate setting of the interface N where N is the valid interface number Sets alternate setting M of the interface N where N is the valid interface number PELINFERFAGE E a M og N 901 900 and M is the valid alternate setting of the interface N Note In column State D Default state A Address state C Configured state All All states 2 EP DO D3 endpoint address D4 D6 Reserved as zero D7 0 OUT endpoint 1 IN endpoint DoclD025934 Rev 3 17 59 USB device library overview UM1734 Non standard requests All the non standard requests are passed to the class specific code through callback functions SETUP stage The library passes all the non standard requests to the class specific code with the callback pdev gt pClass gt Setup pdev req function The non standard requests include the user interpreted requests and the invalid requests User interpreted requests are class specific requests ve
18. device request the host sends a device request on the default pipe of e bmRequestType Class Interface device to host e bRequest field set to 254 FEh e wValue field set to O e windex field set to the interface number e wLength field set to 1 2 34 59 DoclD025934 Rev 3 UM1734 USB device library class module 6 2 3 2 MSC Core files Table 15 usbd msc c h files Functions uint8 t USBD MSC Init USBD HandleTypeDef pdev uint8 t cfgidx Description Initializes the MSC interface and opens the used endpoints uint8 t USBD MSC Delnit USBD HandleTypeDef pdev uint8 t cfgidx De initializes the MSC layer and close the used endpoints uint8 t USBD MSC Setup USBD HandleTypeDef pdev USBD SetupReqTypedef req Handles the MSC specific requests uint8 t USBD MSC Dataln USBD HandleTypeDef pdev uint8 t epnum Handles the MSC Data In stage uint8 t USBD MSC DataOut USBD HandleTypeDef pdev uint8 t epnum Handles the MSC Data Out stage Table 16 usbd msc bot c h files Functions void MSC BOT Init USBD HandleTypeDef pdev Description Initializes the BOT process and physical media void MSC BOT Reset USBD HandleTypeDef pdev Resets the BOT Machine void MSC BOT Delnit USBD HandleTypeDef pdev De Initializes the BOT process void MSC BOT Dataln USBD HandleTypeDef pdev uint8 t epnum Handles the
19. mute state static int8 t Audio PeriodicTC uint8 t cmd Handles the end of current packet transfer not needed for the current version of the driver static int8 t Audio GetState void Returns the current state of the driver audio player Playing Paused Error The usbd audio if template c h file provides a template driver which allows you to implement additional functions for your Audio application The Audio player state is managed through the following states Table 25 Audio player states State Code Description AUDIO CMD START 0x01 Audio player is initialized and ready AUDIO CMD PLAY 0x02 Audio player is currently playing AUDIO CMD STOP 0x04 Audio player is stopped How to use this driver This driver uses an abstraction layer for hardware driver i e HW Codec 12S interface I2C control interface This abstraction is performed through a lower layer i e usbd audio if c which you can modify depending on the hardware available for your application To use this driver 1 Configure the audio sampling rate define USBD AUDIO FREQ through the file usbd conf h 2 Call the USBD AUDIO Init function at startup to configure all necessary firmware and hardware components application specific hardware configuration functions are also called by this function The hardware components are managed by a lower layer interface i e usbd audio if c and can be modified by user
20. B device library architecture oooooooccooooccoo eee 10 Driver architecture overview liliis 11 USBD_HandleTypedef 0 ell 13 USB device library directory structure ee 15 Data structure for SETUP packet es 16 USB device library process flowchart cece eee 18 USB device data flow le 20 USB device library interfacing model ene 21 USB Class callback structure llle 27 USB device descriptors structure o oooooocooo tees 28 Example of USBD HID SendReport function 20 eeeee 31 BOT Protocol architecture ns 33 Disk operation structure description llle 37 Example of standard inquiry definition liliis 37 DFU Interface state transitions diagram 1 2 0 eee 40 Audio core structures 00 000 aa a a ea rea a E E A E pa E T 45 CDC core structures liiis e 49 CDC interface callback structure liliis 50 Example of USB descriptors declared as COonstantS o oooooooooooooo 54 Example of dynamic memory allocation for class structure o o o oooooooo 55 DoclD025934 Rev 3 5 59 Overview UM1734 1 1 1 2 1 3 6 59 Overview Acronyms and abbreviations Table 1 gives a brief definition of acronyms and abbreviations used in this document Table 1 List of terms Term Meaning API Application Programming Interface
21. D CDC ItfTypeDef The functions pointed by this structure are listed in the following sections DoclD025934 Rev 3 49 59 USB device library class module UM1734 Note 50 59 If a function is not supported by a given memory interface the relative field is set as NULL value In order to get the best performance it is advised to calculate the values needed for the following parameters all of them are configurable through defines in the usbd cdc h and usbd cdc interface h files Table 27 Configurable CDC parameters Typical value Define Parameter Full Speed High Speed CDC DATA HS IN PACKET SIZE CDC DATA FS IN PACKET SIZE Size of each IN data packet 64 512 CDC DATA HS OUT PACKET SI ZE CDC DATA FS OUT PACKET Size of each OUT data packet 64 512 SIZE Total size of circular temporary buffer for OUT data transfer 2048 2048 APP TX DATA SIZE Total size of circular temporary buffer for IN data transfer a D APP RX DATA SIZE usbd cdc interface c h This driver can be part of the user application It is not provided in the library but a template usbd cdc if template c h can be used to build it and an example is provided for the USART interface It manages the low layer CDC hardware The usbd cdc interface c h driver manages the terminal interface configuration and communication i e USART interface configuration and data send receive This drive
22. DFU protocol It uses sub requests to manage memory addressing command processing specific memory operations that is memory erase etc As required by the DFU specification only endpoint 0 is used in this application Other endpoints and functions may be added to the application that is HID etc These aspects may be enriched or modified for a specific user application The USB driver does not implement the Manifestation Tolerant mode defined in the specification However it is possible to manage this feature by modifying the driver 2 DoclD025934 Rev 3 UM1734 USB device library class module 6 3 1 2 Device firmware upgrade DFU class implementation The DFU transactions are based on endpoint 0 control endpoint transfer All requests and status control are sent received through this endpoint The DFU state machine is based on the following states Table 19 DFU states State State code appIDLE Ox00 appDETACH 0x01 dfulDLE 0x02 dfuDNLOAD SYNC 0x03 dfuDNBUSY 0x04 dfuDNLOAD IDLE 0x05 dfuMANIFEST SYNC 0x06 dfuMANIFEST 0x07 dfuMANIFEST WAIT RESET 0x08 dfuUPLOAD IDLE 0x09 dfuERROR Ox0A The allowed state transitions are described in the specification document DoclD025934 Rev 3 39 59 USB device library class module UM1734 Figure 16 DFU Interface state transitions diagram DFU_DETACH 0 1 appIDLE appDETACH Detach Time
23. Driver APls All HID class driver APIs are defined in usbd hid c and summarized in the table below Table 13 usbd hid c h files Functions Description static uint8 t USBD HID Init Initializes the HID interface and open the used USBD HandleTypeDef pdev uint8 t cfgidx endpoints static uint8 t USBD HID Delnit Un Initializes the HID layer and close the used USBD HandleTypeDef pdev uint8 t cfgidx endpoints static uint8 t USBD HID Setup USBD HandleTypeDef pdev Handles the HID specific requests USBD SetupReqTypedef req uint8 t USBD HID SendReport USBD HandleTypeDef pdev uint8 t report Sends HID reports uint16 t len The HID stack is initialized by calling the USBD HID Init Then the application has to call the USBD HID SendReport function to send the HID reports The Following HID specific requests are implemented through the endpoint 0 Control define HID REQ SET PROTOCOL 0x0B define HID REQ GET PROTOCOL 0x03 define HID_REQ_SET_IDLE Ox0A define HID_REQ_GET_IDLE 0x02 define HID_REQ_SET_REPORT 0x09 define HID REQ GET REPORT 0x01 The IN endpoint address and the maximum number of bytes that can be sent are given by these defines tdefine HID EPIN ADDR 0x81 tdefine HID EPIN SIZE 0x04 Mass storage class Mass storage class implementation This module manages the MSC class V1 0 following the Universal S
24. G FS core and 1024 x 32 bits 4 Kbytes for the USB OTG HS core For STM32F0 STM32L0 STM32F1 and STM32F3 series FS core only HAL_PCD_PMA_Config Is the USB device library compatible with Real Time operating system RTOS Yes The USB device library could be used with RTOS the CMSIS RTOS wrapper is used to make abstraction with OS kernel DoclD025934 Rev 3 57 59 Revision history UM1734 8 58 59 Revision history Table 30 Document revision history Date 27 May 2014 Revision 1 Changes Initial release 28 Nov 2014 Updated Section Introduction Figure 1 STM32Cube block diagram and Section 2 1 Overview All figures added missing titles updated figure style and clarified color codes updated sequence to use the driver in Section 6 3 2 Device firmware upgrade DFU Class core files Section 6 4 3 How to use this driver Section 6 5 6 How to use and Section 6 6 Adding a custom class 27 May 2015 Section Introduction updated and merged with section STM32Cube overview d DoclD025934 Rev 3 UM1734 IMPORTANT NOTICE PLEASE READ CAREFULLY STMicroelectronics NV and its subsidiaries ST reserve the right to make changes corrections enhancements modifications and improvements to ST products and or to this document at any time without notice Purchasers should obtain the latest relevant information on ST products before placing orders S
25. IES ooo uud gd uod hater eee rer Rede A 24 usbd ioreq c h files functions llle II 25 usbd ctrlq c h files functions III 26 USB device class files hn 30 usbd hid OWIES is NP E iaa A 32 SCSI commands iex E A SR IA Ad RE ndn X 34 USDA MSC Oh files csl aa LERRA a eed et eae a aaa 35 usbd msc bot c h files c neiere ee eee 35 USDA MSC SCS Miranda aaa a NAN gehe tere a bead 36 Disk operation functions n 38 DFU States ood eet c od Re nee a va a deni Pe i RR RR ee 39 Supported requests xi sas ise gu ears ee ae dra RAANG ADR S 41 usbd a ool dose bed edo eerte Ghar 41 Audio control requests liliis 44 usbd audio core c h files 2 2 n 44 usbd audio if c h files tees 46 Audio player states 002 maa sus a lla e a pla E Ra p EEG 46 usbd cdc c h fles lle AEN TEER 49 Configurable CDC parameters liiis 50 usbd cdc interface c h fles llle 50 Variables used by usbd cdc xxx i c h liliis 51 Document revision history llle 58 2 DoclD025934 Rev 3 UM1734 List of figures List of figures Figure 1 Figure 2 Figure 3 Figure 4 Figure 5 Figure 6 Figure 7 Figure 8 Figure 9 Figure 10 Figure 11 Figure 12 Figure 13 Figure 14 Figure 15 Figure 16 Figure 17 Figure 18 Figure 19 Figure 20 Figure 21 2 STM32Cube USB device library o ooooccoconccco eh 8 US
26. L StatusTypeDef HAL PCD EP Open PCD HandleTypeDef hpcd uint8 t ep addr uint16 t ep mps uint8 tep type HAL StatusTypeDef HAL PCD EP Close PCD HandleTypeDef hpcd uint8 t ep addr ep addr ep mps and ep type are respectively the endpoint address the maximum data transfer and transfer type Device core structure The main structure used in the device library is the device handle Its type is USBD HandleTypedef see Figure 4 on page 13 The USB Global device structure contains all the variables and structures used to keep all the information related to devices in real time as well as store the control transfer state machine and the endpoint information and status In this structure dev config holds the current USB device configuration and epO state controls the state machine with the following states EPO State define USBD EPO IDLE define USBD EPO SETUP define USBD EPO DATA IN define USBD EPO DATA OUT U U define USBD EPO STATUS IN define USBD EPO STATUS OUT define USBD EPO STALL NU F WN PB O In this structure dev state defines the connection configuration and power status Device Status define USBD DEFAULT define USBD ADDRESSED define USBD CONFIGURED define USBD SUSPENDED BRB wd B d DoclD025934 Rev 3 UM1734 USB OTG Hardware Abstraction Layer Note 2 The USB specification see Chapter 9 defines six USB device states Attached the devi
27. Low level initialization USBD LL Delnit Low level de initialization USBD LL Start Low level start USBH LL Stop Low level stop USBD LL OpenEP Initializes an endpoint USBD LL CloseEP Closes and de initializes an endpoint state 2 DoclD025934 Rev 3 UM1734 USB device library overview Table 4 API description continued API USBD LL FlushEP Description Flushes an endpoint of the Low Level Driver USBD LL StallEP Sets a Stall condition on an endpoint of the Low Level Driver USBD LL ClearStallEP Clears a Stall condition on an endpoint of the Low Level Driver USBD LL IsStallEP Returns Stall condition USBD LL SetUSBAddress Assigns an USB address to the device USBD LL Transmit Transmits data over an endpoint USBD LL PrepareReceive Prepares an endpoint for reception USBD LL GetRxDataSize Returns the last transferred packet size 5 1 4 USB device library interfacing model The USB device library is built around central generic and portable class modules Figure 9 USB device library interfacing model User Files gt USB Device Class Application c Ki P USB Device Core Ka core 7 o s 5 3 USB Descriptor de a 5 o USBD Driver Configuration dien EE lt Device Controller Driver DCD B L
28. Status USBD HandleTypeDef pdev Handles the DFU CLRSTATUS request static void DFU GetState USBD HandleTypeDef pdev static void DFU Abort USBD HandleTypeDef pdev Handles the DFU GETSTATE request Handles the DFU ABORT request static void DFU Leave USBD HandleTypeDef pdev Handles the sub protocol DFU leave DFU mode request leaves DFU mode and resets device to jump to user loaded code Internal Flash memory is the default memory provided by the library However you can add other memories using the usbd dfu media template c template file To use the driver 1 Use the file usbd_conf h to configure The number of media memories to be supported define USBD DFU MAX ITF NUM The application default address where the image code should be loaded define USBD DFU APP DEFAULT ADD 2 Call USBD DFU Init function to initialize all memory interfaces and DFU state machine 3 All control request operations are performed through control endpoint O through the functions USBD DFU Setup and USBD DFU EPO TxReady These functions can be used to call each memory interface callback read write erase get state depending on the generated DFU requests No user action is required for these operations 4 To close the communication call the USBD DFU Delnit function When the DFU application starts the default DFU state is DFU STATE ERROR This state is set to pr
29. T products are sold pursuant to ST s terms and conditions of sale in place at the time of order acknowledgement Purchasers are solely responsible for the choice selection and use of ST products and ST assumes no liability for application assistance or the design of Purchasers products No license express or implied to any intellectual property right is granted by ST herein Resale of ST products with provisions different from the information set forth herein shall void any warranty granted by ST for such product ST and the ST logo are trademarks of ST All other product or service names are the property of their respective owners Information in this document supersedes and replaces information previously supplied in any prior versions of this document O 2015 STMicroelectronics All rights reserved 2 DoclD025934 Rev 3 59 59
30. ader file of the class driver In the case of the MSC demo case for example the IN OUT endpoints address are defined in the usbd msc h file as below define MSC EPIN ADDR 0x81 For Endpoint 1 IN define MSC EPOUT ADDR 0x01 For Endpoint 1 OUT Can the USB device library be configured to run in either High Speed or Full Speed mode Yes the library can handle the USB OTG HS and USB OTG FS core if the USB OTG FS core can only work in Full Speed mode the USB OTG HS can work in High or Full Speed mode To select the appropriate USB Core to work with user must add the following macro defines within the compiler preprocessor already done in the preconfigured projects provided with the examples USE USB HS when using USB High Speed HS Core USE USB FS when using USB Full Speed FS Core USE USB HS and USE USB HS IN FS when using USB High Speed HS Core in FS mode How can the used endpoints be changed in the USB device class driver To change the endpoints or to add a new endpoint a Perform the endpoint initialization using USBD LL OpenEPY b Configure the TX or the Rx FIFO size of the new defined endpoints in the usb conf c file using these APIs in the USBD LL Init function For STM32F2 and STM32F4 series FS and HS cores HAL PCD SetRxFiFo HAL PCD SetTxFiFo The total size of the Rx and Tx FIFOs should be lower than the total FIFO size of the used core that is 320 x 32 bits 1 25 Kbytes for USB OT
31. are received from USB OUT endpoint in the CDC core functions uint8 t UserTxBuffer APP TX DATA SIZE Increments this pointer or rolls back to start address AO when data are received over USART 6 5 6 How to use The USB driver uses an abstraction layer for hardware driver i e USART control interface This abstraction is performed through a lower layer i e stm32fxxx hal msp c which you can modify depending on the hardware available for your application To use this driver 1 Through the file usbd cdc h and usbd cdc interface h configure The Data IN and OUT and command packet sizes defines CDC DATA XX IN PACKET SIZE CDC DATA XX OUT PACKET SIZE The size of the temporary circular buffer for IN OUT data transfer define APP RX DATA SIZE and APP TX DATA SIZE The device string descriptors 2 Call the function USBD CDC Init at startup to configure all necessary firmware and hardware components application specific hardware configuration functions are called by this function as well The hardware components are managed by a lower layer 2 DoclD025934 Rev 3 51 59 USB device library class module UM1734 6 5 7 6 6 52 59 interface i e usbd cdc interface c and can be modified by user depending on the application needs 3 CDC IN and OUT data transfers are managed by two functions USBD CDC SetTxBuffer should be called by user application each time a data or a cer
32. ative to this class usbd bot c h This file handles the bulk only transfer protocol usbd scsi c h This file handles the SCSI commands usbd msc data c h This file contains the vital inquiry pages and the sense data of the mass storage devices usbd msc storage template c h usbd dfu c h This file provides a template driver which allows you to implement additional functions for MSC This file contains the DFU class callbacks driver and the configuration descriptors relative to this class usbd dfu media template if c h This file provides a template driver which allows you to implement additional memory interfaces Audio usbd audio c h usbd audio if template c h This file contains the AUDIO class callbacks driver and the configuration descriptors relative to this class This file provides a template driver which allows you to implement additional functions for Audio CDC Custom HID usbd cdc c h This file contains the CDC class callbacks driver and the configuration descriptors relative to this class usbd cdc if template c h usbd customhid c h This file provides a template driver which allows you to implement low layer functions for a CDC terminal This file contains the Custom HID class callbacks driver and the configuration descriptors relative to this class 30 59 DoclD025934 Rev 3 2
33. c uint8 t USBD CDC Setup USBD HandleTypeDef pdev USBD SetupReqTypedef req Handles the CDC control requests static uint8 t USBD CDC EPO RxReady USBD HandleTypeDef pdev Handles CDC control request data static uint8 t USBD CDC Dataln USBD HandleTypeDef pdev uint8 t epnum Handles the CDC IN data stage static uint8 t USBD CDC DataOut USBD HandleTypeDef pdev uint8 t epnum Handles the CDC Out data stage uint8 t USBD CDC Registerlnterface USBD HandleTypeDef pdev USBD CDC ItfTypeDef fops Adds CDC Interface Class uint8 t USBD CDC SetTxBuffer USBD HandleTypeDef pdev uint8 t pbuff uint16 t length Sets application TX Buffer uint8 t USBD CDC SetRxBuffer USBD HandleTypeDef pdev uint8 t pbuff Sets application RX Buffer uint8 t USBD CDC TransmitPacket USBD HandleTyp eDef pdev Transmits Transfer completed callback uint8 t USBD CDC ReceivePacket USBD HandleType Def pdev Receives Transfer completed callback The low layer hardware interfaces are managed through their respective driver structure Figure 18 CDC core structures typedef struct USBD CDC Itf int8_t Init void int8 t DeInit void int8 t Control int8 t Receive JUSBD CDC ItfTypeDef uint8 t uint8 t uint8 t uint32 t uint16 t Each hardware interface driver should provide a structure pointer of type USB
34. ce is attached to the USB but is not powered by the USB Powered the device is attached to the USB and has been powered but has not yet received any reset request Default the device is attached to the USB It is powered and reset but no unique address has been assigned to it Address the device is attached to the USB it is powered and reset and has had a unique address assigned to it Configured the device is already in address state and configured It is not in suspend state Suspended the device is attached and configured but has not detected any activity on the bus for at least 3 ms Figure 4 USBD HandleTypedef typedef struct USBD HandleTypeDef uint8_t 1d uint32_t dev_config uint32_t dev_default_config uint32_t dev_config_status USBD_SpeedTypeDef dev_speed USBD_EndpointTypeDef ep in 15 USBD EndpointTypeDef ep out 15 uint32 t ep0 state uint32 t ep0 data len uint8 t dev state uint8 t dev old state uint8 t dev address uint8 t dev connection status uint8 t dev test mode uint32 t dev remote wakeup USBD SetupReqTypedef request USBD DescriptorsTypeDef pDesc USBD ClassTypeDef pClass void pClassData void pUserData void pData USBD HandleTypeDef DoclD025934 Rev 3 13 59 USB OTG Hardware Abstraction Layer UM1734 14 59 USB data transfer flow The PCD layer provides all the APIs required to start and control a transfer flow This is done through the follo
35. ceived data length Table 11 usbd ctrlq c h files functions Functions USBD StatusTypeDef USBD StdDevReq USBD HandleTypeDef pdev USBD SetupReqTypedef req Description Handles standard USB device requests USBD StatusTypeDef USBD StdltfReq USBD HandleTypeDef pdev USBD SetupReqTypedef req Handles standard USB interface requests USBD StatusTypeDef USBD StdEPReq USBD HandleTypeDef pdev USBD SetupReqTypedef req Handles standard USB endpoint requests static void USBD GetDescriptor USBD HandleTypeDef pdev USBD SetupReqTypedef req static void USBD SetAddress USBD HandleTypeDef pdev USBD SetupReqTypedef req Handles Get Descriptor requests Sets new USB device address static void USBD SetConfig USBD HandleTypeDef pdev USBD SetupReqTypedef req Handles Set device configuration request static void USBD GetConfig USBD HandleTypeDef pdev USBD SetupReqTypedef req Handles Get device configuration request static void USBD GetStatus USBD HandleTypeDef pdev USBD SetupReqTypedef req Handles Get Status request static void USBD SetFeature USBD HandleTypeDef pdev USBD SetupReqTypedef req Handles Set device feature request static void USBD ClrFeature USBD HandleTypeDef pdev USBD SetupReqTypedef req void USBD CtlError USBD HandleTypeDef pdev USBD SetupReqTypedef req Handles Clear device feature request
36. common USB device classes HID MSC Audio CDC based on the USB device stack that supports all STM32 microcontroller series This document is applicable to all STM32 Series that feature an USB peripheral However for simplicity reason the STM32F4xx devices and STM32CubeF4 are used as reference platform To know more about the examples implementation on your STM32 device refer to the readme file provided within the associated STM32Cube firmware package amp amp DoclD025934 Rev 3 1 59 www st com Contents UM1734 Contents 1 OVEIVIEW avant a RARAS 6 1 1 Acronyms and abbreviations 0 0000 eee ee 6 1 2 Additional Information o ooooooooooooooo eee 6 1 3 References iii ds y RR RU e e RC e ftue 6 2 USB device library description lsssssss 7 2 1 OVerviOW sse cc a ROCA CR ee Raed a 7 2 2 Fates ido atero Rie ha deo E pre dodo erede Dead dra i Uus ce Din incu 8 3 USB device library architecture ooooooooorrrrmmmmmoo 9 3 1 Architecture overview eee 9 4 USB OTG Hardware Abstraction Layer oooooooommoo 11 4 1 Driver architecture illii 11 4 2 USB driver programming manual 00 00 eee eee 12 4 2 1 Configuring USB driver structure aa 12 5 USB device library overview eee 15 5 1 USB device library description lisi 19 5 1 1 USB device library flow n 15 5 1 2 USB device data flow
37. d when the last isochronous IN transfer is incomplete e IsoOUTIncomplete This callback is called when the last isochronous OUT transfer is incomplete e GetHSConfigDescriptor This callback returns the HS USB Configuration descriptor e GetFSConfigDescriptor This callback returns the FS USB Configuration descriptor e GetOtherSpeedConfigDescriptor This callback returns the other configuration descriptor of the used class in High Speed mode e GetDeviceQualifierDescriptor This callback returns the Device Qualifier Descriptor USB device descriptors structure The library provides also descriptor callback structures that allow user to manage the device and string descriptors at application run time This descriptors structure is defined as follows Figure 11 USB device descriptors structure typedef struct uint8 t GetDeviceDescriptor USBD SpeedTypeDef speed uint16_t length uint8 t GetLangIDStrDescriptor USBD SpeedTypeDef speed uint16 t length uint8 t GetManufacturerStrDescriptor USBD_SpeedTypeDef speed uint16 t length uint8 t GetProductStrDescriptor USBD SpeedTypeDef speed uint16 t length uint8 t GetSerialStrDescriptor USBD SpeedTypeDef speed uint16 t length uint8 t GetConfigurationStrDescriptor USBD SpeedTypeDef speed uint16 t length uint8 t GetInterfaceStrDescriptor USBD SpeedTypeDef speed uint16 t length USBD Descripto
38. depending on the application needs 3 The entire transfer is managed by the following functions no need for user to call any function for out transfers usbd audio Dataln and usbd audio DataOut which update the audio buffers with the received or transmitted data For Out transfers when data are received DoclD025934 Rev 3 Ly UM1734 USB device library class module they are directly copied into the audiobuffer and the write buffer wr_ptr is incremented 4 The Audio Control requests are managed by the functions USBD AUDIO Setup and USBD AUDIO EPO RxReady These functions route the Audio Control requests to the lower layer i e usbd audio if c In the current version only SET CUR and GET CUR requests are managed and are used for mute control only 6 4 4 Audio known limitations e Ifa low audio sampling rate is configured define USBD AUDIO FREQ below 24 kHz it may result in noise issue at pause resume stop operations This is due to software timing tuning between stopping 12S clock and sending mute command to the external Codec e Supported audio sampling rates range from 96 kHz to 24 kHz non multiple of 1 kHz values like 11 025 kHz 22 05 kHz or 44 1 kHz are not supported by this driver For frequencies multiple of 1000 Hz the Host will send integer number of bytes each frame 1 ms When the frequency is not multiple of 1000Hz the Host should send non integer number of bytes per frame This is in
39. dleTypeDef pdev Handles the Audio control request parsing USBD SetupReqTypedef req DocID025934 Rev 3 Ly UM1734 USB device library class module Table 23 usbd_audio_core c h files continued Functions Description static uint8 t USBD AUDIO EPO RxReady USBD HandleTypeDef pdev static uint8 t USBD AUDIO Dataln USBD HandleTypeDef pdev uint8 t epnum static uint8 t USBD AUDIO DataOut USBD HandleTypeDef pdev uint8 t epnum Handles audio control requests data Handles the Audio In data stage Handles the Audio Out data stage static uint8 t USBD AUDIO SOF Handles the SOF event data buffer update and USBD HandleTypeDef pdev synchronization static void AUDIO REQ GetCurrent USBD HandleTypeDe Handles the GET CUR Audio control request f pdev USBD SetupReqTypedef req static void AUDIO REQ SetCurrent USBD HandleTypeDe Handles the SET CUR Audio control request f pdev USBD SetupReqTypedef req The low layer hardware interfaces are managed through their respective driver structure Figure 17 Audio core structures typedef struct int8 t Init uint32 t AudioFreq uint32 t Volume uint32 t options int8 t DeInit uint32 t options int8 t AudioCmd uint8 t pbuf uint32 t size uint8 t cmd int8 t VolumeCtl uint8 t vol int8 t MuteCtl uint8 t cmd int8 t PeriodicTC uint8 t cmd
40. e generates a detach attach sequence on the bus when it receives this request The firmware image is downloaded via the control write DFU DNLOAD 0x01 transfers initiated by the DFU DNLOAD class specific request DFU UPLOAD 0x02 The purpose of the upload is to provide the capability of retrieving and archiving a device firmware The host employs the DFU GETSTATUS request to DEREGETPSTATUA 9x03 facilitate synchronization with the device Upon receipt of DFU_CLRSTATUS the device sets a DES fecto ALS om status of OK and transitions to the dfulDLE state DFU_GETSTATE 0x05 This request solicits a report about the state of the device DFU_ABORT 0x06 The DFU ABORT request enables the host to exit from certain states and to return to the DFU IDLE state Each transfer to the control endpoint belong to one of the two main categories e Data transfers These transfers are used to Get some data from the device DFU_GETSTATUS DFU_GETSTATE and DFU UPLOAD Or to send data to the device DFU DNLOAD e No Data transfers These transfers are used to send control requests from host to device DFU_CLRSTATUS DFU_ABORT and DFU DETACH Device firmware upgrade DFU Class core files usbd_dfu c h This driver is the main DFU core It allows the management of all DFU requests and state machine lt does not directly deal with memory media managed by lower layer drivers Table 21 usbd_dfu c h fi
41. ead mainly for the ROM memory For this it s advised to use static allocation for the low memory STM32 devices or when multi instance support is not needed In that case it s necessary to declare a static buffer having the size of the class handle structure 2 DoclD025934 Rev 3 UM1734 USB device library class module Below an example of implementation 1 Inusbd conf h file define the memory static allocation and routines USBD static malloc and USBD static free Zdefine MAX STATIC ALLOC SIZE 4 HID Class structure size define USBD malloc uint32 t USBD static malloc define USBD free USBD static free 2 The implementation is done in usbd conf c file as below Figure 21 Example of dynamic memory allocation for class structure param size size of allocated memory retval None y 3 brief static single allocation Ez void USBD static malloc uint32 t size static uint32 t mem MAX STATIC ALLOC SIZE return mem brief Dummy memory free param p pointer to allocated memory address retval None xi void USBD static free void p 2 DoclD025934 Rev 3 55 59 Frequently asked questions UM1734 7 Frequently asked questions 1 How can the Device and string descriptors be modified on the fly In the usbd_desc c file the descriptor relative to the device and the strings can be modified using the Get Descriptor callbacks The application
42. erial Bus Mass Storage Class MSC Bulk Only Transport BOT Version 1 0 Sep 31 1999 This driver implements the following aspects of the specification e Bulk only transport protocol e Subclass SCSI transparent command set ref SCSI Primary Commands 3 The USB mass storage class is built around the Bulk Only Transfer BOT It uses the SCSI transparent command set DocID025934 Rev 3 Ly UM1734 USB device library class module d A general BOT transaction is based on a simple basic state machine It begins in ready state idle state If a CBW is received from the host three cases can be managed DATA OUT STAGE when the direction flag is set to 0 the device must be prepared to receive an amount of data indicated in cbw dDataLength in the CBW block At the end of data transfer a CSW is returned with the remaining data length and the STATUS field DATA IN STAGE when direction flag is set to 1 the device must be prepared to send an amount of data indicated in cbw dDataLength in the CBW block At the end of data transfer a CSW is returned with the remaining data length and the STATUS field ZERO DATA in this case no data stage is required and the CSW block is sent immediately after the CBW one Figure 13 BOT Protocol architecture Ready Command Transport CBW Data OUT EE Data IN Ally Status Transport
43. fact managed by sending frames with different sizes i e for 22 05 kHz the Host will send 19 frames of 22 bytes and one frame of 23 bytes This difference of sizes is not managed by the Audio core and the extra byte will always be ignored It is advised to set a high and standard sampling rate in order to get best audio quality i e 96 kHz or 48 kHz Note that maximum allowed audio frequency is 96 kHz this limitation is due to the Codec used on the Evaluation board The STM32 12S cell enables reaching 192 kHz 6 5 Communication device class CDC The USB driver manages the Universal Serial Bus Class Definitions for Communications Devices Revision 1 2 November 16 2007 and the sub protocol specification of Universal Serial Bus Communications Class Subclass Specification for PSTN Devices Revision 1 2 February 9 2007 This driver implements the following aspects of the specification e Device descriptor management e Configuration descriptor management e Enumeration as CDC device with 2 data endpoints IN and OUT and 1 command endpoint IN e Request management as described in section 6 2 in specification e Abstract Control Model compliant e Union Functional collection using 1 IN endpoint for control e Data interface class Note For the Abstract Control Model this core can only transmit the requests to the lower layer 2 dispatcher i e usbd cdc vcp c h which should manage each request and perform relative actions
44. ibrary comes on top of the STM32Cube USB device HAL driver and offers all the APIs required to develop a USB device application The present document describes the STM32Cube USB device library middleware module and illustrates how the user can develop easily his own USB device application by using this library The USB device library is a part of STM32Cube package for each STM32 series It contains e The USB low level driver e Commonly used USB class drivers e A set of applications for the most common USB device classes supporting USB Full speed and High speed transfer types control interrupt bulk and isochronous The USB device library aim is to provide at least one firmware demonstration per USB transfer type e Human Interface Device HID HID Joystick demonstration based on the embedded joystick on the EVAL boards and Custom HID examples e Audio streaming Audio device example for streaming audio data e Communication Device CDC VCP USB to RS232 bridge to realize a virtual COM port e Mass storage Mass storage demonstration based on the microSD card available on the EVAL boards e Device Firmware Upgrade DFU for firmware downloads and uploads e Dual Core devices demonstration Based on mass storage with Human interface and mass storage with CDC device examples Among the topics covered are e USB device library architecture e USB device library description e USB device library state machine overview e USB device cla
45. in the flash It is recommended to allocate all constant global variables which never change to a read only section As example the USB descriptors are declared as constant using the C keyword const Figure 20 Example of USB descriptors declared as constants USB Standard Device Descriptor const uint8 t USBD DeviceDesc USB LEN DEV DESC 0x12 bLength USB DESC TYPE DEVICE bDescriptorType 0x00 bcdUSB 0x02 0x00 bDeviceClass 0x00 bDeviceSubClass 0x00 bDeviceProtocol USB MAX EPO SIZE bMaxPacketSize LOBYTE USBD VID idVendor HIBYTE USBD_VID idVendor LOBYTE USBD PID idVendor HIBYTE USBD PID idVendor 0x00 bcdDevice rel 2 00 0x02 USBD IDX MFC STR Index of manufacturer string USBD IDX PRODUCT STR Index of product string USBD IDX SERIAL STR Index of serial number string USBD MAX NUM CONFIGURATION bNumConfigurations USB DeviceDescriptor Use static memory allocation rather than malloc The USB device library uses dynamic memory allocation for a class handle structure to allow multi instance support in case of the dual core operation this means for example we can have same USB class used for the two instances of the USB HS and FS The secondary reason for using dynamic allocation is to allow freeing memory when USB is no more used However dynamic memory allocation adds some footprint overh
46. incomplete isochronous transfers for more information refer to the USB audio device example EPO TxSent and EPO RxReady could be eventually used when the application needs to handle events occurring before the Zero Length Packets see the DFU example Memory allocation process Memory is allocated to the applications using the malloc USBD malloc USBD malloc sizeof USBD CUSTOM CLASS HandleTypeDef this is dynamically allocates memory for a Class structure Library footprint optimization In this section we review some basic tips about how to optimize the footprint of an application developed on top of the USB device library Reducing the USB examples footprint is important objective especially for STM32 products with small Flash RAM memory size such as STM32 LO and FO series Reduce the heap and stack size settings in the Linker file The stack is the memory area where the program stores Local variables Return addresses Function arguments Compiler temporaries Interrupt contexts If your linker configuration reserves more amounts of heap and stack than necessary for your application you can determine accurately the appropriate sizes DoclD025934 Rev 3 53 59 USB device library class module UM1734 54 59 Whenever possible use local instead if global variables If a variable is used only in a function then it should be declared inside the function as a local variable Constant should be allocated
47. io Control endpoint management e Audio Control requests other than SET CUR and GET CUR e Abstraction layer for Audio Control requests only mute functionality is managed e Audio Synchronization type Adaptive e Audio Compression modules and interfaces e MIDI interfaces and modules e Mixer Selector Processing Extension Units featured unit is limited to Mute control e Any other application specific modules e Multiple and Variable audio sampling rates e Audio Out Streaming Endpoint Interface microphone Audio class implementation The Audio transfers are based on isochronous endpoint transactions Audio control requests are also managed through control endpoint endpoint 0 In each frame an audio data packet is transferred and must be consumed during this frame before the next frame The audio quality depends on the synchronization between data transfer and data consumption This driver implements simple mechanism of synchronization relying on accuracy of the delivered 12S clock At each start of frame the DoclD025934 Rev 3 43 59 USB device library class module UM1734 6 4 2 44 59 driver checks if the consumption of the previous packet has been correctly performed and aborts it if it is still ongoing To prevent any data overwrite two main protections are used e Using DMA for data transfer between USB buffer and output device registers 12S e Using multi buffers to store data received from USB Based on thi
48. les Functions Description static uint8 t USBD DFU Init USBD HandleTypeDef pdev uint8 t cfgidx itlalizes the DFU interface static uint8 t USBD DFU Delnit USBD HandleTypeDef pdev uint8_t cfgidx Deiniiializes the DFU layer static uint8 t USBD DFU Setup USBD HandleTypeDef pdev Handles the DFU request parsing USBD SetupReqTypedef req static uint8 t USBD DFU EPO TxReady USBD HandleTypeDef pdev Handles the DFU control endpoint data IN stage static uint8 t USBD DFU EPO RxReady Handles the DFU control endpoint data OUT USBD HandleTypeDef pdev stage DoclD025934 Rev 3 41 59 USB device library class module UM1734 Note Note 42 59 Table 21 usbd_dfu c h files continued Functions static uint8_t USBD_DFU_GetUsrStringDesc USBD HandleTypeDef pdev uint8 t index uint16 t length Description Manages the transfer of memory interfaces string descriptors static void DFU Detach USBD HandleTypeDef pdev USBD SetupReqTypedef req Handles the DFU DETACH request static void DFU Download USBD HandleTypeDef pdev USBD SetupReqTypedef req Handles the DFU DNLOAD request static void DFU Upload USBD HandleTypeDef pdev USBD SetupReqTypedef req Handles the DFU UPLOAD request static void DFU GetStatus USBD HandleTypeDef pdev Handles the DFU GETSTATUS request static void DFU Clear
49. mum number of supported USBD MAX NUM INTERFACES Interfaces 1 to 255 Common USBD MAX STR DESC SIZ Maximum size of string descriptors configuration uint16 USBD_SELF_POWERED USBD_DEBUG_LEVEL Enables self power feature 0 1 Debug and log level G USBD_SUPPORT_USER_STRIN Enables user string support 0 1 Mass Storage configuration MSC_MEDIA_PACKET Media O buffer size multiple of 512 bytes 512 to 32 Kbytes HID Configuration NA DoclD025934 Rev 3 NA 2 UM1734 USB device library overview Table 6 USB library configuration continued item Parameter Description Maximum media interface number 1 to 2551 Media l O buffer size multiple of 512 bytes 512 to 32 Kbytes USBD DFU APP DEFAULT ADD Application address 0x0800C000 CDC Configuration NA NA Audio Configuration USBD AUDIO FREQ 8 to 48 KHZ USBD DFU MAX ITF NUM DFU Configuration NEED DFU XFER_SIZE Note The user can start from the usbd_conf c file provided within STM32Cube package This file could be also copied to the application folder and modified depending on the application needs By default for USB device examples library and user messages are not displayed on the LCD However the user can implement his own messages To redirect the library messages on the LCD screen lcd log c driver must be added to the application sources He can choose to displa
50. ndard requests on the control endpoint 0 DoclD025934 Rev 3 15 59 USB device library overview UM1734 The format and the meaning of the class specific requests and the vendor specific requests are not common for all USB devices All SETUP requests are processed with a state machine implemented in an interrupt model An interrupt is generated at the end of the correct USB transfer The library code receives this interrupt In the interrupt process routine the trigger endpoint is identified If the event is a setup on endpoint O the payload of the received setup is saved and the state machine starts Transactions on non control endpoint The class specific core uses non control endpoints by calling a set of functions to send or receive data through the data IN and OUT stage callbacks Data structure for the SETUP packet When a new SETUP packet arrives all the eight bytes of the SETUP packet are copied to an internal structure USB SETUP REQ req so that the next SETUP packet cannot overwrite the previous one during processing This internal structure is defined as Figure 6 Data structure for SETUP packet typedef struct usb setup req uint8_t bmRequest uint8 t bRequest uint16 t wValue uint16 t wIndex uint16 t wLength JUSBD SetupReqTypedef Standard requests Most of the requests specified in Table 3 of the USB specification are handled as standard requests in the library Table 3 lists all the standard
51. ndles the Burst Write process DoclD025934 Rev 3 2 UM1734 USB device library class module 6 2 4 Disk operation structure definition Figure 14 Disk operation structure description USBD StorageTypeDef USBD DISK fops STORAGE Init STORAGE GetCapacity STORAGE IsReady STORAGE IsWriteProtected STORAGE Read STORAGE Write STORAGE GetMaxLun STORAGE_Inquirydata hi Note MicroSD is the default media interface provided by the library However you can add other media Flash memory using the template file provided in usbd msc storage template c The storage callback for MSC class is added in the user application by calling USBD MSC RegisterStorage amp USBD Device amp USBD DISK fops The standard inquiry data are given by the user inside the STORAGE Inquiry data array They should be defined as shown in Figure 15 Figure 15 Example of standard inquiry definition int8 t STORAGE Inquirydata LUN O 0x00 0x80 0x02 0x02 STANDARD INQUIRY DATA LEN 5 0x00 0x00 0x00 S pr t Z 30 proa t aa 1 1 1 D 1 D D 1 O LM Manufacturer 8 bytes Product 16 Bytes Version Bytes 2 DoclD025934 Rev 3 37 59 USB device library class module UM1734 6 2 5 6 3 Note 38 59 Disk operation functions Table 18 Disk operation functions Functions Description int8 t STORAGE I
52. ndor specific requests or the requests that the library considers as invalid requests that the application wants to interpret as valid requests Invalid requests are the requests that are not standard requests and are not user interpreted requests Since pdev gt pClass gt Setup pdev req is called after the SETUP stage and before the data stage user code is responsible in the pdev gt pClass gt Setup pdev req to parse the content of the SETUP packet req If a request is invalid the user code has to call USBD CtlError pdev req and return to the caller of pdev gt pClass gt Setup pdev req For a user interpreted request the user code prepares the data buffer for the following data stage if the request has a data stage otherwise the user code executes the request and returns to the caller of pdev gt pClass gt Setup pdev req DATA stage The class layer uses the standard USBD CtlSendData and USBD CtlPrepareRx to send or receive data The data transfer flow is handled internally by the library and the user does not need to split the data in ep size packet Status stage The status stage is handled by the library after returning from the pdev gt pClass gt Setup pdev req callback Figure 7 USB device library process flowchart amp USBD HID amp HID Desc Anni 7 Coogee pplication amp USBD AUDIO esc amp USBD CDC amp DFU Desc ZwN Za USBD Init 8USBD Device USBD RegisterClass
53. nished to process the data sent by host Thus there is no need for circular data buffer when a packet is received from host the driver calls the lower layer OUT transfer function and waits until this function is completed before allowing new transfers on the OUT endpoint meanwhile OUT packets will be NACKed Command request management In this driver control endpoint endpoint O is used to manage control requests But a data interrupt endpoint may be used also for command management If the request data size does not exceed 64 bytes the endpoint 0 is sufficient to manage these requests The CDC driver does not manage command requests parsing Instead it calls the lower layer driver control management function with the request code length and data buffer Then this function should parse the requests and perform the required actions Command device class CDC core files usbd cdc c h This driver is the CDC core It manages CDC data transfers and control requests It does not directly deal with CDC hardware which is managed by lower layer drivers 2 DoclD025934 Rev 3 UM1734 USB device library class module 2 Table 26 usbd cdc c h files Functions static uint8_t USBD CDC Init USBD HandleTypeDef pdev uint8 t cfgidx Description Initializes the CDC interface static uint8 t USBD CDC Delnit USBD HandleTypeDef pdev uint8 t cfgidx De initializes the CDC interface stati
54. nit uint8 t lun Initializes the storage medium int8 t STORAGE GetCapacity uint8 t lun uint32 t block num uint16 t block size Returns the medium capacity and block size int8 t STORAGE IsReagy uint8 t lun Checks whether the medium is ready int8 t STORAGE JIsWriteProtected uint8_t lun Checks whether the medium is write protected Reads data from the medium blk address is given in sector unit blk len is the number of the sector to be processed int8 t STORAGE Read uint8 t lun uint8 t buf uint32 t blk addr uint16 t blk len Writes data to the medium blk address is given in sector unit blk len is the number of the sector to be processed int8 t STORAGE Write uint8 t lun uint8 t buf uint32 t blk addr uint16 t blk len int8 t STORAGE GetMaxLun void Returns the number of supported logical units Device firmware upgrade DFU class The DFU core manages the DFU class V1 1 following the Device Class Specification for Device Firmware Upgrade Version 1 1 Aug 5 2004 This core implements the following aspects of the specification e Device descriptor management e Configuration descriptor management e Enumeration as DFU device in DFU mode only e Request management supporting ST DFU sub protocol e Memory request management Download Upload Erase Detach GetState GetStatus e DFU state machine implementation ST DFU sub protocol is compliant with
55. otect the application from spurious operations before having a correct configuration DoclD025934 Rev 3 Ly UM1734 USB device library class module 6 4 Note 6 4 1 2 Audio class The USB driver manages the Audio Class 1 0 following the USB Device Class Definition for Audio Devices V1 0 Mar 18 98 The driver implements the following aspects of the specification e Device descriptor management e Configuration descriptor management e Standard AC Interface Descriptor management e 1 Audio Streaming Interface with single channel PCM Stereo mode e 1 Audio Streaming endpoint e 1 Audio Terminal Input 1 channel e Audio Class Specific AC Interfaces e Audio Class Specific AS Interfaces e Audio Control Requests only SET CUR and GET CUR requests are supported for Mute e Audio Feature Unit limited to Mute control e Audio Synchronization type Asynchronous e Single fixed audio sampling rate configurable in usbd conf h file The Audio Class 1 0 is based on USB Specification 1 0 and thus supports only Low and Full speed modes and does not allow High Speed transfers Please refer to USB Device Class Definition for Audio Devices V1 0 Mar 18 98 for more details These aspects can be enriched or modified for a specific user application This driver does not implement the following aspects of the specification but it is possible to manage these features with some modifications on this driver e Aud
56. out Application Program Mode DFU Program Mode Any Status USB Reset except OK State 10 Any State 2 3 5 6 9 dfuERROR Except 0 or 1 DFU CLRSTATUS USB Reset 7 Power On reset DFU_ABORT DFU_UPLOAD RE Enumeration Corrupt Firmware DFU_DNLOAD wlength gt 0 DFU_GETSTATUS block in i rogress DFU_UPLOAD bitCanDnload 1 progress bitcanUpload 1 3 4 9 dfuDNLOADS dfuDNBUSY dfuUPLOAD YNC IDLE DFU_UPLOAD Short Frame DFU_GETSTATUS Block complete Status Poll Timeout DFU_DNLOAD wLength gt 0 DFU_DNLOAD 6 wLength 0 5 dfuMANIFEST dfuDNLOAD SYNC IDLE Status Poll Timeout BitManifestationTo DFU_GETSTATUS lerant 1 manifestation in rogress prog State 8 0 1 2 3 5 6 9 dfuMANIFEST 10 WAIT RESET Status Poll Timeout BitManifestationTolera nt 0 State 0 1 2 5 9 10 DFU_GETSTATE DFU_GETSTATUS MS34130V1 To protect the application from spurious accesses before initialization the initial state of the DFU core after startup is dfuERROR The host must then clear this state by sending a DFU_CLRSTATE request before generating another request The DFU core manages all supported requests see Table 20 40 59 DoclD025934 Rev 3 2 UM1734 USB device library class module 6 3 2 2 Table 20 Supported requests Request Code Details When bit 3 in bmAttributes bit WillDetach is set the DFU_DETACH 0x00 devic
57. ow Level driver Core MS34131V1 Ly DoclD025934 Rev 3 21 59 USB device library overview UM1734 Table 5 shows all the device library callback functions which are called from the low level interface following some USB events Table 5 Low level Event Callback functions 5 1 5 22 59 Callback functions HAL_PCD_ComnectCallback Description Device connection Callback HAL_PCD_DatalnStageCallback Data IN stage Callback HAL_PCD_DatalnStageCallback Data OUT stage Callback HAL PCD DisconnectCallback Disconnection Callback HAL PCD ISOINIncompleteCallback ISO IN transaction Callback HAL PCD ISOINIncompleteCallback ISO OUT transaction Callback HAL PCD ResetCallback USB Reset Callback HAL PCD ResumeCallback USB Resume Callback HAL PCD SetupStageCallback Setup stage Callback HAL PCD SOFCallback Start Of Frame callback HAL PCD SuspendCallback Suspend Callback Configuring the USB device firmware library The USB device library can be configured using the usbd_conf h file The usbd_conf h is a specific configuration file used to define some global parameters and specific configurations This file is used to link the upper library with the HAL drivers and the BSP drivers Table 6 USB library configuration item Parameter Description USBD MAX NUM CONFIGURAT Maximum number of supported ION configurations 1 to 255 Maxi
58. r provides the structure pointer Figure 19 CDC interface callback structure USBD CDC ItfTypeDef USBD CDC fops DC Itf Init DC Itf DeInit DC Itf Control DC Itf Receive no a na Q Table 28 usbd cdc interface c h files Functions Description static int8 t CDC Itf Init Initializes the low layer CDC interface void static int8 t CDC Itf Delnit De initializes the low layer CDC interface void 2 DoclD025934 Rev 3 UM1734 USB device library class module Table 28 usbd cdc interface c h files Functions Description static int8 t CDC Itf Control Handles CDC control request parsing and uint8 t cmd uint8 t pbuf uint16 t length execution static int8 t CDC Itf Receive Handles CDC data reception from USB host to uint8 t pbuf uint32 t Len low layer terminal OUT transfers In order to accelerate data management for IN OUT transfers the low layer driver usbd cdc interface c h use these global variables Table 29 Variables used by usbd cdc xxx if c h Variable Usage Writes CDC received data in this buffer from USART These data will be sent over USB IN endpoint in the CDC core functions uint8 t UserRxBuffer APP RX DATA SIZE Increments this pointer or rolls it back to start the uint32 t UserTxBufPtrOut address when writing received data in the buffer UserRxBuffer Writes CDC received data in this buffer These data
59. requests and their valid parameters in the library Requests that are not in Table 3 are considered as non standard requests Table 3 Standard requests E w u u E olaaa x E o o o o o 2 3 83 53 23 29 5 C S ggasososoc O omments o 2 2 lt 2 y cy 3 x 3 552553 s gt O co O o O o O o o o O N Gets the status of the Device Gets the status of Interface where N is the valid interface number O Co o o o o z o o N GET STATUS A C 82 00 o0 00 00 2 Gets the status of endpoint O OUT direction A C 82 00 00 80 00 2 Gets the status of endpoint 0 IN direction C 82 00 00 EP 00 2 Gets the status of endpoint EP 16 59 DoclD025934 Rev 3 Ky UM1734 USB device library overview Table 3 Standard requests continued E w E o o o O P o 2252852323 5 I oe 2S 2s 29 29 S Comments O Z 223537335329 E o Sg o Sg E 2 I l I A c 00 01 00 00 00 00 Clears the device remote wakeup feature CLEAR_FEATURE Clears the STALL condition of endpoint E de o0 di PERS e 90 EP EP does not refer to endpoint 0 A C 00 01 00 00 00 00 Sets the device remote wakeup feature SET_FEATURE Sets the STALL condition of endpoint EP C 02 00 00 EP 00 00 EP does not refer to endpoint 0 SET ADDRESS D A 00 N 00 00 00 00 Sets the device address N is the valid
60. ribed in Section 5 3 in the usbd template c h available under Class Template 2 DoclD025934 Rev 3 UM1734 USB device library class module 6 7 2 directory This template contains all the functions that should be adapted to the application s needs and may be also used to implement any type of USB Device class Customizing the descriptors The descriptors retrieved by the host must be configured to describe a device depending on the specifications for the application class devices The following list is not complete but gives an overview about the various descriptors that may be required Standard device descriptor Standard configuration descriptor Standard interface descriptor for the Class that is implemented Standard endpoint descriptors for IN and OUT endpoints The firmware must configure the STM32 to enable USB transfer isochronous Bulk Interrupt or Control depending on the user application Inthe Dataln and DataOut functions the user can implement the internal protocol or state machine Inthe Setup the class specific requests are to be implemented The configuration descriptor is to be added as an array and passed to the USB device library Through the GetConfigDescriptor function which should return a pointer to the USB configuration descriptor and its length A Additional functions could be added as the IsolNIncomplete and IsoOUTIncomplete could be eventually used to handle
61. rsTypeDef e GetDeviceDescriptor This callback returns the device descriptor e GetLangIDStrDescriptor This callback returns the Language ID string descriptor 28 59 DocID025934 Rev 3 Ly UM1734 USB device library overview e GetManufacturerStrDescriptor This callback returns the manufacturer string descriptor e GetProductStrDescriptor This callback returns the product string descriptor e GetSerialStrDescriptor This callback returns the serial number string descriptor e GetConfigurationStrDescriptor This callback returns the configuration string descriptor e GetinterfaceStrDescriptor This callback returns the interface string descriptor Note The usbd desc c file provided within USB Device examples implements these callback bodies 2 DoclD025934 Rev 3 29 59 USB device library class module UM1734 6 USB device library class module The class module contains all the files related to the class implementation It complies with the specification of the protocol built in these classes Table 12 shows the USB device class files for the MSC HID DFU Audio CDC classes Table 12 USB device class files Class HID Files usbd_hid c h Description This file contains the HID class callbacks driver and the configuration descriptors relative to this class MSC DFU usbd_msc c h This file contains the MSC class callbacks driver and the configuration descriptors rel
62. rt This function allows user to start the USB device core For example the user can add additional endpoints in the usbd conf file depending on the class requirement This is done by calling USBD LL Init function The dev endpoints should contain the number of required endpoints following the USB class specifications The USB device library provides several configurations thanks to the usbd conf h file for more details refer to Section 5 1 5 Configuring the USB device firmware library on page 22 The HAL library initialization is done through the HAL Init API in the stm32fxxx hal c This function performs the following operation Reset of all peripherals Configuration of Flash prefetch Instruction cache Data cache Enabling of SysTick and configuration of 1 ms tick default clock after Reset is HSI USB device data flow The USB library USB core and USB class layer handles the data processing on endpoint O EPO through the I O request layer when a wrapping is needed to manage the multi packet feature on the control endpoint or directly from the stm32fxxx hal pcd layer when the other endpoints are used since the USB OTG core supports the multi packet feature Figure 8 illustrates this data flow scheme DoclD025934 Rev 3 19 59 USB device library overview UM1734 Note 20 59 Figure 8 USB device data flow usbd ioreq c Usbd class core c A A A USBD StatusTypeDef USBD CtlSendData
63. s mechanism if the clock accuracy or the consumption rates are not high enough it will result in a bad audio quality This mechanism may be enhanced by implementing more flexible audio flow controls like USB feedback mode dynamic audio clock correction or audio clock generation control using SOF event The driver also supports basic Audio Control requests To keep the driver simple only two requests have been implemented However other requests can be supported by slightly modifying the audio core driver Table 22 Audio control requests Request Supported Meaning SET CUR Yes ao mode On or Off can also be updated to set volume SET_MIN No NA SET_MAX No NA SET_RES No NA SET_MEM No NA GET_CUR Yes Gets Mute mode state can also be updated to get volume level GET_MIN No NA GET_MAX No NA GET_RES No NA GET_MEM No NA Audio core files usbd_audio c h This driver is the audio core It manages audio data transfers and control requests It does not directly deal with audio hardware which is managed by lower layer drivers Table 23 usbd_audio_core c h files Functions Description static uint8 t USBD_AUDIO_Init USBD_HandleTypeDef pdev uint8_t cfgidx Initializes the Audio interface static uint8 t USBD AUDIO Delnit USBD HandleTypeDef pdev uint8 t cfgidx De initializes the Audio interface static uint8 t USBD AUDIO Setup USBD Han
64. s the Read Format Capacity command static int8 t SCSI ModeSense6 USBD HandleTypeDef pdev uint8 t lun uint8 t params Processes the Mode Sense 6 command static int8 t SCSI ModeSense10 USBD HandleTypeDef pdev uint8 t lun uint8 t params Processes the Mode Sense 10 command static int8 t SCSI RequestSense USBD HandleTypeDef pdev uint8 t lun uint8 t params Processes the Request Sense command void SCSI SenseCode USBD HandleTypeDef pdev uint8 t lun uint8 t sKey uint8 t ASC Loads the last error code in the error list static int8 t SCSI StartStopUnit USBD HandleTypeDef pdev uint8 t lun uint8 t params Processes the Start Stop Unit command static int8 t SCSI Read10 USBD HandleTypeDef pdev uint8 t lun uint8 t params Processes the Read10 command static int8 t SCSI Write10 USBD HandleTypeDef pdev uint8 t lun uint8 t params static int8 t SCSI Verify10 USBD HandleTypeDef pdev uint8 t lun uint8 t params Processes the Write10 command Processes the Verify10 command static int8 t SCSI CheckAddressRange USBD HandleTypeDef pdev uint8 tlun uint32 t blk offset uint16 t blk nbr Checks if the LBA is inside the address range static int8 t SCSI ProcessRead USBD HandleTypeDef pdev uint8 t lun static int8 t SCSI ProcessWrite USBD HandleTypeDef pdev uint8 t lun Handles the Burst Read process Ha
65. sactions usbd conf template c h Template file for the low layer interface file should be customized by user and included with application file usbd def c h Common library defines The Class folder contains all the files relative to the class implementation and complies with the specification of the protocol built in these classes Table 8 Class drivers files USB class file Description usbh msc c h Mass storage class handler Massage usbh msc bot c Bulk only transfer protocol handler usbh msc scsi c h SCSI commands usbd msc data c h Vital inquiry pages and sense data HID Joystick mouse usbh hid c h HID class state handler Audio speaker usbh audio c h Audio class handler Audio speaker usbh cdc c h CDC virtual comport handler Custom HID usbd customhid c h Custom HID Class Handler DFU Class usbd dfu c h DFU class handler Table 9 usbd core c h files USBD StatusTypeDef USBD_Init USBD_HandleTypeDef pdev USBD DescriptorsTypeDef pdesc uint8 t id Functions Description Initializes the device library and loads the class driver and the user call backs USBD StatusTypeDef USBD Delnit USBD HandleTypeDef pdev De Initializes the device library USBD StatusTypeDef USBD RegisterClass USBD HandleTypeDef pdev Loads the class driver USBD ClassTypeDef pclass 24 59 2 DoclD025934 Rev 3
66. sed of the core and the class drivers e Core drivers The library core is composed of four main blocks USB core module that offers a full set of APIs to manage the internal USB device library state machine and call back processes from USB Interrupts USB Requests module that handles chapter 9 requests USB I O requests module handles low level I O requests USB Log and debug module that follows debug level USB_DEBUG_LEVEL outputs user log error and debug messages e Class drivers The USB Device classes is composed of a set predefined class drivers ready to be linked to the USB core through the USBD_RegisterClass routine The USB device library is a USB 2 0 compatible generic USB device stack compliant with all the STM32 USB cores It t can be easily linked to any USB HAL driver thanks to the configuration wrapper file which avoids any dependency between the USB library and the low level drivers DoclD025934 Rev 3 9 59 USB device library architecture UM1734 10 59 Figure 2 USB device library architecture USB Device Core Device Controller Driver DCD Low Level driver Core USB Device Class MS34125V1 1 The USB library core blocks are shown in orange the USB Device Configuration in magenta and the USB HAL driver in blue DoclD025934 Rev 3 d UM1734 USB OTG Hardware Abstraction Layer 4 USB OTG Hardware Abstraction Layer The low level driver can be u
67. sed to connect the USB OTG core with the high level stack 4 1 Driver architecture Figure 3 Driver architecture overview OTG Device PCD stm32fxxx hal pcd c h Low Layer USB Driver stm32fxxx Il usb c h Upper layer stack and high level software Low level driver MS34126V1 e The bottom layer Low Layer USB driver provides common APIs for device and OTG modes It performs the core initialization in each mode and controls of the transfer flow e The Peripheral controller driver PCD layer provides an API for device mode access and the main interrupt routine for this mode e The OTG controller driver OTG layer provides an API for OTG mode access and the main interrupt routine for this mode Note For more details on how to use the PCD driver please refer to UM1725 that describes all PCD driver APIs 2 DoclD025934 Rev 3 11 59 USB OTG Hardware Abstraction Layer UM1734 4 2 4 2 1 12 59 USB driver programming manual Configuring USB driver structure Device initialization The device is initialized using the following function contained in stm32fxxx hal pcd c file HAL_StatusTypeDef HAL_PCD_Init PCD_HandleTypeDef hpcd Endpoint configuration Once the USB core is initialized the upper layer can call the low level driver to open or close the active endpoint and start transferring data The following two APIs can be used HA
68. sses overview DoclD025934 Rev 3 7 59 USB device library description UM1734 2 2 Features The main USB device library features are e Support of multi packet transfer features allowing sending big amount of data without splitting it into max packet size transfers e Support of up to 3 back to back transfers on control endpoints compatible with OHCI controllers e Configuration files to change the core and the library configuration without changing the library code Read Only e 32 bits aligned data structures to handle DMA based transfer in High speed modes e Support of multi USB OTG core instances from user level configuration file Note The USB device library can be used with or without RTOS the CMSIS RTOS wrapper is used to make abstraction with OS kernel USB device examples do not display log messages Figure 1 STM32Cube USB device library USB device Library LI Hardware MS34124V1 1 The user application is shown in green the USB library core blocks in orange and the USB Device HAL driver in blue 2 8 59 DoclD025934 Rev 3 UM1734 USB device library architecture 3 3 1 2 USB device library architecture Architecture overview The USB device library is mainly divided into three layers The applications is developed on top of them as shown in Figure 2 USB device library architecture The first Layer is compo
69. t USBD HandleTypeDef pdev uint8 t IsoINIncomplete struct USBD HandleTypeDef pdev uint8 t epnum uint8 t IsoOUTIncomplete struct USBD HandleTypeDef pdev uint8 t epnum uint8 t GetHSConfigDescriptor uint16 t length uint8 t GetFSConfigDescriptor uint16 t length uint8 t uint8 t GetDeviceQualifierDescriptor uint16 t length USBD ClassTypeDef GetOtherSpeedConfigDescriptor uint16 t length e Init this callback is called when the device receives the set configuration request in this function the endpoints used by the class interface are open e Delnit This callback is called when the clear configuration request has been received this function closes the endpoints used by the class interface 2 DoclD025934 Rev 3 27 59 USB device library overview UM1734 e Setup This callback is called to handle the specific class setup requests e EPO TxSent This callback is called when the send status is finished e EPO RxSent This callback is called when the receive status is finished e Dataln This callback is called to perform the data in stage relative to the non control endpoints e DataOut This callback is called to perform the data out stage relative to the non control endpoints e SOF This callback is called when a SOF interrupt is received this callback can be used to synchronize some processes with the SOF e IsoINIncomplete This callback is calle
70. tain number of data is available to be sent to the USB Host from the hardware terminal USBD CDC SetRxBuffer is called by the CDC core each time a buffer is sent from the USB Host and should be transmitted to the hardware terminal This function should exit only when all data in the buffer are sent the CDC core then blocks all coming OUT packets until this function finishes processing the previous packet 4 CDC control requests should be handled by the function Controllability This function is called each time a request is received from Host and all its relative data are available if any This function should parse the request and perform the needed actions 5 To close the communication call the function USBD CDC Delnit This closes the used endpoints and calls lower layer de initialization functions CDC known limitations When using this driver with the OTG HS core enabling DMA mode define USB OTG HS INTERNAL DMA ENABLED in usb conf h file results in data being sent only by multiple of 4 bytes This is due to the fact that USB DMA does not allow sending data from non word aligned addresses For this specific application it is advised not to enable this option unless required Adding a custom class This section explains how to create a new custom class based on an existing USB class To create a new custom Class follow the steps below 1 Add USBD CustomClass cb In order to receive various USB bus Events as desc
71. wing set of functions HAL StatusTypeDef HAL PCD EP Transmit PCD HandleTypeDef hpcd uint8 t ep addr uint8 t pBuf uint32 t len HAL StatusTypeDef HAL PCD EP Receive PCD HandleTypeDef hpcd uint8 t ep addr uint8 t pBuf uint32 t len HAL StatusTypeDef HAL PCD EP SetStall PCD HandleTypeDef hpcd uint8 t ep addr HAL StatusTypeDef HAL PCD EP CirStall PCD_HandleTypeDef hpcd uint8 t ep addr HAL StatusTypeDef HAL PCD EP Flush PCD HandleTypeDef hpcd uint8 t ep addr The PCD layer contains one function that must be called by the USB interrupt void HAL PCD IRQHandler PCD HandleTypeDef hpcd The stm32fxxx hal pcd h file contains the function prototypes called from the library core layer to handle the USB events Important enumerated typedefs e USBD StatusTypeDef Almost all library functions return a status of type USBD StatusTypeDef The user application should always check the returned status typedef enum USBH_OK 0 USBH_BUSY USBH_FAIL JUSBH StatusTypeDef Table 2 describes the possible returned status Table 2 USB device status Status Description USBH OK Returned when operation is completed successfully USBH BUSY Returned when operation is still not completed busy Returned when operation has failed due to a low level error USBH FAIL F or protocol fail 2 DoclD025934 Rev 3 UM1734 USB device library overview 5 5 1 5 1 1 2 USB device library overview
72. y them or not by modifying define values in the usbd_conf h configuration file available under the project includes directory For example 0 No Log Debug messages 1 log messages enabled 2 log and debug messages enabled 5 1 6 USB control functions Device reset When the device receives a reset signal from the USB the library resets and initializes both application software and hardware This function is part of the interrupt routine Device suspend When the device detects a suspend condition on the USB the library stops all the ongoing operations and puts the system in suspend state if low power mode management is enabled in the usbd conf c file Device resume When the device detects a resume signal on the USB the library restores the USB core clock and puts the system in idle state if low power mode management is enabled in the usbd conf c file 2 DoclD025934 Rev 3 23 59 USB device library overview UM1734 5 2 USB device library functions The Core folder contains the USB device library machines as defined by the Universal Serial Bus Specification revision 2 0 Table 7 USB device core files File usbd_core c h usbd_req c h Description This file contains the functions for handling all USB communication and state machine This file includes the requests implementation listed in Chapter 9 of the specification usbd ctlreq c h This file handles the results of the USB tran
Download Pdf Manuals
Related Search
Related Contents
Informações Técnicas Xerox ColorQube 8880: Impressora Tinta Sólida 審査判定結果について Samsung 223BW Kasutusjuhend Robustes, wetterfestes Telefon Betriebsanleitung promix1212e mixer 12 canali - processore multieffetto User Manual GBEST Manuale dell`utente Manuel d`utilisation Cadre photos CP 24 Magnet YK600XC OWNER`S MANUAL MANUAL dEL USUARiO GUidE d`UTiLiSATiON Copyright © All rights reserved.
Failed to retrieve file