Home

UM1021 - STMicroelectronics

image

Contents

1. UM1021 USB device library Table 20 usbd flash if c h files Functions Description Pointer to the memory interface descriptor that allows the i host to get memory interface organization name size const uint8_t pStrDesc number of sectors pages size of sectors pages read write rights uint16_t pMAL_Init void Handles the memory interface initialization uneto E MoMA ARREN LE Handles the memory interface de initialization void pasak H COMAL eee Handles the block erase on the memory interface uint32_t Add uint16 t pMAL_Write ae luint32 t Add uint32 t Len Handles the data writing to the memory interface uint8 t pMAL Read s A uint32_t Add uint32 t Len Handles the data reading from the memory interface uint16 t pMAL_CheckAdd Returns MAL OK result if the address is in the memory uint32 t Add range Mean time for erasing a memory block sector page It is const uint32 t EraseTiming possible to set this timing value to the maximum value allowed by the memory Mean time for writing a memory block sector page It is const uint32 t WriteTiming possible to set this timing value to the maximum value allowed by the memory How to use the driver e Using the file usbd conf h you can configure The number of media memories to be supported define MAx USED MEDIA The device string descriptors The application default address where the image code should be loaded
2. define USBD VID 0x0483 define USBD PID 0x5740 define USBD LANGID STRING 0x409 define USBD_MANUFACTURER_STRING STMicroelectronics define USBD PRODUCT HS STRING STM32 Virtual ComPort in HS mode define USBD SERIALNUMBER HS STRING 00000000050B define USBD PRODUCT FS STRING STM32 Virtual ComPort in FS Mode define USBD SERIALNUMBER FS STRING 00000000050C define USBD_CONFIGURATION_HS_STRING VCP Config define USBD INTERFACE HS STRING VCP Interface define USBD CONFIGURATION FS STRING VCP Config define USBD INTERFACE FS STRING VCP Interface At power on the LCD displays the following messages Doc ID 18153 Rev 3 ky UM1021 USB device library Figure 25 USB virtual com port power on display message USB OTG VCP Device gt USB device Library started gt Device in suspend mode USB Device Library vx x x MS18195V1 When the USB cable is plugged in the LCD displays the following messages Figure 26 USB virtual com port cable connected display message USB OTG VCP Device gt USB device Library started VCP device gt Device in suspend mode configured and traffic gt VCP Interface started has started with the host USB Device Library vx x x HS Library version and Current device speed MS18196V1 When the VCP application starts the USB device is enumerated as serial communication port and can be configured in the
3. Ka fops 4USBD MICRO SDIO fops T nquirydata array It 36 Manufacturer 8 bytes Product 16 Bytes Bytes Functions int8_t STORAGE_GetCapacity lun uint32_t block_num block_size int8 t STORAGE Init uint8_t lun uint8 t uint16 t Description Initializes the storage medium Returns the medium capacity and block size Doc ID 18153 Rev 3 ky UM1021 USB device library Table 15 Functions continued Functions Description as STORAGE TsReady uint8 t Checks whether the medium is ready Intact STORAGE ISITI rey Ae GeerSe Checks whether the medium is write protected uint8_t lun int8_t STORAGE_Read uint8_t lun Reads data from the medium uint8 t buf uint32_tblk_addr blk address is given in sector unit uint16 t bik len bik len is the number of the sector to be processed int8 t STORAGE Write uint8 t lun Writes data to the medium uint8 t buf uint32 t blk addr blk address is given in sector unit uint16 t blk len bik len is the number of the sector to be processed int8 t STORAGE GetMaxLun void Returns the number of supported logical units 6 7 3 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 foll
4. USB manual dual role device example In this demonstration the user can use Host or Device mode on the same core by selecting through the menu the sub demo to run In both Device and Host modes the mass storage class is used Figure 48 USB Manual DRD example USB Manual DRD Demo gt Initializing demo gt Demo initialized gt Use joystick to select demo 1 Host demo 2 Device demo 3 Credits MS20008V1 a Doc ID 18153 Rev 3 UM1021 USB host library To move within the menu the user has to use the embedded joystick the menu structure is as follows Figure 49 Menu structure Main menu 1 Host demo 2 Device demo 3 Credits Mass storage menu 1 Explore flash content 2 Write file to disk 3 Show BMP file 4 Return HID menu 1 Return MS19715V1 Doc ID 18153 Rev 3 101 107 Frequently asked questions UM1021 8 Note Note 102 107 Frequently asked questions 1 How can the USB Device Library be configured to run in either High Speed or Full Speed mode 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 For that the user has to a Select the core to be used during the library initalization issuing one of the two core IDs USB OTG HS CORE ID USB OTG FS CORE ID Example USBD I
5. Library version and Current device speed gt AUDIO Interface started has started with the host MS18198V1 When the Application is ready for audio streaming the state footer gt State indicates Application Active state When an audio file is being played the state changes to PLAYING and when the audio file is paused or stopped the state updates to PAUSED The last line of the footer on the LCD screen indicates the current output state Headphone or Speaker For STM32F2xx and STM32F4xx devices the Headphone is selected as output by default When pushing Key button the output is switched to Speaker or to Headphone if the current output is the Speaker For STM32F105 7 devices the default state is Automatic detection when the Headphone is plugged in it is used as output and when it is unplugged output automatically switches to Speaker When pushing Key button the automatic detection is disabled and only the output set by the Key command is configured Headphone or Speaker 6 10 7 Known limitations e If alow 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 timings tuning between stopping 12S clock and sending mute command to the external codec Supported audio sampling rates are from 96 kHz to 24 kHz non multiple of 1 kHz values like 11 025 kHz
6. UM1021 YI User manual STM32F105xx STM32F107xx STM32F2xx and STM32F4xx USB On The Go host and device library Introduction The USB On The Go Host and Device Library is a firmware and application software package for USB universal serial bus hosts and devices This package includes example and demonstration software for developing applications using USB full speed and high speed transfer types control interrupt bulk and isochronous The aim of the USB OTG Host and Device Library is to provide at least one firmware example demonstration for each USB transfer type This library is designed for use with the following evaluation boards m STM3210C EVAL evaluation board UM0600 for STM32F105 7 devices STM3220G EVAL evaluation board UM1057 for STM32F20x devices STM3221G EVAL evaluation board UM1065 for STM32F21x devices STM3240G EVAL evaluation board UM1461 for STM32F40x devices STM3241G EVAL evaluation board UM1460 for STM32F41x devices This document describes all the components of a USB OTG host and device library including examples for the following types of devices m Mass storage based on the microSD card available on the evaluation boards HID joystick based on the embedded joystick on the evaluation boards Virtual COM port Direct Firmware Update based Audio OUT Dual Core based on mass storage and HID examples available only for STM322xG EVAL and STM324xG EVAL evaluation boards And the following exam
7. USBH MSC Interfacelnit USBH MSC InterfaceDelnit USBH MSC ClassRequest USBH MSC Handle yi Table 34 MSC core module description Function Description Parses interface and endpoint descriptors and configures VERNA BIAG TAE host channels bulk IN and bulk OUT pipes USBH MSC InterfaceDelnit De initialization routine freeing host channels In case of MSC this function only moves the library core BH M 1 R Deer Mec ClassRequest state machine to the HOST_CLASS state USBH_MSC_Handle Implements the MSC handler core state machine USBH_MSC_Issue_BOTReset Issues a BOT reset class request USBH_MSC_Issue_GETMaxLUN Issues a GET MAX LUN class request USBH MSC ErrorHandle MSC error handling MSC BOT module The MSC Bulk Only Transport BOT module implements the transport protocol for sending the SCSI commands such as READ 10 or WRITE 10 This module is implemented in the usbh msc bot c file For details about the BOT protocol please refer to the usb org mass storage class document The BOT module has the following functions Table 35 MSC BOT module description Function Description USBH MSC Init Initialize BOT state machine USBH MSC HandleB0TXfer BOT transfer state machine MSC SCSI module The SCSI Small Computer System Interface module usb_msc_scsi c stands on top of the BOT It implements the set of SCSI commands r
8. uint8_t bNumEndpoints Number of Endpoints used for this interface uint8_t bInterfaceClass Class Code Assigned by USB Org uint8 t bInterfaceSubClass Subclass Code Assigned by USB Org uint8_t bInterfaceProtocol Protocol Code uint8 t iInterface Index of String Descriptor Describing this interface K Doc ID 18153 Rev 3 91 107 USB host library UM1021 7 8 92 107 USBH InterfaceDesc TypeDef typedef struct 5 EndpointDescriptor f uint8 t bLength uint8 t bDescriptorType uint8 t bEndpointAddress indicates what endpoint this descriptor is describing uint8_t bmAttributes specifies the transfer type uint16 t wMaxPacketSize Maximum Packet Size this endpoint is capable of sending or receiving uint8_t bInterval is used to specify the polling interval of certain transfers USBH EpDesc TypeDef In order to move the core state machine to HOST CLASS REQUEST slate the UserInput callback should return the value USBH USR RESP OK of type USBH USR Status typedef enum USBH USR NO RESP 0 no response from user USBH_USR_RESP_OK Ty USBH_USR_Status Application layer description Figure 37 Folder organization USB Host Device Examples DRD Release Notes html USB Host Examples DualCore HID MSC EWARM DB inc MDK ARM RIDE sre TASKING TrueSTUDIO E readme be Release Not
9. D CONFIGURATION FS STRING D INTERFACE FS STRING 0x0483 0x5710 0x409 STMicroelectronics Joystick in HS mode 00000000011B Joystick in FS Mode 00000000011C HID Config HID Interface HID Config HID Interface At power on the LCD displays the following message Figure 18 USB HID power on display message USB OTG HID Device gt USB device Library started gt Device in suspend mode USB Device Library vx x x MS18189V1 When the USB cable is plugged in the LCD displays the following messages Figure 19 USB HID cable connected display message USB OTG HID Device gt USB device Library started gt Device in suspend mode gt HID Interface started USB Device Library vx x x HS HID device configured and traffic has started with the host Library version and Current device speed MS18190V1 Doc ID 18153 Rev 3 ky UM1021 USB device library The user can use the embedded joystick on the evaluation board to move the mouse pointer on the host screen 6 10 3 Dual core USB device example The Dual core USB device example integrates the two mass storage and HID example described above in same project and uses the multi core support feature The Mass storage device is connected to the High speed USB connector while the HID is connected to the Full Speed connector Note that project comes with only two configurations for the ST
10. Sets new USB device address static void USBD SetConfig USB OTG COR USB SETUP REQ rea E HANDLE pdev Handles Set device configuration request static void USBD_GetConfig USB_OTG_COR USB_SETUP_REQ req E HANDLE pdev Handles Get device configuration request static void USBD GetStatus USB OTG COR USB SETUP REQ rea FE HANDLE pdev Handles Get Status request static void USBD SetFeature USB OTG COR USB SETUP REQ rea FE HANDLE pdev Handles Set device feature request USB OTG COR static void USBD_ClrFeature FE HANDLE pdev USB SETUP REQ rea Handles Clear device feature request 34 107 Doc ID 18153 Rev 3 ky UM1021 USB device library Table 8 usbd_req c h continued Functions Description void USBD_ParseSetupRequest USB OTG CORE HANDLE pdev Copies request buffer into setup structure USB SETUP REQ req void USBD CtlError USB OTG CORE HANDLE pdev Handles USB Errors on the control pipe USB SETUP REQ rea 6 5 USB device class interface 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 typedef struct Device cb uint8 t Init void pdev uint8 t cfgidx uint8 t DeInit void pd
11. At the end of the enumeration the core calls a specific class driver function to manage all class related operations Note The proper class driver selection is not based on the result of device enumeration but it is pre defined when initializing the host library by calling the USBH_Init function A class driver is implemented using a structure of type USBH Class cb TypeDef typedef struct Device cb USBH_Status Init USB_OTG_CORE_HANDLE pdev USBH DeviceProp TypeDef hdev void DeInit USB OTG CORE HANDLE pdev USBH DeviceProp TypeDef hdev USBH_Status Requests USB_OTG_CORE_HANDLE pdev USBH DeviceProp TypeDef hdev USBH Status Machine USB OTG CORE HANDLE pdev USBH DeviceProp TypeDef hdev USBH_Class_cb_TypeDef The structure members are described below Init this function is called at the startup of a class operation for assuring all required initializations This includes Parsing interface and endpoint descriptors please note that the current USB host library supports only one interface Opening and allocating host channels for non control endpoints Calling a user callback in case the device is not supported by the class Denit this function is called for freeing allocated host channels when re initializing the host It is called when a device is unplugged or in case of unrecovered error e Requests this function implements the class request state machine It is called durin
12. 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 Doc ID 18153 Rev 3 53 107 USB device library UM1021 54 107 Audio core files usbd audio core 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 22 usbd_audio_core c h files Functions static uint8 t usbd_audio_Init void pdev uint8 t cfgidx Description Initializes the Audio interface static uint8 t usbd audio Delnit void pdev uint8 t cfgidx De initializes the Audio interface static uint8 t usbd audio Setup void pdev USB SETUP REQ rea Handles the Audio control request parsing static uint8 t usbd audio EP0 RxReady void pdev Handles audio control requests data static uint8 t usbd_audio_DataIn void pdev uint8_t epnum Handles the Audio In data stage static uint8_t usbd_audio_DataOut void pdev uint8_t epnum Handles the Audio Out data stage static uint8 t usbd_audio_SOF void pdev static void AUDIO Req GetCurrent void pdev USB SETUP REQ req Handles the SOF event data buffer update and synchronization Handles the GET CUR Audio control request static void AUDIO Req SetCurrent void pdev USB
13. define USB OTG EPO STATUS IN 4 define USB OTG EPO STATUS OUT 5 define USB OTG EPO STALL 6 uint8 t uint8 t uint8 t uint8 t uint32 t USB OTG USB OTG 1 EH lav EJ kd uint8 t USBD Class cb TypeDef DCD device config device state device status device address DevRemoteWakeup in_ep USB_OTG_MAX_TX_FIFOS out ep USB_OTG_MAX TX _FIFOS setup packet 8 3 USBD Usr cb TypeDef uint8 t usr_ch pConfig_descriptor D_DEV DCD_PDEV class cb In this structure device status defines the connection configuration and power status Device Status define USB OTG DEFA define USB OTG ADDRESSED define USB OTG CONFIGUR 18 107 ULT E3 jo N Doc ID 18153 Rev 3 a UM1021 USB OTG low level driver 4 USB data transfer flow The DCD layer offers the user all APIs needed to start and control a transfer flow using the following set of functions uint32_t DCD_EP_PrepareRx USB_OTG_CORE_HANDLE pdev uint8 t ep addr uint8 t pbuf uint16 t buf len uint32 t DCD EP Tx USB OTG CORE HANDLE pdev uint8 t ep addr uint8 t pbu uint32 t buf len uint32 t DCD EP Stall USB OTG CORE HANDLE pdev uint8 t epnum uint32 t DCD EP CIrStall USB OTG CORE HANDLE pdev uint8 t epnum uint32 t DCD EP Flush USB OTG CORE HA
14. uint32 t Initializes the audio interface Volume uint32 t options static uint8 t Delnit De initializes the audio interface and free used uint32 t options resources static uint8 t AudioCmd uint8 t pbuf uint32 t size Handles audio player commands play pause uint8 t cmd static uint8 t VolumeCtl uint8 t I Handles audio player volume control vol ti i M 1 i 5 Statio NITSO Mu pect turnt t Handles audio player mute state cmd static uint8_t PeriodicTC Handles the end of current packet transfer not uint8_t cmd needed for the current version of the driver f f Returns the current state of the driver audio static uint8_t GetState void player Playing Paused Error The Audio player state is managed through the following states Table 24 Audio player states State Code Description AUDIO_STATE_INACTIVE 0x00 Audio player is not initialized AUDIO_STATE_ACTIVE 0x01 Audio player is initialized and ready AUDIO STATE PLAYING 0x02 Audio player is currently playing AUDIO_STATE_PAUSED 0x03 Audio player is paused AUDIO_STATE_STOPPED 0x04 Audio player is stopped AUDIO STATE ERROR 0x05 Error occurred during initialization or while executing an audio command How to use this driver This driver uses an abstraction layer for hardware driver i e HW Codec 12S interface 12C control interface This abstraction is perfo
15. FS STRING MSC Config define USBD INTERFACE FS STRING MSC Interface At power on the LCD displays the following messages Figure 16 Power on display message USB OTG MSC Device 5 USB device Library started Mass storage device 5 Device in suspend mode configured and traffic 5 MSC Interface started has started with the host z Library version and USB Device Library vx x x HS ee device speed MS18187V1 When the USB cable is plugged in the LCD shows the following messages Figure 17 Cable connected display message USB OTG MSC Device 5 USB device Library started 5 Device in suspend mode USB Device Library vx x x MS18188V1 6 10 2 USB human interface device example a The HID example uses the joystick embedded in the STM322xG EVAL STM324xG EVAL or STM3210C EVAL evaluation boards The HID example works in High and Full speed modes and provides the following USB device information usbd desc c Doc ID 18153 Rev 3 65 107 USB device library UM1021 66 107 define U de de de de de de de de de de de fine fine fine fine fine fine fine fine fine fine fine USB USB USB L td C ti USB USB SBD VID D PID D LANGID STRING D MANUFACTURER STRING D PRODUCT HS STRING D SERIALNUMBER HS STRING D PRODUCT FS STRING D SERIALNUMBER FS STRING D CONFIGURATION HS STRING D INTERFACE HS STRING
16. Figure 23 USB device firmware upgrade power on display message USB OTG DFU Device gt USB device Library started gt Device in suspend mode USB Device Library vx x x MS18193V1 When the USB cable is plugged in the LCD displays the following messages Figure 24 USB device firmware upgrade cable connected display message USB OTG DFU Device gt USB device Library started DFU device gt Device in suspend mode configured and traffic gt DFU Interface started has started with the host USB Device Library vx x x HS Current device speed Library version and MS18194V1 When the DFU application starts the default state is DFU ERROR in order to prevent spurious access to the application before it is correctly configured Once the application is running the state displayed in the footer on the LCD is updated depending on the current operation After downloading a DFU image into the internal Flash and exiting from DFU mode using command Leave DFU mode of the ST DFU applet a hardware reset may be performed using RESET button on the evaluation board After reset the DFU example jumps and executes the loaded user application in the internal Flash memory Doc ID 18153 Rev 3 69 107 USB device library UM1021 Note 6 10 5 70 107 To go back to the DFU example you have to reset the device using RESET button or software reset while the KEY button is pushed If
17. HID class Doc ID 18153 Rev 3 85 107 USB host library UM1021 Table 39 HID class modules File usbh hid core c h Description This module implements the HID class core state machine usbh hid mouse c h HID mouse specific routines usbh hid keybd c h HID keyboard specific routines The main functions of each module are described below HID class core The HID core module usb hid core c implements the HID class driver structure USBH HID cb of type USBH Class cb TypeDef see Section 7 5 f USBH HID Interfacelnit USBH HID InterfaceDelnit USBH HID ClassRequest USBH HID Handle Ji USBH Class cb TypeDef USBH HID cb The following table summarizes the functions implemented in the HID core module Table 40 MSC core module functions Function USBH_HID_InterfaceInit USBH_HID_InterfaceDeInit Description Parses interface and endpoint descriptors and configures a host channel in order to have an interrupt IN pipe for getting HID reports Frees the allocated interrupt IN pipe USBH_HID_ClassRequest Implements a state machine of the required class requests for HID mouse and keyboard devices ex getting HID report descriptors setting IDLE time setting Protocol USBH HID Handle USBH Get HID ReportDescripto HID class core state machine processing of interrupt IN transfers Class request for getting HID report d
18. MSCapacity MS device capacity in bytes uint32_t MSSenseKey Request Sense SCSI command returned value uint16 t MSPageLength MS device Page length uint8_t MSBulkOutEp Bulk OUT endpoint address uint8_t MSBulkInEp Bulk IN endpoint address uint8_t MSWriteProtect Write protection status 0 non protected 1 protected MassStorageParameter_TypeDef HID user callback functions For the HID class the following callbacks are defined void USR_MOUSE_Init void user initialization for mouse application void USR KEYBRD Init void user initialization for keyboard application void USR_MOUSE_ProcessData HID_MOUSE_Data_TypeDef data this callback is called when an input parameter data of type HID MOUSE Data TypeDef see Note below is available void USR_KEYBRD_ProcessData uint8_t data this callback is called when a new ASCII character is typed The character is received in input parameter data HID MOUSE Data TypeDef is defined as follows typedef struct HID MOUSE Data uint8 t x uint8 t y uint8 t z Not Supported uint8 t button Bitmap showing pressed buttons 1 pressed 0 non pressed Ej HID_MOUSE_Data_TypeDef Class independent callback functions The class independent callback functions are defined in a structure of type USBH_Usr_cb_TypeDef as follows typedef struct _USBH_US
19. Rev 3 97 107 USB host library UM1021 7 10 2 98 107 USB HID Host example When attaching a HID device to the STM322xG EVAL STM324xG EVAL or STM3210C EVAL board the LCD displays the following text for example when plugging Logitech USB mouse or a keyboard Figure 43 USB HID Host connected display message USB OTG HS HID Host gt USB host Library started gt Device attached gt High speed detected VID 046dh PID c016h High speed device gt HID device connected has been detected gt Manufacturer Logitech and correctly enumerated gt Product Optical USB mouse gt Serial number N A gt Enumeration completed USB Device Library vx x x MS20004V1 When the user press the user key B4 the application displays the mouse pointer and buttons Figure 44 USB HID Host user key message USB OTG HS MSC Host 5 Product Optical USB mouse gt Serial number N A USB Device Library vx x x MS20005V1 Moving the mouse will move the pointer in the display rectangle and if a button is pressed the corresponding rectangle will be highlighted in green If a keyboard has been attached the display show the following messages and the taped characters are displayed in green on the display Doc ID 18153 Rev 3 ky UM1021 USB host library Note 7 10 3 4 Figure 45 USB HID Host text example message USB OTG HS HID Host gt Product Optical USB mouse g
20. To prevent this additional RAM footprint the user can redirect the Library and User messages on another terminal HyperTerminal or LCD using the native display functions Library and user messages are located in the user callbacks in the application layer They are not mandatory and they are used for information and debug purpose only They can be modified or even removed USB mass storage device example The Mass storage example uses the microSD Flash embedded in the STM322xG EVAL STM324xG EVAL and STM3210C EVAL evaluation boards as media for data storage In addition to the source files mentioned above additional files for the disk access were added to handle the microSD driver and microSD access operations The mass storage example works in High and Full speed modes and has the following USB device information usbd desc c define USBD VID 0x0483 define USBD PID 0x5720 define USBD LANGID STRING 0x409 define USBD_MANUFACTURER_STRING STMicroelectronics Doc ID 18153 Rev 3 ky UM1021 USB device library define USBD_PRODUCT_HS_STRING Mass Storage in HS Mode define USBD_SERIALNUMBER_HS_STRING 00000000001A define USBD PRODUCT FS STRING Mass Storage in FS Mode define USBD SERIALNUMBER FS STRING 00000000001B define USBD_CONFIGURATION_HS_STRING MSC Config define USBD INTERFACE HS STRING MSC Interface define USBD CONFIGURATION
21. UM1021 USB host library 7 3 3 7 3 4 7 3 5 7 3 6 7 4 The enumeration state machine is implemented in the USBH_Hand1eEnun library function which is called from the core state machine process USBH HandleEnum function calls the following library routines implemented in file usbh stdreq c A user callback will be called at the end of enumeration phase in order to enable the user to process the descriptor information such as displaying descriptor data for example Control transfer state machine The control transfer state machine is entered from the core or class driver whenever a control transfer is required This state machine implements the standard stages for a control transfer i e the setup stage the optional data stage and the status stage The control transfer state machine is implemented in the USBH HandleControl function It is called from the core state machine process USB I O request module The USB I O request module is located in the low layer of the core It interfaces with the USB low level driver for issuing control bulk or interrupt USB transactions Host channel control module The host channel control module is located in the lower layer of the core It allows the configuration of a host channel for a particular operation control bulk or interrupt transfer type and it assigns a selected host channel to a device endpoint for creating a USB pipe USB host library configuration The US
22. a Doc ID 18153 Rev 3 UM1021 USB host library 4 uint8_t bLength uint8_t bDescriptorType uint16 t bcdUSB USB Specification Number which device complies too uint8_t bDeviceClass uint8_t bDeviceSubClass uint8_t bDeviceProtocol uint8_t bMaxPacketSize uint16 t idVendor Vendor ID Assigned by USB Org uint16 t idProduct Product ID Assigned by Manufacturer uint16 t bcdDevice Device Release Number uint8_t iManufacturer Index of Manufacturer String Descriptor uint8_t iProduct Index of Product String Descriptor uint8_t iSerialNumber Index of Serial Number String Descriptor uint8_t bNumConfigurations Number of Possible Configurations USBH_DevDesc_TypeDef Device configuration information config interface and endpoint descriptors are returned with pointers on structures USBH_CfgDesc_TypeDef USBH_InterfaceDesc_TypeDef and USBH_EpDesc_TypeDef defined as follows typedef struct 5 ConfigurationDescriptor uint8_t bLength uint8_t bDescriptorType uint16 t wTotalLength uint8 t bNumInterfaces uint8 t bConfigurationValue uint8 t iConfiguration uint8 t bmAttributes uint8 t bMaxPower USBH CfgDesc TypeDef typedef struct _InterfaceDescriptor uint8_t bLength uint8_t bDescriptorType uint8_t bInterfaceNumber uint8_t bAlternateSetting Value used to select alternative setting
23. bytes USB pendrives with Flash memories having higher page size are not supported 84 107 Doc ID 18153 Rev 3 a UM1021 USB host library FatFS application programming interface Table 38 FatFS API commands Function Description f mount Register Unregister a work area f open Open Create a file f close Close a file f read Read file f write Write file f_lseek Move read write pointer expand file size f truncate Truncate file size f sync Flush cached data f opendir Open a directory f readdir Read a directory item f getfree Get free clusters f stat Get file status f mkdir Create a directory f unlink Remove a file or directory f chmod Change attribute f utime Change timestamp f rename Rename Move a file or directory f mkfs Create a file system on the drive f forward Forward file data to the stream directly f chdir Change current directory f chdrive Change current drive f getcwd Retrieve the current directory f gets Read a string f putc Write a character f puts Write a string f printf Write a formatted string 7 6 2 HID class 4 The HID class implementation in v1 0 of the USB host library is used to support HID boot mouse and keyboard devices HID reports are received using the interrupt IN transfer The following modules located in the Libraries GSTM32_USB_HOST_Library Class HID folder are used to implement the
24. handlers e system sim32fxxx c system clock configuration file for STM32Fxxx devices e usb_bsp c contains the function implementation declared in the usb_bsp h in the USB OTG low level driver to initialize the GPIO for the core time delay methods and interrupts enabling disabling process usbd_usr contains the function implementation declared in the usbd_usr hin the USB library to handle the library events from user layer event messages e usbd_desc c This file is provided within USB Device examples and implements callback bodies This file offers a set of functions used to change the device and string descriptors at application runtime The includes directory contains the following files stm32fxxx_it h header file of the stm32fxxx_it c file e usb_confh configuration files for the USB OTG low level driver e usbd_conf h configuration files for the USB device library Doc ID 18153 Rev 3 ky UM1021 USB device library Note When using the USB OTG Full speed core the user should use the CN8 connector on the STM322xG EVAL and STM324xG EVAL or the CN2 connector when the STM3210C EVAL is used When using the USB OTG High speed core the user should use the CN9 connector on the STM322xG EVAL and STM324xG EVAL boards 6 9 Starting the USB device library Since the USB Library can handle multi core instances the user must first define the core device handles Figure 14 Example of the define for core device
25. message s aa 69 USB device firmware upgrade cable connected display message 69 USB virtual com port power on display message a 71 USB virtual com port cable connected display message 0 a 71 Configuration 1a Two different hosts for USB and USART a 72 Configuration 1b One single Host for USB and USART 0 000 cee eee 72 Configuration 2 Loopback mode for test purposes aaa 72 USB audio device power on display message eee eee 73 USB audio device cable connected display message 0 74 USB host library overview 0c 75 USB host library file tree structure cee 76 USB host library state machine 000 cee eee 77 Device enumeration steps ee teens 78 Block diagram organization of the MSC driver 0 00 eens 82 Folder organization 0 0 0 tetas 92 USB mass storage host display message c eee eee ee 95 USB mass storage explorer display message cece eee eee eee 96 USB mass storage explorer display message last screen 96 USB mass storage write file display message ce eee eee eee 97 USB mass storage slideshow example 0c cece eee eee eee eee 97 USB HID Host connected display message c eee 98 USB HID Host user key message 2 ee 98 USB HID Host text
26. process usbd msc mem h This file contains the function prototypes of the functions called from the SCSI layer to have access to the physical media sa Doc ID 18153 Rev 3 43 107 USB device library UM1021 44 107 Disk operation structure definition typedef struct _USBD_STORAGE f int8 t Init uint8 t lun int8 t 4 GetCapacity uint8 t lun tblock size int8 t IsReady uint8 t lun int8 t 4 IsWriteProtected int8 t 4 Read uint8 t lun blk len int8 t 4 Write uint8 t lun bik len int8 t 4 GetMaxLun void int8 t pInquiry USBD STORAGE cb TypeDef uint32 t block num uint16 t uint8 t lun uint8 t buf uint32 t blk addr uint16 t uint8 t buf uint32 t blk addr uint16 t In the media access file from user layer once the USBD STORAGE cb TypeDerf structure to the USBD STORAGE fops pointer is defined it should be assigned Example USBD STORAGE cb TypeDef USBD STORAG The standard inquiry data are given by the user inside the STORAG should be defined as const int8 t STORAGE Inquirydata LUN 0 0x00 0x80 0x02 0x02 USBD_STD_INQUIRY_LENGTH 0x00 0x00 0x00 Nae Ak AA O 5 1 tmi ULA NG E 1o KP LS D 1 ae LG al tS lc a 1 EO Wa Mi Vor PELI NG Disk operation functions Table15 Functions NS pi lt oO K n Tara 0 5 e 1
27. setup data status stages USBH BulkSendData Issues a bulk OUT transaction USBH BulkReceiveData Issues a bulk IN transaction USBH InterruptSendData Issues an interrupt OUT transaction USBH InterruptReceiveData Issues an interrupt IN transaction Table 31 8 Host channel control module Function USBH_Open_Channel Description Opens and configures a new host channel USBH_Modify_Channel Modifies an existing host channel USBH_Alloc_Channel Assigns a host channel to a device endpoint creation of a USB USBH_Free_Channel Frees a host channel USBH DeAllocate AllChannel Frees all host channels used during de initialization phase Table 32 Standard request module Function USBH_Get_CfgDesc USBH_Get_DevDesc Description Gets a configuration descriptor request Gets a device descriptor request a SBH_Get_StringDesc Gets a string descriptor request a SBH_GetDescriptor Generic get descriptor request USBH SetCfg1 Sets a configuration request USBH SetAddress2 Sets an address request USBH_ClrFeature Clears the feature request USBH SetCfg selects the default configuration configuration 0 USBH_SetAddress sets the device address to 0x1 Doc ID 18153 Rev 3 a UM1021 USB host library 7 5 USB host class interface
28. speed is detected see note 1 DeviceDescAvailable called when a device descriptor is available see note 2 DeviceAddressAssigned called when the device address is assigned ConfigurationDescAvailable called when configuration interface and endpoint descriptors are available see note 3 ManufacturingString called when manufacturing string is extracted ProductString called when product string is extractcted SerialNumString called when serial num string is extracted EnumerationDone called when enumeration is finished UserInput called after the end of the enumeration process for prompting the user for further action such as pressing a button to start a host class operation see note 4 SBH_USR_MSC_Application called to launch the class application process SBH_USR_DeviceNotSupported called when the detected device is not supported by the current class driver UnrecoveredError called when the core state machine is in HOST ERROR STATE state It allows the user to handle any error by displaying an error message on the LCD screen for example U U Device speed information is returned in the DeviceSpeed parameter Possible values are 0x1 for Full speed devices and 0x2 for Low speed devices Device descriptor information is returned in the pointer DeviceDesc which points to a structure of type USBH_DevDesc_TypeDef defined as follows typedef struct _DeviceDescriptor f
29. that the application wants to interpret as valid requests for example the library does not support the Halt feature on endpoint O but the user application wants so Invalid requests are the requests that are not standard requests and are not user interpreted requests Since pdev gt dev class_cb gt Setup pdev req is called after the SETUP stage and before the data stage user code is responsible in the pdev gt dev class_cb 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 dev class_cb gt Setup pdev req For a user interpreted request the user code then 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 dev class_cb gt Setup pdev req DATA stage The class layer uses the standard USBD_Ct1SendData and USBD_Ct1PrepareRx to send or receive data the data transfer flow is handled internally by the library and the user does not need to split and the data in ep_size packet Status stage The status stage is handled by the library after returning from the pdev gt dev class_cb gt Setup pdev req callback USB device library process Figure 9 shows the different layers interaction between the low level driver the usb device library and the application layer Doc I
30. 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 0 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 Doc ID 18153 Rev 3 57 107 USB device library UM1021 58 107 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 Communication device class CDC core files usbd_cdc_core 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 Table 25 usbd cdc core c h files Functions Description static uint8_t usbd_cdc_Init Initializes the CDC interface void pdev uint8_t cfgidx alizes the CDC interface static uint8 t usbd cdc Delnit void pdev AA fgidx De initializes the CDC interface static uint8_t usbd_cdc_Setup Handles the CD ntrol ri ts void pdev USB SETUP REQ req andies ihe GDO contol requeste static uint8_t usbd_cdc_EP0_RxReady void bd v Han
31. which are e Issuing GET MAX LUN class requests for detecting the number of device logical units present on the device Please note that only devices with one logical unit are supported Issuing BOT RESET class requests for resetting the device BOT state machine Issuing SCSI commands MODE SENSE for detecting if the device is write protected and READ CAPACITY for detecting the size of the Flash pendrive After the above device initializations the MSC core state machine calls the application user callback The user callback can perform any type of file access into the used file system This operation is translated into a logical page read or write operation The file system interface provides the connection between the used file system and the MSC driver At the SCSI level the logical page read or write operations are converted into SCSI commands READ 10 or WRITE 10 These commands are transferred to the Flash pendrive device using the Bulk Only Transport protocol 82 107 Doc ID 18153 Rev 3 ky UM1021 USB host library 4 The BOT layer state machine issues the required Bulk IN and Bulk OUT transactions using the core USB I O request module Each MSC module is described below MSC core module The MSC core module usb_msc_core c implements the MSC driver which is defined in the structure USBH MSC cb of type USBH Class cb TypeDef see Section 7 5 USBH Class cb TypeDef USBH MSC cb
32. 0V1 The user has to press the user key B4 to display the whole disk flash recursion level 2 Once the entire disk flash is shown Figure 40 USB mass storage explorer display message last screen USB OTG HS MSC Host USB Device Library vx x x MS20001V1 The user has to press the user key B4 to write a small file less to 1 KB on the disk a Doc ID 18153 Rev 3 UM1021 USB host library Figure 41 USB mass storage write file display message USB OTG HS MSC Host Directory3 Directory4 Directory5 File 5 Directory6 I Fileb gt Writing File to disk flash gt Host_Write_Demo TXT file created USB Device Library vx x x Ms20002V1 After writing the file to the disk the user can press the user key B4 and start the Image slide show BMP file located in the USB Disk root Figure 42 USB mass storage slideshow example USB OTG HS MSC Host USB Device Library vx x x MS20003V1 The image advancement is done automatically each one second Once all the images are displayed the application explores again the disk flash Figure 39 Note The application header title depends on the board in use once the full speed port is used the title is USB OTG FS MSC Host Only the BMP files with the following format are supported Width 320 Height 240 BPP 16 and Compression RGB bitmap with RGB masks ky Doc ID 18153
33. 0x04 dfUuDNLOAD IDLE 0x05 dfuMANIFEST SYNC 0x06 dfuMANIFEST 0x07 dfuMANIFEST WAIT RESE 0x08 dfuUPLOAD IDLE 0x09 dfuERROR Ox0A The allowed state transitions are described in the specification document Doc ID 18153 Rev 3 a UM1021 USB device library 4 Figure 12 DFU Interface state transitions diagram State 23 5 6 9 DFU_ABORT DFU_UPLOAD To protect the application from spurious access before initialization the initial state of the DFU core after startup is dfuERROR Then the host has to clear this state by sending a DFU_CLRSTATE request before generating any other request The DFU core manages all supported requests Doc ID 18153 Rev 3 47 107 USB device library UM1021 48 107 Table 17 Supported requests Request Code When bit 3 in bmAttributes bit WillDetach is set the DFU_DETACH 0x00 device generates a detach attach sequence on the bus when it receives this request Details 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 facilitate DFU_GETSTATUS 0x03 aba synchronization with the device DeU NG 0x04 Upon receipt of DFU CLRSTATUS the device sets a status E of OK
34. 16 Bytes tprp Te SKO Meth Ua VK GIG aM SE Sn 1 0 0 Version 4 Bytes LUN 0 0x00 0x80 0x02 0x02 USBD_STD_INQUIRY_LENGTH 5 0x00 0x00 0x00 ST NTG IM 9 Tye NO Tp WG NG MB T a Manufacturer 8 bytes EN Ag TA NANG T Ba BG Ac Ba WT Kk Product 16 Bytes Doc ID 18153 Rev 3 103 107 Frequently asked questions UM1021 104 107 ie cE al igi H 1 a 1 ko NG 1 7 O 0 Version 4 Bytes How can the DFU class driver support more than one memory interface To add an additional memory interface a Inthe usbd_conth file under ProjectlUSB Device ExamplesIDFUlinc change the following define define MAX USED MEDIA For example define MAX USED MEDIA 2 b Implement the APIs given by the following structure DFU MAI Prop TypeDef to implement the media I O requests Read Write Erase etc the prototype of each API is given in the usbd dfu mal h file c Add the interface string of the new medium to be added in the usbd_dfu_StringDesc table defined in the usbd_dfu_mal c file How can the keyboard layout be changed in the USBH HID class In the USB Host HID class two layouts are defined in the usbh_hid_keybd h file and can be used Azerty and Querty Uncomment the required keyboard layout define QWERTY_KEYBOARD define AZERTY KEYBOARD The User can eventually add his o
35. 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 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 e For STM32F105 7 devices the on board Speaker output quality with 25MHz external quartz may be not sufficient noise due to lack of accuracy on audio output frequency using this quartz 74 107 Doc ID 18153 Rev 3 UM1021 USB host library 7 7 1 USB host library The USB Host library Supports multi packet transfer features enabling the transmission of large amounts of data without having to split it into maximum packet size transfers Uses configuration files to change the core and the library configuration without changing the library code Read Only 32 bit aligned data structures to handle DMA based transfer in High speed modes Su
36. 28 Table 29 Table 30 Table 31 Table 32 Table 33 Table 34 Table 35 Table 36 Table 37 Table 38 Table 39 Table 40 Table 41 Table 42 Listol terms nad cde tgewe daa ved bond aga LENG aks hates e ae ade ede whe Rate 8 USB OTG low level file descriptions 0000 c eee 14 Core configurations 1 2 0 0 0 6 c cae 14 Standard requests c cette eae 26 USB device core files ssas smear ernaia pawia tees 32 usbd core c h files 2 0 2 eee 32 usbd ioreg Gh TICS inea Mena ee ee ede ee DOOR Pee Ste dew ees 33 usbd 7eq 0 AA 34 USB device class files 0 0 0 0 00 ccc ttt nee 38 usbd hid core c h files nnana anana ee eee eee ee eens 39 SCSI COMMANAS is a ea aoe dae Seed KGG de Mae tn ee ee eS 41 usbd msc core c h files 0 0 eee 42 usbd msc bot c h files cect 42 usbd msc scsi Ch eea seraa eee 43 FUNCHONS ceri BA GARA KG GALENG KUPAD DARA LNAG NP epee DFA hhaha NG vars 44 DEU Stal6S AA AA AA 46 Supported requests 0c ett ae 48 usbd dfu core c h files eee 48 usbd dfu mal c h files aaa 49 usbd flash if c h files tte 51 Audio control requests eee eee 53 usbd audio core c h files eee 54 usbd audio XXX if c h files eee 55 Audio player states eee 55 usbd cdc core c h files eee 58 Configurable CDC parameters 00 cee eta
37. 3 USB host library file tree structure STM32_USB_HOST_Library Class HID MSC Core 5 usbh_conf_template h usbh_core h usbh def h usbh hcsh usbh_ioreg h usbh stdreq h usbh core c usbh hcs c usbh_ioreg c usbh stdreq c Release Notes html OMT 8 MMMA The USB Host library is based on the generic USB OTG low level driver which supports Host device and OTG modes and works for High speed Full speed and Low speed for host mode The Core folder contains the USB Host library machines as defined by the Universal Serial Bus Specification revision 2 0 The Class folder contains all the files relative to the class implementation and meets with the specification of the protocol built in these classes Doc ID 18153 Rev 3 ky UM1021 USB host library 7 3 USB host library description 7 3 1 Host core state machine The following figure describes the library state machine Figure 34 USB host library state machine Device connection Event Host Initializations Device disconnection USB Reset Issued Event HOST_ISSUE_ iy CORE_RESET ib HOST IDLE jag Device connected amp USB Reset Issued HOST DEV ATTACHED USB Full Low speed device attached y _ _ HOST_ENUMERATION ys J i C Device enumerated y HOST ERROR STATE HOST CTRL XFER A HOST_USR_INPUT User selects to enter in class ope
38. 3 Rev 3 105 107 Revision history UM1021 10 Revision history Table 42 Document revision history Date Revision Changes 26 Nov 2010 1 Initial release Major document revision to include both the USB On The Go host 08 Aug 2011 2 and device libraries for STM32F105 7 and STM32F2xx devices Added STM32F4xx devices 08 Mar 2012 3 Removed Appendix A Changed format of the document for codes a 106 107 Doc ID 18153 Rev 3 UM1021 Please Read Carefully Information in this document is provided solely in connection with ST products STMicroelectronics NV and its subsidiaries ST reserve the right to make changes corrections modifications or improvements to this document and the products and services described herein at any time without notice All ST products are sold pursuant to ST s terms and conditions of sale Purchasers are solely responsible for the choice selection and use of the ST products and services described herein and ST assumes no liability whatsoever relating to the choice selection or use of the ST products and services described herein No license express or implied by estoppel or otherwise to any intellectual property rights is granted under this document If any part of this document refers to any third party products or services it shall not be deemed a license grant by ST for the use of such third party products or services or any intellectual property co
39. 5 USE host class interface 2s icchseey PRA cusassade pes beesebee AG 81 7 6 USB host classes AA AA 81 KYT Doc ID 18153 Rev 3 3 107 Contents UM1021 7 6 1 Mass storage class 1 2 eee 81 7 6 2 HID Class rera fos seep AA 85 7 7 USB host user interface rekon ea kek KAG bind phew teh ee wa ee 88 7 7 1 Library User API vac papagawa eee hed etd ee ANG ee ee ee 88 7 7 2 User callback functions 0 0 0 ee eee 88 7 7 3 Class callback functions 88 7 8 Application layer description eee 92 7 9 Starting the USB host library 2 4 3227080 a nika eee ee eee eee es 93 7 10 USB host examples sas KKA ee Seek ee hs KG ENGE DEAN KASAL 94 7 10 1 USB mass storage host example 00 cee e eee 95 7 10 2 USB HID Host example 0 0 0 c cee 98 7 10 3 USB dual core host example 0c eee eee ee 99 7 10 4 USB manual dual role device example 0 20000 100 8 Frequently asked questions 000 c cece eee 102 9 Troubleshooting aaa NA NA GG IS WADA 105 10 Revision history iene AA wae em a Nw es wl 106 4 107 Doc ID 18153 Rev 3 ky UM1021 List of tables 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
40. 5 5 4 2 Programming considerations when using internal DMA 15 5 4 3 Selecting USB physical interface 0 0 0000 e eee eee 17 5 4 4 Programming device drivers 0 00 eee eet ees 17 5 4 5 Programming host drivers 0 e eee eee 20 6 USB device library ois cae c inn dew een dawn sae ee Owe ws dare 23 6 1 USB device library overview 000 cece eee eee 23 6 2 USB device library files 0 0 0 c cece ee 24 6 3 USB device library description 0 0 0 c eee ee 24 6 3 1 USB device library flow 0 00 c eee 24 6 3 2 USB device library process 00 cece eee eee 27 6 3 3 USB device data flow 0 0000 cee ee 28 6 3 4 USB device library configuration 000 cee eee 29 6 3 5 USB data transfer handling 0c cece eee eee 29 6 3 6 Using the multi packet feature 1 0 0 ee ee 30 2 107 Doc ID 18153 Rev 3 1677 UM1021 Contents 6 3 7 USB control functions 0 00 ee 30 6 3 8 FIFO size customization 0 0 0 cee 30 6 4 USB device library functions 0 0 0 eee ee 32 6 5 USB device class interface 0 c eee eee 35 6 6 USB device user interface 0 000 36 6 7 USB device classes tees 38 6 7 1 FID ClaSS AA AA 39 6 7 2 Mass storage class eee 40 6 7 3 Device firmware upgrade DFU class 0 aa 45 6 7 4 Audio ClaSS 7x na tad NG NGALAN ELI seed oe bare
41. 59 usbd_cdc_xxx_if c h files eai areenaa tee 59 Variables used by usbd_cdc_xxx_if c h 0 teens 60 USB host core files srs ee ana tentados Ske ead wae bebe bowed eee oad aaa A 79 USB I O request module 1 2 20 0 ee 80 Host channel control module 0 00 tenes 80 Standard request module 0 0 eee 80 ile bA toh a bead Saeed ee Sa oo ae Ae eS 82 MSC core module description 00 0c cee eee 83 MSC BOT module description 0 00 tee 83 MSC SCSI commands 00 cee tenes 84 MSC file system interface functions 0 0000 cece eee 84 FatFS API commands 0 0 00 e cette ete 85 HID class modules 000 c ete ee 86 MSC core module functions 86 Mouse and keyboard initialization amp HID report decoding functions 87 Document revision history eet eee 106 Doc ID 18153 Rev 3 5 107 List of figures UM1021 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 Figure 22 Figure 23 Figure 24 Figure 25 Figure 26 Figure 27 Figure 28 Figure 29 Figure 30 Figure 31 Figure 32 Figure 33 Figure 34 Figure 35 Figure 36 Figure 37 Figure 38 Figure 39 Figure 40 Figure 41 Figure 42 Figure 43 Figure 44 Figure 45
42. 8 kHz Note that maximum allowed audio frequency is 96 kHz this limitation is due to the codec used on the Evaluation board The STM32 I2S cell enables reaching 192 kHz Communication device class CDC This 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 Doc ID 18153 Rev 3 ky UM1021 USB device library e Device descriptor management e Configuration descriptor management Enumeration as CDC device with 2 data endpoints IN and OUT and 1 command endpoint IN 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 dispatcher i e usbd_cdc_vcp c h which should manage each request and perform relative actions These aspects may 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 Any class specific aspect relative to communication c
43. ARM lt IAR Compiler pragma data_alignment 4 endif endif USB OTG HS INTERNAL DMA ENABLED ALIGN BEGIN USB OTG CORE HANDLE USB OTG dev _ ALIGN END _ ALIGN BEGIN and ALIGN END are compiler specific keywords defined in the usb_conf h file and are used to align variables on a 32 bit boundary Figure 6 C compiler dependant keywords defined in usb conf h file J9 Pe te he he e he ie e ie e e e e e e e Cc Compilers dependant keywords IE E V hahaha e S e V Y e e e e S e V Y e e e e e e e e e A In HS mode and when the DMA is used all variables and data structures dealing with the DMA during the transaction process should be 4 bytes aligned ifdef USB OTG HS INTERNAL DMA ENABLED if defined __ GNUC GNU Compiler define __ALIGN_END attribute aligned 4 define ALIGN BEGIN else define 58 ALIGN END if defined 8 CC ARM ARM Compiler define __ALIGN_ BEGIN __ align 4 elif defined ICCARM IAR Compiler define _ ALIGN BEGIN elif defined _ TASKING TASKING Compiler define ALIGN BEGIN __ align 4 endif _ CC ARM endif GNUC else define ALIGN BEGIN define 8 ALIGN END endif USB_OTG HS INTERNAL DMA ENABLED __ packed keyword used to decrease the data type alignment to i byte if defined CC ARM ARM Compiler define packed _ packed elif defined ICCARM IAR Compiler define _ packed _ packed elif defined _
44. B host library can be configured using the usbh cont h file a template configuration file is available in the LibrariesISTM32 USB Host LibrarylCore directory of the library define USBH MAX NUM ENDPOINTS 2 define USBH MAX NUM INTERFACES 1 define USBH MSC MPS SIZE 0x200 USB host library functions The Core layer contains the USB host library machines as defined by the revision 2 0 Universal Serial Bus Specification The following table presents the USB device core files Table 29 USB host core files Files Description This file contains the functions for handling all USB communication and usbh_core c h state machine usbh_stdreq c h This file includes the chapter 9 request implementation usbh_ioreg c h This file handles the generation of the USB transactions usbh hcs c h This file handles the host channel allocation and triggers processes This file contains the configuration of the device interface number usbh_conf h f configuration number and maximum packet size Doc ID 18153 Rev 3 79 107 USB host library UM1021 Note 80 107 Table 30 USB I O request module Function USBH_Ct1SendSetup Description Issues a setup transaction USBH_Ct1SendData Issues a control data OUT stage transaction USBH_CtlReceiveData Issues a control data IN stage transaction USBH CtlReq High level function for generating a control transfer
45. Continues receiving data on the control pipe pbuf uint16 t len Doc ID 18153 Rev 3 33 107 USB device library UM1021 Table 7 usbd ioreq c h files continued Functions Description USBD Status USBD_CtlSendStatus USB OTG CORF HANDLE pdev Sends a zero length packet on the control pipe USBD Status USBD_CtlReceiveStatus Receives a zero length packet on the USB OTG CORE HANDLE pdev control pipe Table 8 usbd req c h Functions Description void USBD GetString uint8 t desc uint8 t unicode uint16 t len Converts an ASCII string into Unicode one to format a string descriptor static uint8 t USBD GetLen uint8 t buf Returns the string length USB OTG COR USB SETUP RE USBD Status USBD_StdDevReq E HANDLE Q req pdev Handles standard USB device requests USB_SETUP_RE TI USBD Status USBD StdItfReq USB OTG COR FE HANDLE Q req pdev Handles standard USB interface requests USB_SETUP_RE USBD_Status USBD_StdEPReq USB OTG COR E HANDLE Q req pdev Handles standard USB endpoint requests USB_SETUP_RE static void USBD_GetDescriptor USB OTG COR E HANDLE Q req pdev Handles Get Descriptor requests static void USBD_SetAddress USB OTG COR USB SETUP REQ rea FE HANDLE pdev
46. D 18153 Rev 3 27 107 USB device library UM1021 6 3 3 28 107 Figure 9 USB device library process flowchart USBD_Init it USB device library Application USBD_USR_cb USBD Class cb USB device class USBD OTG ISR Handler USBD OTG EP1IN ISR Handler USBD OTG EP10UT ISR Handler Low level driver The Application layer has only to call to one function USBD Init to initialize the USB low level driver the USB device library the hardware on the used board BSP and to start the library The application has also to use the general USB ISR and the specific EP1 subroutines when the USB OTG HS DEDICATED EP1 ENABLED define is uncommented in the usb cont h file USBD DCD INT cb MS20016V1 The usBD Init function needs however the user callback structure to inform the user layer of the different library states and messages and the class callback structure to start the class interface The USB Low level driver can be linked to the USB device library through the USBD DCD INT cb structure This structure ensures a total independence between the USB device library and the low level driver enabling the low level driver to be used by any other device library USB device data flow The USB Library USB core and USB class layer handles the data processing on Endpoint 0 EPO through the IO request layer when a wrapping is needed to ma
47. Figure 46 Figure 47 Figure 48 6 107 USB host and device library organization overview 0 00 ccc ees 9 Folder structure 0000 ce nee eee 10 Driver architecture overview 0c eee 13 Driver files rero naieepa delat pain e ae E ar ea aid Race Wa lace de De aE o Weare Ca 13 USB core structure accede dd aed Dk ead ode ear a eed ae dee tas 16 C compiler dependant keywords defined in usb conf h file 16 USB device library architecture etna 23 USB device library file structure tenes 24 USB device library process flowchart 0 0 c cece eens 28 USB device data flow eee 29 BOT Protocol architecture cette eee 40 DFU Interface state transitions diagram 1 6 00 ce eee 47 Folder organization 00 ener ee aa eee ee 62 Example of the define for core device handles 020 cece eee ee eee 63 USBD Init function example 0c eae 63 Power on display message e eee eee eee 65 Cable connected display message een eee eens 65 USB HID power on display message cece tees 66 USB HID cable connected display message 2 66 Dual core USB device example 000 tees 67 USB dual device power on display message eee eee ee 68 USB dual device cable connected display message 0a 68 USB device firmware upgrade power on display
48. HID keyboard mouse HID USB device Mass storage mass storage Host MSC Device MSC FAT FS file system CDC virtual COM Dual core MSC HID Stacks and libraries USB device library USB host library L l i STM32F 105 107xx STM32F2xx l and STM32F4xx standard peripheral libraries i L MS19706V2 The USB host and device libraries are built around the common STM32 USB OTG low level driver and the USB device and host libraries Main features The USB host and device library is Compatible with the STM32F105x STM32F107x STM32F2xx and STM32F4xx devices in HS and FS USB modes Fully compliant with the Universal Serial Bus Revision 2 0 Specification Optimized to work with the USB OTG peripherals high speed and full speed and can use all their features Built with a reduced footprint high transfer performance robustness and a high quality code and documentation package Easily extended to support USB OTG features Built following a generic and easy to use architecture able to add further specific vendor classes supports multi interface applications composite devices Able to support multiple USB OTG cores allowing the use of several cores with the same library Doc ID 18153 Rev 3 9 107 USB host and device library folder structure UM1021 3 10 107 USB host and device library folder str
49. Init nyah CRANE vo Initializes the BOT process and physical media USB OTG CORE HANDLE pdev void MSC BOT Reset USB_OTG_CORE HANDLE pdev Resets the BOT Machine void MSC BOT Delnit ere USB_OTG_CORE HANDLE pdev De Initializes the BOT process void MSC_BOT_DataiIn USB_OTG_CORE_HANDLE pdev uint8 t Handles the BOT data IN Stage Handles the BOT data OUT Stage static void MSC BOT CBW Decode USB OTG CORE HANDLE pdev Decodes the CBW command and sets the BOT state machine accordingly static void MSC_BOT_SendData USB_OTG_CORE_HANDLE pdev uint8_t buf uint16 t len Sends the requested data void MSC BOT SendCsw USB OTG CORE HANDLE CSW Status pdev uint8 t Sends the Command Status Wrapper static void MSC BOT Abort USB OTG CORE HANDLE pdev Aborts the current transfer void MSC BOT Cp1CIrFeature USB OTG CORE HANDLE pdev uint8 t epnum Completes the Clear Feature request Doc ID 18153 Rev 3 a UM1021 USB device library Table 14 usbd msc scsi c h Functions int8 t SCSI ProcessCmd USB OTG CORE HANDLE pdev uint8 t LUN uint8 t params Description Processes the SCSI commands static int8 t SCSI TestUnitReady uint8 t lun uint8 t params Processes the SCSI Test Unit Ready command static int8 t SCSI Inquiry uint8 t lun uint8 t para
50. M322xG EVAL and STM324xG EVAL boards Figure 20 Dual core USB device example 81 82 USB_OTG CORE HANDLE USB OTG FS dev 83 USB OTG CORE HANDLE USB OTG HS dev 84 85 86 brief Program entry point 87 param None 88 retval None 89 YU int ma n void 91 92 uint32_t i 0 93 94 USBD Init sUSB OTG FS dev 95 USB OTG FS CORE ID 96 sUSR HID desc 97 USBD HID cb 98 USR FS cb 99 100 USBD Init sUSB OTG HS dev 101 USB OTG HS CORE ID 102 amp USR_MSC desc 103 USBD MSC cb 104 USR HS cb 105 106 while 1 107 108 if i Ox100000 109 f 110 STM EVAL LEDToggle LED1 111 STM EVAL LEDToggle LED2 112 STM EVAL LEDToggle LED3 11 3 STM EVAL LEDToggle LED4 114 i 0 115 116 117 4 Doc ID 18153 Rev 3 67 107 USB device library UM1021 6 10 4 68 107 For this project two USB device instances are declared and the USBD Init function is called twice to initialize each USB OTG core and to load the class callbacks for each instance At power on the LCD displays the following messages Figure 21 USB dual device power on display message USB Dual Devices gt USB device Library started gt HID Device in suspend mode gt MSC Device in suspend mode USB Device Library vx x x MS18191V1 When the USB cable is plugged in the LCD shows the following messages Figure 22 USB dual devic
51. NDLE pdev uint8 t epnum The DCD layer of the USB OTG Low Level Driver has one function that must be called by the USB interrupt high speed or full speed uint32_t DCD_Handle_ISR USB_OTG_CORE_HANDLE pdev The dcd_int h file contains the function prototypes of the functions called from the library core layer to handle the USB events USB driver structure definition typedef struct _USBD_DCD_INT uint8_t DataOutStage USB_OTG_CORE_HANDLE pdev uint8_t epnum uint8_t DataInStage USB_OTG_CORE_HANDLE pdev uint8_t epnum uint8_t SetupStage USB_OTG_CORE_HANDLE pdev uint8_t SOF USB_OTG_CORE_HANDLE pdev uint8_t Reset USB_OTG_CORE_HANDLE pdev uint8_t Suspend USB_OTG_CORE_HANDLE pdev uint8_t Resume USB_OTG_CORE_HANDLE pdev uint8_t IsoINIncomplete USB_OTG_CORE_HANDLE pdev uint8_t IsoOUTIncomplete USB_OTG_CORE_HANDLE pdev uint8_t DevConnected USB_OTG_CORE_HANDLE pdev uint8_t DevDisconnected USB_OTG_CORE_HANDLE pdev USBD DCD INT cb TypeDef In the library layer once the USBD DCD INT cb TypeDef structure is defined it should be assigned to the USBD DCD INT fops pointer Example USBD DCD INT cb TypeDef USBD DCD INT fops amp USBD_DCD_INT_cb Doc ID 18153 Rev 3 19 107 USB OTG l
52. OTG driver programming manual 5 4 1 Low level driver structures The low level driver does not have any exportable variables A global structure USB OTG CORE HANDLE which keeps all the variables state and buffers used by the core to handle its internal state and transfer flow should be used to allocate in the application layer the handle instance for the core to be used This method allows the application to use the same low level driver for both high and Full Speed cores in the same project The global USB core structure is defined as follows typedef struct USB OTG handle USB OTG CORE CFGS cfg USB_OTG_CORE_REGS regs ifdef USE_DEVICE_MODE DCD_DEV dev endif ifdef USE_HOST_MODE HCD_DEV host endif ifdef USE_OTG_MODE OTG_DEV otg endif USB OTG CORE HANDLE PUSB_OTG_CORE_HANDLE 5 4 2 Programming considerations when using internal DMA sa When using the internal DMA with the USB OTG High Speed core all structures dealing with the DMA data buffer during the transaction process should be 32 bit aligned Doc ID 18153 Rev 3 15 107 USB OTG low level driver UM1021 Note 16 107 Consequently the USB_OTG_hand_1e structure is defined to keep all the internal buffers and variables used to hold the data to be transferred 32 bit aligned When the internal DMA is used the global USB Core structure should be declared as follows Figure 5 USB core structure ifdef USB_OTG HS INTERNAL DMA ENABLED if defined IICC
53. R_PROP void Init void void DeviceAttached void void ResetDevice void void DeviceDisconnected void void OverCurrentDetected void void DeviceSpeedDetected uint8_t DeviceSpeed void DeviceDescAvailable void void DeviceAddressAssigned void Doc ID 18153 Rev 3 89 107 USB host library UM1021 Note 90 107 void ConfigurationDescAvailable USBH_CfgDesc_TypeDef USBH_InterfaceDesc_TypeDef USBH_EpDesc_TypeDef void ManufacturerString void void ProductString void void SerialNumString void void EnumerationDone void USBH int USR Status UserInput void USBH USR MSC Application void void USBH USR DeviceNotSupported void void UnrecoveredError void USBH_Usr_cb_TypeDe The above callback functions are described below Init called during initialization by USBH_Init core function In this function the user can implement any specific intialization related to his application DeviceAttached called when a USB device is attached It can be useful to inform the user of any device attachment using a display screen DeviceReset called after a USB reset is generated from the host DeviceDisconnect called when a device is disconnected OverCurrentDetected called when an overcurrent is detected on USB VBUS DeviceSpeedDetected called when the device
54. SETUP REQ req Handles the SET CUR Audio control request The low layer hardware interfaces are managed through their respective driver structure typedef struct Audio Fops f uint8 t Init uint32 t AudioFreq uint8 t DeInit uint32 t options uint8 t AudioCmd uint8_t pbuf uint8_t VolumeCtl uint8 t vol uint8_t MuteCtl uint8 t cmd uint8_t PeriodicTC uint8_t cmd uint8_t GetState void JAUDIO FOPS TypeDef uint32 t Volume uint32 t options uint32 t size uint8 t cmd Each audio hardware interface driver should provide a structure pointer of type AUDIO FOPS TypeDef 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 Doc ID 18153 Rev 3 a UM1021 USB device library sa usbd audio xxx if c h i e usbd audio out if c h This driver manages the low layer audio hardware usbd audio out if c h driver manages the Audio Out interface from USB to audio speaker headphone It calls lower layer codec driver i e stm322xg usb audio codec c h for basic audio operations play pause volume control This driver provides the structure pointer extern AUDIO FOPS TypeDef AUDIO OUT fops Table 23 usbd audio xxx if c h files Functions Description static uint8 t Init uint32 t AudioFreq
55. SIZE The device string descriptors 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 interface i e usbd cdc vcp if c and can be modified by user depending on the application needs CDC IN and OUT data transfers are managed by two functions APP DataTx i e VCP_dataTx should be called by user application each time a data or a certain number of data is available to be sent to the USB Host from the hardware terminal APP DataRx i e VCP dataRx 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 e CDC control requests should be handled by the function APP Ctr1 i e VCP Ctrl 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 e To close the communication call the function usbd cdc Delnit This closes the used endpoints and calls lower layer de initialization funct
56. Transmit FIFO size for a device endpoint Full speed where n is Xn_FIFO_FS_SIZE the Index of the endpoint to be used Sets the Transmit FIFO size for a device endpoint High Speed core TXn_FIFO_HS_SIZE where nis the Index of the endpoint to be used TXH NP FS FIFOSIZ Sets the non periodic Transmit FIFO size for Host mode Full Speed 14 107 Doc ID 18153 Rev 3 ky UM1021 USB OTG low level driver Table 3 Core configurations continued Define Description Sets the non periodic Transmit FIFO size for Host mode High Speed TXH_NP_HS_FIFOSIZ core TXH P FS FIFOSIZ Sets the Periodic Transmit FIFO size for Host mode Full Speed TXH P HS FIFOSIZ Sets the Periodic Transmit FIFO size for Host mode High Speed core USB_OTG_ULPT_PHY_ Enables the ULPI PHY for High Speed core ENABLED Yee OTe ae PDED_ Enables the embedded FS PHY for High Speed core PHY_ENABLED USB OTG HS LOW PW Enables low power management for High Speed core USB Core clock R_MGMT_SUPPORT gating etc USB OTG FS LOW PW Enables low power management for Full Speed core USB Core clock R MGMT SUPPORT gating etc ka ecclesia Enables the internal DMA feature for High Speed core AL DMA ENABLED USB OTG HS DEDICA Enables the dedicated Endpoint 1 feature for Device mode in High Speed TED EP1 ENABLED core 5 4 USB
57. _GNUC_ GNU Compiler define _ packed attribute packed elif defined _ TASKING TASKING Compiler define _ packed _ unaligned endif _ CC ARM Doc ID 18153 Rev 3 a UM1021 USB OTG low level driver 5 4 3 Note 5 4 4 Selecting USB physical interface As described in the USB OTG Low Level Driver configuration the user can select the USB Physical interface PHY to be used e For the USB OTG Full Speed Core the embedded Full Speed PHY is used When using the USB OTG High Speed core the user can select one of the two PHY interfaces AULPI interface for the external High Speed PHY the USB HS Core will operate in High speed mode An on chip Full Speed PHY the USB HS Core will operate in Full speed mode The library provides the capability of selecting the PHY to be used using one of these two defines in usb_conf h file as described in Section 5 3 USB OTG low level driver configuration on page 14 e USE ULPI PHY if the USB OTG HS Core is to be used in High speed mode e USE_EMBEDDED_PHY if the USB OTG HS Core is to be used in Full speed mode With the ULPI interface the user can force the core to work in Full Speed mode by modifying the usb_core c file through the ULPIFSLS bit in the OTG_HS_GUSBCFG register In Host mode the core speed can be modified when a device with a lower speed is connected Programming device drivers Device initialization The d
58. a IN stage pdev static uint8 t EPO_RxReady void Handles the DFU control endpoint data OUT pdev stage Doc ID 18153 Rev 3 ky UM1021 USB device library Table 18 usbd dfu core c h files continued void pdev Functions uint8_t idx static uint8_t Get_USRStringDesc Description Manages the transfer of memory interfaces string descriptors pdev USB SETUP REQ req static void DFU_Req DETACH void Handles the DFU DETACH request tpdev USB SETUP REQ req static void DFU_Req_DNLOAD void Handles the DFU DNLOAD request pdev USB_SETUP_REQ req static void DFU_Req_UPLOAD void Handles the DFU UPLOAD request static void pdev DFU_Req_GETSTATUS void Handles the DFU GETSTATUS request static void DFU_Req_CLRSTATUS void Handles the DFU CLRSTATUS request pdev pdev nae void DFU_Req_GETSTATE void Uandles the DFU GETSTATE request Statie vale DFU CREG ABORT v id Handles the DFU ABORT request pdev Handles the sub protocol DFU leave DFU mode static void DFU_LeaveDFUMode void request leaves DFU mode and resets device to jump to user loaded code usbd dfu mal c h This driver is the entry point for the memory low layer access It allows the parsing of the memory control access requests through the available memories that is internal Flash OTP etc Depending on the add
59. acteristics 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 device request the host sends a device request on the default pipe of bmRequestType Class Interface device to host bRequest field set to 254 FEh wValue field set to 0 wIndex field set to the interface number wLength field set to 1 ky Doc ID 18153 Rev 3 41 107 USB device library UM1021 42 107 MSC Core files Table 12 usbd msc core c h files Functions static uint8 t USBD MSC Init void pdev uint8 t cfgidx Description Initializes the MSC interface and opens the used endpoints static uint8 t USBD MSC Delnit void pdev uint8 t cfgidx De initializes the MSC layer and close the used endpoints static uint8 t USBD MSC Setup void tpdev USB SETUP REQ req Handles the MSC specific requests uint8 t USBD_MSC_DataIn void pdev uint8 t epnum Handles the MSC Data In stage uint8 t USBD MSC DataQut void pdev uint8 t epnum Handles the MSC Data Out stage epnum void MSC_BOT_DataOut USB_OTG_CORE_HANDLE epnum pdev uint8_t Table 13 usbd_msc_bot c h files Functions Description void MSC_BOT_
60. and transitions to the dfu IDLE state DFU GETSTAT EH 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 can be considered into 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 1 DFU_CLRSTATUS DFU_ABORT and DFU_DETACH Device firmware upgrade DFU core files usbd_dfu_core c h This driver is the main DFU core It allows the management of all DFU requests and state machine It does not directly deal with memory media managed by lower layer drivers Table 18 usbd dfu core c h files Functions Description lene Cee usbd_dfu_Init void Initializes the DFU interface tpdev uint8 t cfgidx static uint8 t usbd dfu Delnit poeta De initializes the DFU layer void pdev uint8_t cfgidx e a SSE U laye static uint8_t usbd_dfu_Setup void E T Handles the DFU r t parsing pdev USB SETUP REQ req andles the U request parsing Skak ere Epo Tesei ene Handles the DFU control endpoint dat
61. ard working with USB OTG FS core and the embedded FS PHY 3 STM324xG EVAL USBD HS High speed example on the STM324xG EVAL board working with USB OTG HS core and the ULPI PHY 4 STM324xG EVAL USBD FS Full speed example on the STM324xG EVAL board working with USB OTG FS core and the embedded FS PHY 5 STM3210C EVAL USBD FS Full speed example on the STM3210C EVAL board working with USB OTG FS core and the embedded FS PHY For the High speed examples the following features are selected in the usb config h file USB OTG HS ULPI PHY ENABLED ULPI Phy is used USB OTG HS INTERNAL DMA ENABLED internal DMA is used USB OTG HS DEDICATED EP1 ENABLED endpoint interrupts relative to the class are independent from the global USB OTG interrupt For the HID example the Low power mode is enabled allowing entering the core into Low power mode by the USB Suspend event the core wakes up when the USB wakeup event is received on the USB The HID example supports also the remote wakeup feature allowing the device to wake up the host by pressing the Key button on the evaluation board The USB device examples are using the Icd_log c module to redirect the Library and User messages on the screen Depending on the LCD cache depth used to scroll forward and backward within the messages the application footprints are impacted With bigger LCD cache depth the RAM footprint is consequently increased
62. b_bsp_template c This file contains the host interface layer used by the library usb_hcd c h to access the core Host f usb_hcd_int c h This file contains the interrupt subroutines for the Host mode usb_dcd c h This file contains the device interface layer used by the library to access the core Device This file contains the interrupt subroutines for the Device usb_dcd_int c h mode This file contains the implementation of the SRP and HNP Org usb_otg c h protocols and the interrupts relative to the OTG mode 5 3 USB OTG low level driver configuration The configuration of the USB OTG cores high and full speed core is defined in the common configuration file usb_conf h The user can enable or disable certain core features define the Tx and Rx FIFO for the device the periodic and the non periodic transmit FIFO and the Rx FIFO for the host This file is also used to select Host Device or OTG modes or selecting both Device and Host modes for manual dual role device applications The table below gives details of the core configurations defined in the usb_conf h file Table 3 Core configurations Define Description USB_OTG_FS_CORE Enables the use of the full speed core USB_OTG_HS_CORE Enables the use of the high speed core RX_FIFO_FS_SIZE Sets the Receive FIFO size for the full speed core RX_FIFO_HS_SIZE Sets the Receive FIFO size for the high speed core Sets the
63. brary and User messages on other terminal HyperTerminal or LCD using the native display functions Library and User messages are located in the user callbacks in the application layer They are not mandatory and they are used for information and debug purpose only They can be modified or even removed USB mass storage host example When attaching a mass storage device to the STM322xG EVAL STM324xG EVAL or STM3210C EVAL board the LCD displays the following text for example when plugging in the Kingston Data Traveler G2 USB Flash drive Figure 38 USB mass storage host display message USB OTG HS MSC Host gt USB host Library started gt Device attached gt High speed detected VID 0483h PID 3251h High speed device gt Mass storage device connected has been detected gt Manufacturer STMicroelectronics and correctly enumerated gt Product USB HS disk flash gt Serial number 000056789E gt Enumeration completed USB Device Library vx x x MS18199V1 When the user press the user key B4 the application explore the USB flash disk content and the LCD displays the following messages Doc ID 18153 Rev 3 95 107 USB host library UM1021 96 107 Figure 39 USB mass storage explorer display message USB OTG HS MSC Host gt File System initilized gt Disk capacity 1001945220 Bytes gt Exploring disk flash kad e 1 USB Device Library vx x x MS2000
64. ce has detected a reset event from the host DeviceConfigured this callback is called when the device receives the set configuration request DeviceSuspended This callback is called when the device has detected a suspend event from the host DeviceResumed This callback is called when the device has detected a resume event from the host DeviceConnected This callback is called when the device is connected to the host DeviceDisconnected This callback is called when the device is disconnected from the host Doc ID 18153 Rev 3 ky UM1021 USB device library The Library provides descriptor callback structures to allow user to manage the device and string descriptors at application run time This descriptors structure is defined as follows typedef struct _Device_TypeDef uint8 t GetDeviceDescriptor uint8_t speed uint16 t length uint8 t GetLangIDStrDescriptor uint8 t speed uint16 t length uint8 t GetManufacturerStrDescriptor uint8_t speed uint16 t length uint8_t GetProductStrDescriptor uint8 t speed uint16 t length uint8 t GetSerialStrDescriptor uint8 t speed uint16 t length uint8 t GetConfigurationStrDescriptor uint8_t speed uint16 t length uint8 t GetInterfaceStrDescriptor uint8 t speed uint16 t length ifdef USB_SUPPORT_USER_STRING_DESC uint8 ty Get USRStringDesc uint8_t speed ui
65. ch supports Host Device and OTG modes and works for High speed Full speed and Low speed for host mode The Core folder contains the USB device library machines as defined by the revision 2 0 Universal Serial Bus Specification The Class folder contains all the files relative to the class implementation It is compliant with the specification of the protocol built in these classes USB device library description USB device library flow Handling control endpoint 0 The USB specification defines four transfer types control interrupt bulk and isochronous transfers 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 standard requests on the control endpoint 0 The library answers requests without the intervention of the user application if the library has enough information about these requests Otherwise the library calls user application defined callback functions to accomplish the requests when some application actions or Doc ID 18153 Rev 3 ky UM1021 USB device library application information are needed The format and the meaning of the class specific requests and the vendor specific req
66. d MEM START ADDin file usbd mem if template h e Update the number of memory interfaces in usbd cont h file define MAX USED MEDIA e Update the file usbd dfu mal c by Including the new memory header file Adding the new memory callback structure in tMALTab table Adding the pointer to the new memory string descriptor in usbd dfu StringDesc table It is advised to modify the names of defines variable files structures in usbd_mem_if_template c h files for each new memory interface In High speed mode it is not possible to use DMA for writing reading to from Flash OTP memories In this case an intermediate buffer is used to interface between memory and DMA controller This may result in performance degradation for transfers relative to these memories in High speed mode It is advised to disable DMA mode in this case comment USB_OTG_HS_INTERNAL_DMA_ENABLED define in file usb_conf h Audio class This driver manages the Audio Class 1 0 following the USB Device Class Definition for Audio Devices V1 0 Mar 18 98 This driver implements the following aspects of the specification Device descriptor management Configuration descriptor management Standard AC Interface Descriptor management 1 Audio Streaming Interface with single channel PCM Stereo mode 1 Audio Streaming Endpoint 1 Audio Terminal Input 1 channel Audio Class Specific AC Interfaces Audio Cla
67. d eS BRA ged 52 6 7 5 Communication device class CDC aa 56 6 7 6 Adding a custom class e cette 61 6 8 Application layer description 0c eee ee 62 6 9 BS Starting the USB device library cee eee 63 6 10 USB device examples 00 e ee ees 64 6 10 1 USB mass storage device example an 64 6 10 2 USB human interface device example 0a 65 6 10 3 Dual core USB device example 0 67 6 10 4 USB device firmware upgrade example a 68 6 10 5 USB virtual com port VCP device example 70 6 10 6 USB audio device example 00 ccc eee 73 6 10 7 Known limitations e eee 74 7 USB host library a eile incerta ng ee Gh so ean ol haw a Ser ee a aA mr 75 7 1 OVENIEW 2c BEKERE REAR RAR eee hie PANEER Sento NETDEN ee be 75 7 2 USB host library files 2 s cciavaeeivveeleeeedareeedenneues eae dd 76 7 3 USB host library description 22 22 c000050 80ense te dee ae eeane 77 7 3 1 Host core state machine 0 ee eee 77 7 3 2 Device enumeration 0 0 ccc eee 78 7 3 3 Control transfer state machine 0c e eee ee 79 7 3 4 USB I O request module 0 0 0 0 cece eens 79 7 3 5 Host channel control module 0 00 c eee es 79 7 3 6 USB host library configuration 0000 e eee eee 79 7 4 USB host library TUNGONG aaa ga ha KAB GWA besetaciies MAA WAG 79 7
68. d through their respective driver structure typedef struct DFU MAL PROP const uint8_t pStrDesc uint16 t pMAL Init void uint16 t pMAI Delnit void uint16 t pMAL Erase uint32 t Add uint16 t pMAL Write uint32 t Add uint32 t Len uint8 t pMAL Read uint32 t Add uint32 t Len uint16 t pMAL CheckAda uint32 t Add const uint32 t EraseTiming const uint32 t WriteTiming DFU MAL Prop TypeDef Each memory interface driver should provide a structure pointer of type DFU MAL Prop TypeDef 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 xxxx if c h i e usbd flash if c h This is the low layer driver managing the memory interface Each memory interface should be managed by a separate low level driver that is usbd flash if c h usbd otp if c h The library provides two default memory drivers for internal Flash memory usbd flash if c h and for OTP memory usbd otp if c h But you can add other memories using the provided template file usbd template if c h This driver provides the structure pointer extern DFU MAL Prop TypeDef DFU Flash cb extern DFU MAL Prop TypeDef DFU OTP cb a 50 107 Doc ID 18153 Rev 3
69. define APP_DEFAULT_ADD Call usbd_dfu_Init function to initialize all memory interfaces and DFU state machine e All control request operations are performed through control endpoint O through the functions usbd_dfu_Setup and EPO_TxSent 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 To close the communication call the usbd_dfu_DeInit function Note When the DFU application starts the default DFU state is DFU_ERROR This state is set to protect the application from spurious operations before having a correct configuration How to add a new memory interface e Use the file usbd_mem_if_template c as reference modify file name fill functions allowing to read write erase get status and the mean timings for write and erase operations in DFU_Mem_cb structure If a functionality is not supported i e Erase fill the relative field in the 1 4 DFU MAL Prop TypeDef structure Doc ID 18153 Rev 3 51 107 USB device library UM1021 Note 6 7 4 Note 52 107 Configure the new memory string descriptor allowing to determine the memory size number of sectors and possibilities of read write erase operations on each group of sectors MEM_IF_STRING in usbd_mem_if_template h e Configure the start and end addresses of the memory using define MEM START ADD an
70. dles CDC control request data static uint8 t usbd_cdc_DataIn void Moder aides ema Handles the CDC IN data stage static uint8 t usbd_cdc_DataOut void oder uint8 t ebrium Handles the CDC Out data stage static uint8_t usbd_cdc_SOF Handles the SOF event data buffer update and void pdev synchronization static void Handle_USBAsynchXfer void pd v Handles the IN data buffer packaging The low layer hardware interfaces are managed through their respective driver structure typedef struct _CDC_IF_PROP uint16 t pIf_Init void uint16 t pIf Delnit void uint16 t pIf Ctrl uint32 t Cmd uint8 t4 Buf uint32 t Len uint16 t pIf DataTx uint8 t4 Buf uint32 t Len uint16 t pIf DataRx CDC_IF_Prop_TypeDef uint8_t Buf uint32_t Len Each hardware interface driver should provide a structure pointer of type CDC_IF_Prop_TypeDef The functions 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 a Doc ID 18153 Rev 3 UM1021 USB device library Note 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_conf h file Table 26 Configurable CDC parameters Typical
71. e N is the valid configuration GET_DESCRIPTOR index Gets the string descriptor where N is Non the valid string index This request is Al A0 28 LangID 0 valid only when the string descriptor is supported GET_CONFIGURATION A C 80 00 00 00 00 1 Gets the device configuration SET CONFIGURATION A C 80 N oo oo oo og poet ne device configuration where N is the valid configuration number Gets the alternate setting of the GET_INTERFACE C 81 00 00 N 00 1 interface N where N is the valid interface number Sets alternate setting M of the interface N where N is the valid SE S Ba LB 0 AN nG 90 interface number and M is the valid alternate setting of the interface N ky UM1021 USB device library Note 6 3 2 In column State D Default state A Address state C Configured state All All states EP DO D3 endpoint address D4 D6 Reserved as zero D7 0 OUT endpoint 1 IN endpoint 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 dev class_cb 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 vendor specific requests or the requests that the library considers as invalid requests
72. e Transmit FIFO indexes Txnshould be configured with the minimum space of 16 words The FIFO is used optimally when used TxFIFOs are allocated in the top of the FIFO For example use EP1 and EP2 as IN instead of EP1 and EP53 as the IN ones The total FIFO size for the used USB OTG core for the USB OTG FS core the total FIFO size is 320 32 bits while for the USB OTG HS core the total FIFO size is 1024 32 bits Example If the application uses 1 IN endpoint for control with MPS 64 Bytes 1 OUT Endpoint for Control with MPS 64 Bytes and 1 IN Bulk endpoint for the class with MPS 512 Bytes Doc ID 18153 Rev 3 31 107 USB device library UM1021 The EPO IN and OUT are configured by the USB Device library However the user should open the IN endpoint 1 in the class layer as shown below DCD_EP_Open pdev 0x81 512 USB_OTG_EP_BULK and configure the TX1_F RM0033 RM0090 and RM0008 6 4 USB device library functions FO_FS_SIZE using the formula described in reference manuals The Core layer contains the USB device library machines as defined by the revision 2 0 Universal Serial Bus Specification The following table presents the USB device core files Table 5 USB device core files Files usbd core c h This file contains the functions for handling all USB communication and state machine Description usbd req c h This file include
73. e cable connected display message USB Dual Devices gt USB device Library started gt HID Device in suspend mode gt MSC Device in suspend mode gt HID Interface started gt MSC interface started USB Device Library vx x x MS18192V1 USB device firmware upgrade example The DFU example allows a device firmware upgrade using the DFU drivers provided by ST ST DFUse and ST DFU Tester available for download from www st com The supported memories for this example are e Internal Flash memory for STM32F105 7 STM32F2xx and STM32F4xx devices OTP memory for STM32F2xx and STM32F4xx devices The DFU example works in High and Full speed modes and has the following USB device information define USBD_VID 0x0483 define USBD PID OxDF11 define USBD LANGID STRING 0x409 define USBD_MANUFACTURER_STRING STMicroelectronics define USBD PRODUCT HS STRING DFU in HS mode Doc ID 18153 Rev 3 ky UM1021 USB device library 4 define USBD_SERIALNUMBER_HS_STRING 00000000010B define USBD_PRODUCT_FS_STRING DFU in FS Mode define USBD_SERIALNUMBER_FS_STRING 00000000010C define USBD_CONFIGURATION_HS_STRING define USBD INTERFACE HS STRING DFU Config DFU Interface define USBD CONFIGURATION FS STRING DFU Config define USBD INTERFACE FS STRING DFU Interface At power on the LCD displays the following messages
74. ects a resume signal on the USB the library restores the USB core clock and puts the system to idle state if low power mode is enabled by in the usb conf h file FIFO size customization In order to use a new endpoint or change the endpoint already used in the application the user has to take care of two things 1 Endpoint initialization this phase is done generally in the usbd class core layer through the following function uint32 t DCD EP Open USB OTG CORE HANDLE pdev uint8 t ep addr uint16 t ep mps uint8 t ep type The ep addr should hold the endpoint address note the endpoint direction is identified by the MSB bit ie Ox801 ep index for ep IN endpoint and the ep mps holds the max packet size of the endpoints 2 The FIFO configuration done in the usb core c file in the usb low level driver the FIFO configuration could be modified by the user through the usb conf h file ifdef USB OTG FS CORE define RX FIFO FS SIZE128 define TXO FIFO FS SIZE64 define TX1 FIFO FS SIZE128 define TX2 FIFO FS SIZEO Doc ID 18153 Rev 3 ky UM1021 USB device library Note define TX3_FIFO_FS_SIZE endif ifdef USB OTG HS CORE define RX FIFO HS SIZ define define define define define define r n m i m XO FIFO X1_FIFO_ X2_FIFO_ X3_FIFO_ X4_FIFO_ X5_FIFO_ endif The configuration of the FIFO is described in detail in reference ma
75. equired to access the Flash pendrives Doc ID 18153 Rev 3 83 107 USB host library UM1021 Table 36 MSC SCSI commands Function USBH_MSC_Read10 Description Command for logical Block Read USBH MSC Writel0 Command for logical Block Write USBH MSC TestUnitReady Command for checking Device Status USBH MSC ReadCapacity10 Command for requesting the Device Capacity USBH MSC ModeSenseb Command for checking the Write protect status of the mass storage device USBH MSC RequestSense Command for getting error information MSC file system interface module The MSC file system interface module usbh msc fatfs c allows interfacing of file systems with the MSC driver This module should be ported to the selected file system The current USB host library package comes with the open source FatFS file system support see next section for an overview about the FatFS API The functions implemented in the file system interface are Table 37 MSC file system interface functions Function disk initialize Description Initialize disk drive disk read Interface function for a logical page read disk write Interface function for a logical page write disk status Interface function for testing if unit is ready disk ioctl Control device dependent features Note For the FatFS file system the page size is fixed to 512
76. er to a structure of type USBH Usr cb TypeDef This structure defines class independent callbacks see Class independent callback functions on page 89 User callback functions User callbacks are declared in the usbh_usr c user template file Two types of user callbacks are defined e Callback functions related to the class operations MSC or HID e Callback functions independent from class operations They are mainly called during the enumeration phase These callbacks are defined in a structure of type USBH_Usr_cb_TypeDef They are generally used to show messages in the different enumeration stage Class callback functions MSC user callback functions For MSC the following callback is used USBH_USR_MSC_Application After the end of the class initializations this function is called by the MSC state machine in order to give hand to the user for file system access operations In this callback the user can implement any access to the FAT file system file open file read file write using the FAT FS file system API The user can also have access to a structure variable exported from the library MSC class driver USBH_MSC_Param Doc ID 18153 Rev 3 ky UM1021 USB host library Note 4 This variable provides some information about the mass storage key It is defined using a structure of type MassStorageParameter_TypeDef as described below typedef struct _ MassStorageParameter uint32_t
77. erform the data in stage relative to the non control endpoints DataOut This callback is called to perform the data out stage relative to the non control endpoints SOF This callback is called when a SOF interrupt is received this callback can be used to synchronize some processes with the Start of frame IsoINIncomplete This callback is called when the last isochronous IN transfer is incomplete IsoOUTIncomplete This callback is called when the last isochronous OUT transfer is incomplete GetConfigDescriptor This callback returns the USB Configuration descriptor GetOtherConfigDescriptor This callback returns the other configuration descriptor of the used class in High Speed mode GetUsrStrDescriptor This callback returns the user defined string descriptor When a callback is not used it can be set to NULL in the callback structure USB device user interface The Library provides user callback structure to allow user to add special code to manage the USB events This user structure is defined as follows typedef struct _USBD_USR_PROP f void Init void void DeviceReset uint8_t speed void DeviceConfigured void void DeviceSuspended void void DeviceResumed void void DeviceConnected void void DeviceDisconnected void USBD Usr cb TypeDef Init This callback is called when the device library starts up DeviceReset This callback is called when the devi
78. es and replaces all information previously supplied The ST logo is a registered trademark of STMicroelectronics All other names are the property of their respective owners 2012 STMicroelectronics All rights reserved STMicroelectronics group of companies Australia Belgium Brazil Canada China Czech Republic Finland France Germany Hong Kong India Israel Italy Japan Malaysia Malta Morocco Philippines Singapore Spain Sweden Switzerland United Kingdom United States of America www st com ky Doc ID 18153 Rev 3 107 107
79. es html For each example the source folder is split into sre sources and ine includes e The sources directory includes the following files app c contains the main function a Doc ID 18153 Rev 3 UM1021 USB host library stm32fxxx_it c contains the system interrupt handlers system_stm32fxxx c system clock configuration file for STM32Fxxx devices usb_bsp c contains the function implementation declared in the usb_bsp h file in the USB OTG Low Level Driver to initialize the GPIO for the core time delay methods and interrupts enabling disabling process usbh_usr c contains the function implementation declared in the usbh usr h file in the USB Library to handle the library events from user layer event messages The includes directory contains the following files stm32fxxx it h header file stm32fxxx_it c file usb_cont h configuration files for the USB OTG low level driver usbh_conf h configuration files for the USB Host library Note For HID demonstration the usbh_usr_lcd c file is used to draw the mouse graphical For Dual core demonstration additional files are used dual_core_demo c h implementation of the demonstration usbh msc usr c h contains the user callbacks for mass storage layer usbh_hid_usr c h contains the user callbacks for HID layer When using the USB OTG Full speed core the user should use the CN8 connector on the STM322xG EVAL a
80. escriptor USBH ParseClassDesc Function used for parsing HID report descriptor USBH Set Idle Class request for setting IDLE time USBH Set Report Class request for sending Report OUT data not used in the demonstration software USBH Set Protocol Class request for setting the HID protocol Boot or Report 1 USB Set Protocol is called to set the Boot protocol mode 86 107 Doc ID 18153 Rev 3 a UM1021 USB host library HID mouse and keyboard specific management The mouse or keyboard device is detected when parsing the interface descriptor in the USBH HID Interfacelnit function The specific initialization for each type of device and the decoding of the received report IN data is performed by two functions which are declared in a structure of type HID cb TypeDef which is defined as follows typedef struct HID cb void Init void void Decode uint8_t data HID cb TypeDef The implementation of the above structures in case a mouse or keyboard is respectively found in HID MOUSE cb and HID MOUSE cb is as follows HID cb TypeDef HID MOUSE cb MOUSE_Init MOUSE_Decode Yi HID cb TypeDef HID KEYBRD cb KEYBRD_Init KEYBRD_Decode yi Table 41 Mouse and keyboard initialization 4 HID report decoding functions Function Description MOUSE Init Initialization routine for USB mouse nodem Hana HID report decoding for mou
81. ests and their valid parameters in the library Requests that are not in this table are considered as non standard requests Doc ID 18153 Rev 3 25 107 USB device library UM1021 Table 4 Standard requests 26 107 Doc ID 18153 Rev 3 EF pa pa ka o o O o Slgelelel e k 7g 5 a 28 5 Comments TI3 B 3 55 3 a l l A C 80 00 00 00 00 2 Gets the status of the Device c 81 00100 N 00 2 Gets the status of Interface where N is the valid interface number GET_STATUS A C 82 o0 oo oo oo 2 Oets the status of Endpoint 0 OUT direction a c 82 o0 00 80 oo 2 Gets the status of Endpoint 0 IN direction C 82 00 00 EP 00 2 Gets the status of Endpoint EP a c loo 01 00 00 00 00 Clears the device remote wakeup feature CURAR FEATURE Clears the STALL condition of C 02 00 00 EP 00 00 endpoint EP EP does not refer to endpoint 0 ac 00 01 00 00 00 00 Sets the device remote wakeup feature SET_FEATURE F3 z ets the STALL condition of endpoint c Bene ee ae Mm EP EP does not refer to endpoint 0 SET ADDRESS DA o0 N 00 00 00 00 Sets the device address N is the valid device address Non a All 80 00 01 00 00 0 Gets the device descriptor Non Gets the configuration descriptor All 80 N 02 00 00 0 wher
82. ev uint8 t cfgidx Control Endpoints uint8 t Setup void pdev USB SETUP REQ rea uint8 t EPO_TxSent void pdev uint8 t EPO_RxReady void pdev Class Specific Endpoints uint8 t DataIn void pdev uint8 t epnum uint8 t DataOut void pdev uint8 t epnum uint8 t SOF void pdev uint8 t IsoINIncomplete void pdev uint8 t IsoOUTIncomplete void pdev uint8 t GetConfigDescriptor uint8 t speed uint16 t length ifdef USB OTG HS CORE uint8 t GetOtherConfigDescriptor uint8 t speed uint16 t length endif ifdef USB SUPPORT USER STRING DESC uint8 t GetUsrStrDescriptor uint8 t speed uint8 t index uint16 t length endif USBD Class cb TypeDef 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 5 Delnit This callback is called when the clear configuration request has been received this function closes the endpoints used by the class interface e Setup This callback is called to handle the specific class setup requests EPO TxSent This callback is called when the send status is finished EPO RxSent This callback is called when the receive status is finished 4 Doc ID 18153 Rev 3 35 107 USB device library UM1021 Note 6 6 36 107 Dataln This callback is called to p
83. evice is initialized using the following function DCD_Init USB OTG CORE HANDLE pdev USB OTG CORE ID TypeDef coreID The Rx and Tx FIFOs size and start address are set inside this function to use one more endpoints in addition to the control Endpoint 0 The user can change the FIFO settings by modifying the default values and changing the FIFO depth for each Tx FIFO in the usb_cont h file Endpoint configuration Once the USB OTG core is initialized the device mode is selected The upper layer may call the low level driver to open or close the active endpoint to start transferring data The following two APIs are used uint32_t DCD_EP Open USB_OTG_CORE_HANDLE pdev uint8_t ep_addr uint16 t ep_mps uint8 t ep type uint32 t DCD EP Close USB OTG CORE DEVICE pdev uint8 t ep addr Doc ID 18153 Rev 3 17 107 USB OTG low level driver UM1021 Device core structure The DCD_DEV structures contain all the variables and structures used to keep in real time all the information related to devices the control transfer state machine and also the endpoint information and status typedef struct f DC In this structure device_config holds the current USB device configuration and device_state controls the state machine with the following states EPO State define USB OTG EPO IDLE 0 define USB OTG EP0O SETUP 1 define USB OTG EPO DATA IN 2 define USB OTG EPO DATA OUT 3
84. example message 2 99 USB dual core host example eee eet 99 Men StructUre neresi ie a araa aa a tie SER IBAAN ea eo E a ee 100 USB Manual DRD example 2 22 cece eee ttt eae 100 Doc ID 18153 Rev 3 ky UM1021 List of figures Figure 49 Menu structure Doc ID 18153 Rev 3 7 107 Reference information UM1021 1 1 8 107 Reference information Glossary Table 1 gives a brief definition of acronyms and abbreviations used in this document Table 1 List of terms Term Meaning AHB AMBA High performance Bus AMBA Advanced Microcontroller Bus Architecture CDC Communication Device Class DCD Device Core Driver DFU Device Firmware Upgrade DRD Dual Role Device FIFO First In First Out FS Full Speed 12 Mbps HCD Host Core Driver HID Human Interface Device HNP Host Negotiation Protocol HS High Speed 480 Mbps LS Low Speed 1 5 Mbps Mbps Megabit per second MSC Mass Storage Class OTG USB On The Go PHY Physical Layer as described in the OSI model SRP Session Request Protocol USB Universal Serial Bus Doc ID 18153 Rev 3 UM1021 USB host and device library overview 2 2 1 USB host and device library overview The following figure gives an overview of the USB host and device libraries Figure 1 USB host and device library organization overview Device Audio class DFU Manual DRD
85. g the HOST_CLASS_REQUEST state It is used to process initial class requests Machine implements the class core state machine It is called during the HOST_CLASS core state 7 6 USB host classes 7 6 1 Mass storage class The mass storage class driver is used to support the common USB flash driver using the BOT Bulk Only Transport protocol and the Transparent SCSI command set The following modules located in the Libraries STM32_USB_HOST_Library Class MSC folder are used to implement the MSC driver Doc ID 18153 Rev 3 81 107 USB host library UM1021 Table 33 Modules Module Description usbh msc core c h MSC core state machine implementation usbh msc bot c h BOT Bulk Only Transport protocol implementation usbh msc scsi c h SCSI command implementation usbh_msc _fatfs c h see tt interfacing with a file system for file access The block diagram in the following figure shows the interactions between these modules Figure 36 Block diagram organization of the MSC driver User MSC application callbacks iaasa as ee et Ny eT napaaga aa File system FAtFS A I I I I I I I I File system driver I I 1 MSC class core I I I I I I I I I I I I I I SCSI commands BOT state machine USB I O requests Operation flow description MS19712V1 The MSC core state machine starts with the required device initializations
86. handles ifdef USB_OTG HS INTERNAL DMA ENABLED if defined ICCARM lt IAR Compiler pragma data_alignment 4 endif endif USB OTG HS INTERNAL DMA ENABLED ALIGN BEGIN USB OTG CORE HANDLE USB OTG dev _ ALIGN END The USB Library is built as an interrupt model from application layer the user has only to call the USBD Init function and pass the user and class callbacks The USB internal process is handled internally by the USB library and triggered by the USB interrupts from the USB driver Figure 15 USBD Init function example 113 114 USBD Init 4USB OTG dev 115 ifdef USE USB OTG HS 116 USB OTG HS CORE ID 117 else 118 USB OTG FS CORE ID 119 endif 120 sUSR desc 121 sUSBD MSC cb 122 USR cb 123 124 while 1 125 126 if i 0x100000 127 f 128 STM EVAL LEDToggle LED1 129 STM EVAL LEDToggle LED2 130 STM EVAL LEDToggle LED3 131 STM EVAL LEDToggle LED4 132 i 0 133 134 aaa ky Doc ID 18153 Rev 3 63 107 USB device library UM1021 6 10 Note 6 10 1 64 107 USB device examples Each project for an example based on a class is given with five configurations as follows exception made for USB device dual core example 1 STM322xG EVAL USBD HS High speed example on the STM322xG EVAL board working with USB OTG HS core and the ULPI PHY 2 STM322xG EVAL USBD FS Full speed example on the STM322xG EVAL bo
87. he USB OTG core is initialized the host mode is selected The upper layer may call the low level driver to open or close a host channel to start transferring data The following API is used uint32 t HCD HC Init USB OTG CORE HANDLE pdev uint8 t hc num Host driver structures After initializing the Host driver HCD the low level driver holds several structures and buffers for data and URB status monitoring The host channel structures are kept in the host driver and accessed from the upper layer through the host number index typedef struct _HCD uint8 t Rx Buffer MAX DATA LENGTH TIO uint32_t ConnSts TO uint32 t ErrCnt USB OTG MAX TX FIFOS IO uint32 t XferCnt USB OTG MAX TX FIFOS IO HC STATUS HC Status USB OTG MAX TX FIFOS IO URB STATE URB State USB OTG MAX TX FIFOS USB OTG HC he USB OTG MAX TX FIFOS uint16 t channel USB OTG MAX TX FIFOS Doc ID 18153 Rev 3 ky UM1021 USB OTG low level driver USB_OTG_hPort_TypeDef tport cb HCD DEV USB OTG USBH PDEV In this structure e Rx Buffer this buffer holds the IN packet and can be accessed directly from the global Host Core structure as follows pdev gt host Rx_Buffer ConnSts connection status It can be accessed directly or by using the HCD_IsDeviceConnected function e 5 ErrCnt holds the number of errors on a channel during one transfer XferCnt holds the number of IN data already rece
88. he class state machine is called for class related operation non control and control operation e HOST_CTRL_XFER this state is entered whenever there is a need for a control transfer e HOST ERROR STATE this state is entered whenever there is an unrecovered error from any library state machine In this case a user callback function is called for example for displaying an unrecovered error message Then the host library is re initialized The core state machine process is implemented by the USBH_Process function This function should be called periodically from the application main loop The initialization of the USB host library is implemented by the USBH_init function This function should be called from the user application during initialization For further details on this function refer to Section 7 7 1 Library user API on page 88 Device enumeration After detecting a device the host library proceeds with a basic enumeration of the device The following diagram shows the different steps involved in the device enumeration Figure 35 Device enumeration steps Get first 8 bytes of device descriptor USB reset r Get full device descriptor Set device address Get configuration descriptor Get string descriptors MFC product and serial number Set device configuration MS19711V1 Doc ID 18153 Rev 3 ky
89. ice An SRP capable USB HS FS low speed host A device A USB OTG FS dual role device Supports HS FS SOF start of frame pulses as well as low speed LS keep alive tokens with SOF pulse pad output capability SOF pulse internal connection to Timer 2 TIM2 Configurable framing period Configurable end of frame interrupt Embeds an internal DMA with thresholding support and software selectable AHB burst type in DMA mode Powersaving features such as system clock stop during USB suspend switching off of the digital core internal clock domains PHY and DFIFO power management Dedicated 4 Kbyte data RAM with advanced FIFO management Memory partition can be configured into different FIFOs to allow flexible and efficient use of RAM Each FIFO can contain multiple packets Memory allocation is performed dynamically FIFO size can be configured to values that are not powers of 2 to allow the use of contiguous memory locations Ensures a maximum USB bandwidth of up to one frame without application intervention STM32F105 07xx devices embed one USB OTG FS core while STM32F2xx and STM32F4xx devices embed one USB OTG FS core and one HS core Doc ID 18153 Rev 3 ky UM1021 USB OTG low level driver 5 5 1 5 2 USB OTG low level driver USB OTG low level driver architecture Figure 3 Driver architecture overview HCD INT Upper layer library and high level softwa
90. ions 60 107 Doc ID 18153 Rev 3 ky UM1021 USB device library 6 7 6 4 CDC known limitations When using this driver with the OTG HS core enabling DMA mode define USB OTG HS INTERNAL DMA ENABLED in usb cont 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 To create a new custom class the user has to add USBD_CustomClass_cb as described in Section 6 5 USB device class interface typedef struct Device cb uint8 t Init void pdev uint8 t cfgidx uint8 t DeInit void pdev uint8 t cfgidx Control Endpoints uint8 t Setup void pdev USB SETUP REQ req uint8 t EPO_TxSent void pdev uint8 t EPO_RxReady void pdev Class Specific Endpoints uint8 t DataIn void pdev uint8 t epnum uint8 t DataOut void pdev uint8 t epnum uint8 t SOF void pdev uint8 t TsoINIncomplete void pdev uint8 t TsoOUTIncomplete void pdev uint8 t GetConfigDescriptor uint8_t speed uint16 t length ifdef USB OTG HS CORE uint8 t GetOtherConfigDescriptor uint8 t speed uint16 t length endif ifdef USB SUPPORT USER STRING DESC uint8 t GetUsrStrDescri
91. ived and available in the Rx Buffer It can be accessed directly or by using the GetXferCnt function e HC Status used internally by the driver It can be accessed also by the upper layer It keeps the status of the current transaction on a channel URB State this variable keeps the transfer status on a host channel Channel this variable manages the host channels status used or free port cb host port callbacks that contain variables used to track the use of the connection or disconnection handler to prevent multiple accesses to this handler Example if HCD IsDeviceConnected pdev amp amp pdev gt host port_cb gt DisconnHandled 0 pdev gt host port_cb gt DisconnHandled 1 Handle to avoid the Re entry USBH_DeInit pdev phost Starting a host transfer Once a host channel is initialized it can be used to start a host transfer The following API is used uint32_t HCD_SubmitRequest USB_OTG_CORE_HANDLE pdev uint8_t hc_num At this point the transfer flow is handled by the HCD interrupts usb hcd int c h and the upper layer can monitor the transfer progress using the following APIs URB_STATE HCD_GetURB_State USB_OTG_CORE_HANDLE pdev uint8_t ch_num HC STATUS HCD GetHCState USB OTG CORE HANDLE pdev uint8 t ch num uint32 t HCD GetXferCnt USB OTG CORE HANDLE pdev uint8 t ch num USB host monitoring It is not possible
92. ks driver and the usbd msc c h p 2 gt configuration descriptors relative 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 M A F PAPA SG This file contains the vital inquiry pages and the sense data usbd_info c h of the mass storage devices This file contains the function prototypes of the called usbd_mem h functions from the SCSI layer to have access to the physical media usbd_dfu_core This file contains the DFU class callbacks driver and the Crh configuration descriptors relative to this class usbd_flash_if This file contains the DFU class callbacks relative to the Crati internal Flash memory interface DFU bd otp if h This file contains the DFU class callbacks relative to the MRAR P E es OTP memory interface usbd_template_if This file provides a template driver which allows you to c h implement additional memory interfaces usbd_audio_core This file contains the AUDIO class callbacks driver and the lt h configuration descriptors relative to this class Audio usbd_audio_out_if This file contains the lower layer audio out driver from USB zeh host to output speaker usbd_cdc_core This file contains the CDC class callbacks driver and the ene c h configuration descriptors relative to this class D usbd_cdc_if_templat e c h This file provides a template driver which allows you to imp
93. lasses should be managed by user application 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 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 On a periodic interval defined through CDC IN FRAME INTERVAL in usbd_cont h file the driver checks if there are available data in the buffer It sends them into successive packets to the host through data IN endpoint 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 finished 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
94. lement low layer functions for a CDC terminal Doc ID 18153 Rev 3 a UM1021 USB device library 6 7 1 4 HID class HID class implementation This module manages the MSC class V1 11 following the Device Class Definition for Human Interface Devices HID Version 1 11 June 27 2001 This driver implements the following aspects of the specification The boot interface subclass The mouse protocol e Usage page generic desktop e Usage joystick e Collection application HID user interface The USBD_HID_SendReport can be used by the 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 static uint8_t HID_Buffer 4 USBD_HID_SendReport amp USB_OTG_FS_dev USBD HID GetPos 4 static uint8_t USBD_HID_GetPos void HID_Buffer 0 0 HID Buffer 1 GetXPos HID Buffer 2 GetXPos HID Buffer 3 0 return HID Buffer HID core files Table 10 usbd_hid_core c h files Functions Description static uint8 t USBD HID Init Initializes the HID interface and open the used void pdev uint8_t cfgidx endpoints static uint8_t USBD HID Delnit Un Initializes the HID layer and close the used void pdev uint8 t cfgidx endpoints static uint8 t USBD HID Setup void Handles the HID ific r ts tpdev USB SETUP RHO req GdlEsang Specme reque
95. low level driver through the DCD HandleRxStatusQueueLevel ISR and DCD HandleInEP ISR when the USB OTG core is running in Slave mode and by the internal DMA when the DMA mode is used DMA mode available only with the USB OTG HS core Doc ID 18153 Rev 3 29 107 USB device library UM1021 6 3 6 6 3 7 6 3 8 30 107 Using the multi packet feature To transmit data the DCD_EP_Tx function is called and to receive data DCD_EP_PrepareRx is called an with unlimited data length Internally the USB OTG core checks the available space in the FIFO and processes the transfer respecting the endpoint size For example if the endpoint size is configured to work with 64 bytes of data and the user wants to transmit receive N bytes of data the USB core sends receives several packets of 64 bytes each USB control functions User applications can benefit from a few other USB functions included in a USB device Device reset When the device receives a reset signal from the USB the library resets and initializes the application on both software and hardware This function is part of the interrupt routine Interrupt routine restrictions apply Device suspend When the device detects a suspend condition on the USB the library stops all the operations and puts the system to suspend state if low power mode is enabled by in the usb_cont h file Device resume When the device det
96. mples Each project for an example based on a class is given with five configurations as follows exception made for USB Host dual core example STM322xG EVAL_USBD HS High speed example on the STM322xG EVAL board working with USB OTG HS core and the ULPI PHY STM322xG EVAL_USBD FS Full speed example on the STM322xG EVAL board working with USB OTG FS core and the embedded FS PHY STM324xG EVAL_USBD HS High speed example on the STM324xG EVAL board working with USB OTG HS core and the ULPI PHY STM324xG EVAL_USBD FS Full speed example on the STM324xG EVAL board working with USB OTG FS core and the embedded FS PHY STM3210C EVAL_USBD FS Full speed example on the STM3210C EVAL board working with USB OTG FS core and the embedded FS PHY For the High speed examples the following features are selected in the usb_config h file 1 USB_OTG_HS_ULPI_PHY_ENA USB_OTG_HS_INTERNAL _ BLEI D ULPI Phy is used Important notes DMA ENABLED internal DMA is used The USB Host examples are using the Icd_log c module to redirect the Library and User messages on the screen Depending on the LCD cache depth used to scroll forward and backward within the message the applications footprints are impacted With bigger LCD cache depth the RAM footprint is consequently increased To prevent this additional RAM Doc ID 18153 Rev 3 UM1021 USB host library 7 10 1 footprint the user can redirect the Li
97. ms Processes the Inquiry command static int8 t SCSI ReadCapacity10 uint8 t lun uint8 t params Processes the Read Capacity 10 command static int8 t SCSI ReadFormatCapacity uint8 t lun uint8 t params Processes the Read Format Capacity command static int8 t SCSI ModeSenseb uint8 t lun uint8 t params Processes the Mode Sense 6 command static int8 t SCSI ModeSensel10 uint8 t lun uint8 t params Processes the Mode Sense 10 command static int8 t SCSI RequestSense uint8 t lun uint8 t params Processes the Request Sense command void SCSI_SenseCode uint8_t lun uint8_t sKey uint8_t ASC static int8_t SCSI StartStopUnit uint8 t lun uint8 t params Loads the last error code in the error list Processes the Start Stop Unit command static int8_ lun uint8_ SCSI Read10 uint8 t params CE T Processes the Read10 command static int8_ lun uint8_ SCSI Writel0 uint8_t params T T static int8_ lun uint8_ SCSI Verify10 uint8 t params Processes the Write10 command Processes the Verify10 command static int8 t SCSI CheckAddressRange uint8 t lun uint32 t blk offset uint16 t blk nbr static int8 t SCSI ProcessRead uint8 t lun Checks if the LBA is inside the address range Handles the Burst Read process static int8 t SCSI ProcessWrite uint8 t lun Handles the Burst Write
98. nage the multi packet feature on the control endpoint or directly from the usb dcd c layer when the other endpoints are used since the USB OTG core supports the multi packet feature The following figure illustrates this data flow scheme Doc ID 18153 Rev 3 ky UM1021 USB device library Figure 10 USB device data flow USBD_CtlSendData USBD CtlContinueSendData USBD Status USBD CtlPrepareRx USBD Status USBD CtlContinueRx USBD GetRxCount kA e reir DCD EP Tx Status USBD CtlReceiveStatus DCD EP PrepareRx USBD GetRxCount mig DCD EP Tx DCD EP PrepareRx MS20017V1 6 3 4 USB device library configuration The USB device library can be configured using the usbd_confh file a template configuration file is available in the Libraries STM32_USB_Device_Library Core directory of the library define USBD_CFG_MAX NUM 1 define USB_MAX_STR_DESC_SIZ 64 USB MSC Class Layer Parameter define MSC_IN_EP 0x81 define MSC OUT EP 0x01 define MSC_MAX_PACKET 512 define MSC_MEDIA_PACKET 4096 USB HID Class_Layer_Parameter x define HID_IN_EP 0x81 define HID OUT EP 0x01 define HID IN PACKET 4 define HID OUT PACKE 4 6 3 5 USB data transfer handling 4 The USB data transfer handling supports multi packet transfer features so that a large amount of data can be sent without splitting it into maximum packet size transfers The multi packet process is handled by the
99. nd STM324xG EVAL or the CN2 connector when the STM3210C EVAL is used When using the USB OTG High speed core the user should use the CN9 connector on the STM322xG EVAL and STM324xG EVAL boards 7 9 Starting the USB host library Since the USB Library can handle multi core instances the user has to define beforehand the core device handle and the host structure pointer in the main file 56 59 defgroup USBH USR MAIN Private Variables 60 G7 SA AG B 61 62 USB_OTG_CORE_HANDLE USB OTG Core dev 63 USBH_HOST USB_Host 64 j 65 66 k7 The USB Library is built in interrupt model from application layer the user has only to call the USBH Init function and pass the user and class callbacks The USB internal process is handled internally by the USB library and triggered by the USB interrupts from the USB driver Doc ID 18153 Rev 3 93 107 USB host library UM1021 7 10 Note 94 107 176int main void 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 Init HS Core USBH_Init USB OTG Core USB OTG HS CORE ID gUSB Host sUSBH MSC cb sUSR_MSC cb LCD UsrLog USB Host High speed initialized 1n Init FS Core USBH Init amp USB_OTG FS Core USB OTG FS CORE ID amp USB_FS Host amp HID cb amp USR_HID cb LCD UsrLog USB Host Full speed initialized n USB host exa
100. nit amp USB_OTG_dev ifdef USE USB OTG HS USB OTG HS CORE ID else USB OTG FS CORE ID endif od be Select the USB OTG Core HS or FS in usb_conf h file USE_USB_OTG_HS if the USB OTG HS Core is to be used USE USB OTG FS if the USB OTG FS Core is to be used Select the PHY to be used in usb cont h file For the USB OTG HS Core you can select the PHY to be used using one of these two defines USE_ULPI_PHY if the USB OTG HS Core is to be used in High speed mode USE EMBEDDED PHY if the USB OTG HS Core is to be used in Full speed mode For USB OTG FS Core the on chip Full Speed PHY is used no need for any configuration To avoid modifying these defines each time you need to change the USB configuration you can declare the needed define in your toolchain compiler preprocessor The USE ULPI PHY symbol is defined in the project compiler preprocessor as default PHY when the HS core is used On STM322xG E VAL and STM324xG EVAL boards and for the HS core only the external ULPI High Speed PHY is available On chip Full Speed PHY need a different hardware For more details refer to your STM32 device datasheet 2 How can the used endpoints be changed in the USB Device class driver To change the endpoints or to add a new endpoint a b Perform the endpoint initialization using DOD EP Open Configure the TX or
101. nt8 t idx uint16 t length endif USB SUPPORT USER STRING DESC USBD DEVICE pUSBD DEVICE e GetDeviceDescriptor This callback returns the device descriptor e GetLang DSirDescriptor This callback returns the Language ID string descriptor e GetManufacturerSitrDescriptor This callback returns the manufacturer string descriptor e GetProductSirDescriptor This callback returns the product string descriptor e GetSerialSirDescriptor This callback returns the serial number string descriptor e GetConfigurationStrDescriptor This callback returns the configuration string descriptor e GetlinterfaceSirDescriptor This callback returns the interface string descriptor e Get_USRStringDesc This callback returns the user defined string descriptor Note The usbd_desc c file provided within USB Device examples implement these callback 4 bodies Doc ID 18153 Rev 3 37 107 USB device library UM1021 6 7 38 107 USB device classes The class module contains all the files relative to the class implementation It complies with the specification of the protocol built in these classes The table below presents the USB device class files for the MSC and HID classes Table 9 USB device class files Class Files Description HID usbd hid Ge h This file contains the HID class callbacks driver and the configuration descriptors relative to this class This file contains the MSC class callbac
102. ntained therein or considered as a warranty covering the use in any manner whatsoever of such third party products or services or any intellectual property contained therein UNLESS OTHERWISE SET FORTH IN ST S TERMS AND CONDITIONS OF SALE ST DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY WITH RESPECT TO THE USE AND OR SALE OF ST PRODUCTS INCLUDING WITHOUT LIMITATION IMPLIED WARRANTIES OF MERCHANTABILITY FITNESS FOR A PARTICULAR PURPOSE AND THEIR EQUIVALENTS UNDER THE LAWS OF ANY JURISDICTION OR INFRINGEMENT OF ANY PATENT COPYRIGHT OR OTHER INTELLECTUAL PROPERTY RIGHT UNLESS EXPRESSLY APPROVED IN WRITING BY TWO AUTHORIZED ST REPRESENTATIVES ST PRODUCTS ARE NOT RECOMMENDED AUTHORIZED OR WARRANTED FOR USE IN MILITARY AIR CRAFT SPACE LIFE SAVING OR LIFE SUSTAINING APPLICATIONS NOR IN PRODUCTS OR SYSTEMS WHERE FAILURE OR MALFUNCTION MAY RESULT IN PERSONAL INJURY DEATH OR SEVERE PROPERTY OR ENVIRONMENTAL DAMAGE ST PRODUCTS WHICH ARE NOT SPECIFIED AS AUTOMOTIVE GRADE MAY ONLY BE USED IN AUTOMOTIVE APPLICATIONS AT USER S OWN RISK Resale of ST products with provisions different from the statements and or technical features set forth in this document shall immediately void any warranty granted by ST for the ST product or service described herein and shall not create or extend in any manner whatsoever any liability of ST ST and the ST logo are trademarks or registered trademarks of ST in various countries Information in this document supersed
103. nuals RM0033 and RM0008 The Rx and the TXs FIFOs can be calculated as follows S SIZI S SIZI S SIZI S SIZI S SIZI S SIZI E512 E128 E384 EO EO EO EO 1 Receive data FIFO size RAM for setup packets Data Out endpoint control information Data Out packets Miscellaneous Space ONE 32 bit word RAM for setup packets 10 Data Out endpoint control information 1 space one space for status information written to the FIFO along with each received packet Data Out packets largest packet size 4 1 space MINIMUM to receive packets OR Data Out packets at least 2 largest packet size 4 1 space if high bandwidth endpoint is enabled or multiple isochronous endpoints Miscellaneous 1 space per Data Out endpoint one space for transfer complete status information also pushed to the FIFO with each endpoint s last packet MINIMUM RAM space required for each Data In endpoint Tx FIFO MAX packet size for that particular Data In endpoint More space allocated in the Data In endpoint Tx FIFO results in a better performance on the USB and can hide latencies on the AHB Txn minimum size 16 words where nis the Transmit FIFO index When a Tx FIFO is not used the Configuration should be as follows Case 1 n gt m and Txn is not used where n m are the Transmit FIFO indexes Txmcan use the space allocated for Txn Case 2 n lt m and Txn is not used where n m are th
104. on without changing the library code Read Only 32 bit aligned data structures to handle DMA based transfer in High speed modes Supports multi USB OTG core instances from a user level USB device library overview Figure 7 USB device library architecture Application module Application User callbacks USB library module USB class module USB device core Class layer HID audio MSC DFU CDC USB I O requests vendor specific USB requests USB low level driver module DCD ISRs Core interface layer MS19708V1 As shown in the above figure the USB device library is composed of two main parts the library core and the class drivers The library core is composed of three main blocks USB device core USB requests USB I O requests Doc ID 18153 Rev 3 23 107 USB device library UM1021 6 2 6 3 6 3 1 24 107 USB device library files Figure 8 USB device library file structure STM32_USB_Device_Library Class audio cdc dfu hid msc Core inc usbd_conf_template h usbd_core h usbd def h usbd_ioreg h usbd_reg h usbd usrh usbd core c usbd_ioreg c usbd_reg c Release Notes html j maom s TEITEI al ET TIE The USB device library is based on the generic USB OTG low level driver whi
105. ow level driver UM1021 Note 5 4 5 20 107 Specific OUT and IN interrupt The USB OTG High Speed core embeds two independent interrupts for endpoint 1 IN and endpoint 1 OUT Consequently the USBD_OTG_EP10UT_ISR_Handler and USBD OTG EP1IN ISR Handler can be used to lighten the global USB OTG interrupt The specific endpoint feature is selected by enabling the USB_OTG_HS_DEDICATED_EP1_ENABLED define in the usb contfh file Internal DMA use in High speed mode The USB OTG High Speed core embeds an internal DMA capable of handling the FIFO I O request automatically without using the CPU However the data structures used in DMA mode should be 32 bit aligned The internal DMA feature is selected by enabling the USB_OTG_HS_INTERNAL_DMA_ENABLED define in the usb_conth file The Internal DMA and Specific OUT and IN interrupt features can be used together to enhance data transfer performance Programming host drivers Host driver initialization The host is initialized using the following function HCD Init USB OTG CORE HANDLE pdev USB OTG CORE ID TypeDef coreID This function sets the Rx and periodic non periodic Tx FIFOs size and start address The user can change the FIFO settings by modifying the default values and changing the FIFO depth for each periodic and non periodic Tx FIFO in the usb cont h file Host channel initialization Once t
106. owing aspects of the specification e Device descriptor management Configuration descriptor management Enumeration as DFU device in DFU mode only Request management supporting ST DFU sub protocol Memory request management Download Upload Erase Detach GetState GetStatus e DFU state machine implementation Note ST DFU sub protocol is compliant with 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 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 Manifestation Tolerant mode 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 ky Doc ID 18153 Rev 3 45 107 USB device library UM1021 46 107 Table 16 DFU states State State code appIDLE 0x00 appDETACH 0x01 dfuIDLE 0x02 dfuDNLOAD SYNC 0x03 dfuDNBUSY
107. ples for hosts m Mass storage using file explorer write files and slide show m HID dynamic support for mice and keyboards m Dual core for mass storage on the high speed port and HID keyboards or mice on the full speed port The package also includes an example of a manual dual role device that enables the core to switch between host and device modes depending on user input March 2012 Doc ID 18153 Rev 3 1 107 www st com Contents UM1021 Contents 1 Reference information 2 200 c cece cece eee 8 1 1 Glossa ese on gos cee age aa BANG TAKA AA Sencee teas BAKYA HAN 8 2 USB host and device library overview 0002e cece e eee 9 2 1 Main features Sc haa NAB eae eeaee NAT ece ten ees Ae ee BABAHA NAK eee 9 3 USB host and device library folder structure 10 4 USB OTG COM aken a nakak KK An 6a beh emine e Ena uE KA KENA 11 4 1 USB OTG full speed Gora aaa AKNG KAANAK de esses en eew eds 11 4 1 1 OTG FS interface main features 000 cece eee 11 4 2 USB OTG high speed core 1 1 2 2 0 02 cee ee 11 5 USB OTG low level driver ce eee ee eee eee 13 5 1 USB OTG low level driver architecture 00 00 eee eee 13 5 2 USB OTG low level driver files 00 00 00 cee eee 13 5 3 USB OTG low level driver configuration 000e ee eee 14 5 4 USB OTG driver programming manual 000 e ee eee 15 5 4 1 Low level driver structures 0 000 cece eee 1
108. pports multi USB OTG core instances from user level Built around global state machine Fully compatible with real time operating system RTOS Overview Figure 32 USB host library overview Application module ee Application User callbacks USB library module core USB host USB class module ost core USB enumeration Class layer HID audio MSC vendor specific USB control transfer Channels management management USB I O requests USB low level driver module HCD ISRs Core interface layer MS19710V1 As shown in the above figure the USB host library is composed of two main parts the library core and the class drivers Doc ID 18153 Rev 3 75 107 USB host library UM1021 7 2 76 107 The library core is composed of five main blocks Core host core USB enumeration USB control transfer management USB I O requests Channels management For all class related operations the core state machine hands over operation to a specific class driver Two class drivers HID and MSC are implemented These class drivers use core layer services for communicating with the low level driver Both the core and the class drivers communicate with the user application mainly through defined callback functions The various host library blocks are described below USB host library files Figure 3
109. ptor uint8 t speed uint8 t index uint16 t length endif USBD Class cb TypeDef In the DataIn and DataOut functions the user can implement the internal protocol or state machine while in the 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 Doc ID 18153 Rev 3 61 107 USB device library UM1021 6 8 62 107 Additional functions could be added as the IsoINIncomplete and IsoOUTIncomplete could be eventually used to handle incomplete isochronous transfers for more information refer to the USB audio device example EP0 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 Application layer description Figure 13 Folder organization USB_Device_Examples AUDIO EWARM D inc MDK ARM RIDE HG sre TASKING TrueSTUDIO E readme bt DFU DualCore HID MSC VCP Release Notes html For each example the source folder is split into src Sources and inc includes The sources directory includes the following files app c contains the main function e stm32fxxx_it c contains the system interrupt
110. ration HOST CLASS REQUEST End of class requests calls q lt Control transfer HOST CLASS _ a Unrecovered error The core state machine shows nine states e HOST IDLE after host initialization the core starts in this state where it polls for a USB device connection This state is also entered when a device disconnection event is detected and also when an unrecovered error occurs e HOST ISSUE CORE RESET this state is entered when a device is connected in order to generate a USB bus RESET e HOST DEV ATTACHED the core enters this state when a device is attached When a device is detected the state machine moves to the HOST ENUMERATION state e HOST ENUMERATION in this state the core proceeds with a basic enumeration of the USB device At the end of enumeration process the default device configuration configuration 0 is selected e HOST USR INPUT this is an intermediary state which follows the enumeration and which includes a wait for user input in order to start the USB class operation e HOST CLASS REQUEST starting from this state the class driver takes over and a class request state machine is called in order to handle all the initial class control requests ex Get Report Descriptor for HID After finishing the required class requests the core moves to the HOST CLASS state Doc ID 18153 Rev 3 77 107 USB host library UM1021 7 3 2 78 107 e HOST_CLASS in this state t
111. re CIL Core Interface Layer DCD INT Low level driver MS19707V1 The low level driver can be used to connect the USB OTG core with the high level stack The user may develop an interface layer above the Low level driver to provide the adequate APIs needed by the used stack USB OTG low level driver files Figure 4 Driver files STM32 USB OTG Driver inc usb bsp h EWE WE NN ETTEN EE ma usb otgh ma NAOGGH EG usb otg c usb regs h usb conf template h usb core h usb dcdh usb dcd int h usb defines h usb hcdh usb hcd inth usb bsp template c usb core c usb dcd c usb dcd int c usb hcd c usb hcd int c Release Notes html Doc ID 18153 Rev 3 13 107 USB OTG low level driver UM1021 Table 2 USB OTG low level file descriptions Mode Files Description This file contains the hardware abstraction layer and the usb_core c h USB communication operations This file contains the core configuration for Host Device and OTG modes Transmit FIFO size Receive FIFO size Core usb_core c h mode and selected features etc Common This file should be copied to the application folder and modified depending on the application needs This file contains the low level core configuration interrupts GPIO This file should be copied to the application folder and modified depending on the application needs us
112. re directly copied into the audiobuffer and the write buffer IsocOutWrPtr is incremented The Audio Control requests are managed by the functions usbd audio Setup and usbd audio EP0 RxReady These functions route the Audio Control requests to the lower layer i e usbd audio out if c In the current version only SET CUR and GET CUR requests are managed and are used for mute control only Audio known limitations If a 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 Supported audio sampling rates are 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 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 4
113. ress parameter it dispatches the control access request to the relative memory driver or returns error code if the address is not supported Table 19 usbd dfu mal c h files uint16 t MAI Functions L Init void Description Calls memory interface initialization functions supported by the low layer uin uint16 t MAI 16 t MALU L DeInit void Erase uint32_t Sec orAddress Calls memory interface de initialization functions supported by the low layer Calls the memory interface Erase functions supported by the low layer if Erase is not supported this function has no effect uint16 t MAI L Write uint32 t SectorAddress uint32 t Datal Length Calls memory interface Write functions supported by the low layer uint8 t MAJ SectorAddress uint32 t Datal L Read uint32 t Length Calls the memory interface Read functions supported by the low layer sa Doc ID 18153 Rev 3 49 107 USB device library UM1021 Table 19 usbd dfu mal c h files continued Functions Description uint16 t MAL GetStatus uint32 t SectorAddress uint8 t Cmd uint8 t Returns the low layer memory interface status buffer Checks which memory interface supports the current address returns error code if the address is not supported static uint8_t MAL _CheckAdd uint32 t Add The low layer memory interfaces are manage
114. rmed through a lower layer i e usbd_audio_out_if c which you can modify depending on the hardware available for your application To use this driver Through the file usbd_conf h you can configure Doc ID 18153 Rev 3 55 107 USB device library UM1021 6 7 5 56 107 The audio sampling rate define USBD_AUDIO_FREQ The default volume level define DEFAULT VOLUME The endpoints to be used for each transfer defines AUDIO IN EP and AUDIO_OUT_EP The device string descriptors Call the function usbd_audio_Init 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 out if c and can be modified by user depending on the application needs The entire transfer is managed by the following functions no need for user to call any function for out transfers usbd audio SOF which synchronizes the low layer interface at each start of frame For out transfers at each SOF event this function controls the low layer to stop the previous transfer if it is not stopped yet and start playing next sub buffer Each time the reading buffer IsocOutRdPtr is incremented 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 they a
115. s registers CSRs and the data FIFO USB OTG high speed core The OTG_HS is a dual role device DRD controller that supports both peripheral and host functions It is fully compliant with the On The Go Supplement to the USB 2 0 Specification It can also be configured as a host only or peripheral only controller fully compliant with the USB 2 0 Specification In Host mode the OTG_HS supports high speed 480 Mbps full speed 12 Mbps and low speed 1 5 Mbps transfers whereas in Peripheral mode it only supports high speed and full speed transfers Doc ID 18153 Rev 3 11 107 USB OTG core UM1021 12 107 The OTG_HS supports both HNP Host Negotiation Protocol and SRP Session Request Protocol The only external device required is a charge pump for the VBUS power supply in OTG mode The OTG_HS interface has the following features USB IF certified with the Universal Serial Bus Revision 2 0 Specification Supports two PHY interfaces An on chip Full Speed PHY An ULPI UTMI low pin interface interface for the external High Speed PHY Supports the host negotiation protocol HNP and the session request protocol SRP It allows the host to turn VBUS off to save power in OTG applications with no need for external components Can be used to monitor VBUS levels with internal comparators Supports dynamic host peripheral role switching Software configurable to operate as An SRP capable USB HS FS peripheral B dev
116. s the requests implementation listed in Chapter 9 of the specification usbd ioreq c h This file handles the results of the USB transactions usbd conf h This file contains the configuration of the device vendor ID Product Id Strings etc Table 6 usbd core c h files void USBD Init Functions USB OTG CORE HANDLE pdev USB OTG CORE ID TypeDef coreID USBD Class cb TypeDef class cb USBD Usr cb TypeDef usr cb Description Initializes the device library and loads the class driver and the user call backs USBD Status USBD Delnit USB OTG CORE HAND E pdev Un initializes the device library USB OTG CORE HAND uint8 t USBD SetupStage E pdev Handles the setup stage uint8_t USBD_DataOutStage USB_OTG_CORE_HAND E pdev uint8 t epnum Handles the Data Out stage epnum uint8 t USBD_DataInStage USB OTG CORE HANDLE pdev uint8 t Handles the Data In stage uint8_t USBD_Reset USB_OTG_CORE_HANDLE pdev 32 107 Doc ID 18153 Rev 3 Handles the reset event a UM1021 USB device library ng Table 6 usbd core c h files continued Functions Description uint8 t USBD Resume Handles the resume event USB OTG CORE HANDLE pdev uint8 t USBD Suspend USB OTG CORE HANDLE pdev Handles the s
117. same way baudrate data format parity stop bit length To test this example you can use one of the following configurations Doc ID 18153 Rev 3 Configuration 1 Connect USB cable to host and USART RS232 to a different host PC or other device or to the same host In this case you can open two hyperterminal like terminals to send receive data to from host to from device Configuration 2 Connect USB cable to Host and connect USART TX pin to USART RX pin on the evaluation board Loopback mode In this case you can open one terminal relative to USB com port or USART com port and all data sent from this terminal will be received by the same terminal in loopback mode This mode is useful for test and performance measurements 71 107 USB device library UM1021 Figure 27 Configuration 1a Two different hosts for USB and USART Host PC ST Evaluation Board Terminal Target Host PC or other HW Terminal Figure 28 Configuration 1b One single Host for USB and USART ST Evaluation Host PC Board USB Terminali USART Terminal2 Figure 29 Configuration 2 Loopback mode for test purposes ST Evaluation Host PC Board Terminal UsAaRT 72 107 Doc ID 18153 Rev 3 ky UM1021 USB device library 6 10 6 4 USB audio device example The Audio device example allows device to communicate with host PC as USB Speaker using isochronous pipe for a
118. se decoding mouse x y ka a positions pressed buttons KEYBRD Init Initialization routine for USB keyboard KEYBRD Decode HID report decoding for keyboard decoding of the key pressed on the keyboard Note You can select AZERTY or QWERTY keyboard through the defines OWERTY KEYBOARD 4 and AZERTY_KEYBOARD in the usbh_hid_keybd h file Doc ID 18153 Rev 3 87 107 USB host library UM1021 7 7 7 7 1 7 7 2 7 7 3 88 107 USB host user interface Library user API The library user API functions are limited to the two following functions void USBH_Process void this function implements core state machine process It should be called periodically from the user main loop USBH Init this function should be called for the initialization of the USB host hardware and library USBH_Init has the following function prototype void USBH Init USB OTG CORE HANDLE pdev USB OTG CORE ID TypeDef coreID USBH HOST phost USBH Class cb TypeDef class cb USBH Usr cb TypeDef usr cb pdev pointer on the USB host core register structure CoreID USB OTG core identifier select the USB core to be used phost pointer on the USB host machine structure reserved for future use class cb pointer to a class structure of type USBH_Class_cb_TypeDef It can be either USBH_MSC_cb for handling MSC devices or USBH_HID_cb for handling HID mouse keyboard devices e usr_cb point
119. se no data stage is needed the CSW block is sent immediately after the CBW one Figure 11 BOT Protocol architecture Command Transport CBW CBW Status Transport MS19705V1 Doc ID 18153 Rev 3 ky UM1021 USB device library The following table shows the supported SCSI commands Table 11 SCSI commands Command specification Command Remark 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 following requests are implemented 5 Bulk only mass storage reset class specific request 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 bmRequestType Class interface host to device bRequest field set to 255 FFh wvValue field set to 0 windex field set to the interface number wLength field set to 0 Get Max LUN class specific request The device can implement several logical units that share common device char
120. ss Specific AS Interfaces 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 Single fixed audio sampling rate configurable in usbd_cont 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 may 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 Audio Control Endpoint management Doc ID 18153 Rev 3 ky UM1021 USB device library Audio Control requests other than SET_CUR and GET_CUR Abstraction layer for Audio Control requests only mute functionality is managed Audio Synchronization type Adaptive Audio Compression modules and interfaces MIDI interfaces and modules Mixer Selector Processing Extension Units featured unit is limited to Mute control Any other application specific modules Multiple and Variable audio sampling rates Audio Out Streaming Endpoint Interface microphone Audio class implementation The Audio transfers are based on isochronous endpoint transactions Audio control requests are also managed
121. ssion from low layer uint32 t Len terminal to USB host IN transfers uint16 t pIf DataRx uint8 t4 Buf Handles CDC data reception from USB host to uint32 t Len low layer terminal OUT transfers In order to accelerate data management for IN transfers the low layer driver usbd cdc xxx if c h should use two global variables exported from CDC core Doc ID 18153 Rev 3 59 107 USB device library UM1021 Table 28 Variables used by usbd_cdc_xxx_if c h Variable Usage Writes CDC received data in this buffer These data extern uint8 t APP Rx Buffer will be sent over USB IN endpoint in the CDC core functions Increments this pointer or rolls it back to start the extern uint32 t APP Rx ptr in address when writing received data in the buffer APP Rx Buffer How to use this driver This driver uses an abstraction layer for hardware driver i e USART control interface This abstraction is performed through a lower layer i e usbd cdc vcp c which you can modify depending on the hardware available for your application To use this driver e Through the file usbd conf h you can configure The Data IN and OUT and command packet sizes defines CDC DATA IN PACKET SIZE CDC DATA OUT PACKET SIZE CDC CMD PACKET SZE The interval between IN packets define CDC IN FRAME INTERVAL The size of the temporary circular buffer for IN data transfer define APP RX DATA
122. sts uint8_t USBD_HID_SendReport USB_OTG_CORE_HANDLE pdev uint8_t Sends HID reports report uint16_t len Doc ID 18153 Rev 3 39 107 USB device library UM1021 6 7 2 40 107 Mass storage class Mass storage class implementation This module manages the MSC class V1 0 following the Universal Serial 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 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 A general BOT transaction is based on a simple basic state machine it begins with ready state idle state and if a CBW is received from the host three cases can be managed e DATA OUT STAGE when direction flag is set to O the device must be prepared to receive an amount of data indicated in dcBWDataTransferLength in the CBW block At the end of data transfer a CSW is returned with the remaining data length and the STATUS field e DATA IN STAGE when direction flag is set to 1 the device must be prepared to send an amount of data indicated in dcBWDataTransferLength in the CBW block At the end of data transfer a CSW is returned with the remaining data length and the STATUS field e ZERO DATA in this ca
123. t Serial number N A gt use keyboard to tape characters Text entered by the attached keyboard USB Device Library vx x x MS20006V1 The application header title depends on the board in use once the full speed port is used the title is USB OTG FS MSC Host USB dual core host example In this demonstration the user can use one or two devices the mass storage device should be connected to the high speed port while the HID device should be connected to the full speed port Figure 46 USB dual core host example USB OTG Dual Core Host gt High speed detected gt HID device connected High speed device gt Manufacturer Logitech has been detected and gt Product Optical USB mouse correctly enumerated gt Serial number N A gt Enumeration completed Low speed device has been detected and correctly enumerated 1 Mass Storage demo 2 Human Interface demo 3 Mass Storage demo MS20007V1 To move within the menu the user has to use the embedded joystick the menu structure is as follows Doc ID 18153 Rev 3 99 107 USB host library UM1021 7 10 4 100 107 Figure 47 Menu structure Main menu 1 Mass storage demo 2 Human interface demo 3 Re enumerate Mass storage menu 1 Explore flash content 2 Write file to disk 3 Show BMP file 4 Return HID menu 1 Start HID application 2 Show HID report 3 Return MS19714V1
124. the USB 2 0 Specification In Host mode the OTG_FS supports full speed 12 Mbps and low speed 1 5 Mbps transfers whereas in Device mode it only supports full speed transfers The OTG_FS supports both HNP Host Negotiation Protocol and SRP Session Request Protocol The only external device required is a charge pump for the VBUS power supply in Host mode OTG_FS interface main features The OTG_FS interface has the following features Complies with the On The Go Supplement to the USB 2 0 Specification Revision 1 0a Operates in Full Speed 12 Mbps and Low Speed 1 2 Mbps modes Supports Session Request Protocol SRP Supports Host Negotiation Protocol HNP Supports a generic root hub and multi point capabilities and includes automatic ping capabilities Four bidirectional endpoints including 1 control endpoint and 3 device endpoints which support bulk interrupt and isochronous transfers e All device IN endpoints can support periodic transfers Eight host channels with periodic OUT support e Dedicated FIFO transmission for each of the 4 device IN endpoints Each FIFO can hold multiple packets Combined Rx and Tx FIFO size of 320 x 35 bits with Dynamic FIFO sizing 1 25 Kbytes Eight entries in periodic Tx queue 8 entries in non periodic Tx queue Controls on chip FS PHY for USB Host Device or OTG operations Requires an external charge pump for VBUS power supply 32 bit AHB Slave interface for accessing control and statu
125. the KEY button is released after reset the example jumps to user image application loaded in the internal Flash In High speed mode when DMA mode is enabled define USB_OTG_HS_INTERNAL_DMA_ENABLED in file usb_conf h the DMA cannot directly access read write the internal Flash memory and the OTP memory due to STM32F2xx and STM32F4xx product architecture In this case an intermediate buffer is used to store data before loading them to the memory or before sending them through DMA to the USB interface This leads to an overall performance equivalent to Full Speed mode However if another memory is used i e NOR Flash it is possible to fully use DMA mode and get a better performance USB virtual com port VCP device example The VCP example illustrates an implementation of the CDC class following the PSTN sub protocol The VCP example allows the STM32 device to behave as a USB to RS232 bridge Onone side the STM32 communicates with host PC through USB interface in Device mode Onthe other side the STM32 communicates with other devices same host other host other devices through the USART interface RS232 The support of the VCP interface is managed through the ST Virtual Com Port driver available for download from www st com This example can be customized to communicate with interfaces other than USART The VCP example works in High and Full speed modes and has the following USB device information
126. the Rx FIFO size of the new defined endpoints in the usb conf h file The total size of the Rx and Tx FIFOs should be lower than the Total FIFO size of the used core 320 x 32 bits for USB OTG FS core and 1024 x 32 bits for the USB OTG HS core Doc ID 18153 Rev 3 ky UM1021 Frequently asked questions sa 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 can return the correct descriptor buffer relative to the application index using a switch case statement How can the mass storage class driver support more than one logical unit LUN In the usbd_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_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 T const int8_t STORAGE_Inquirydata LUN 0 0x00 0x80 0x02 0x02 USBD STD INQUIRY LENGTH 5 0x00 0x00 0x00 Shy MEPS Mg Ng NO NG Pe Ep FAN SB Bu Manufacturer 8 bytes My TET TOT ER ot S y D T p Product
127. 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 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 this 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 21 Audio control requests Request Supported Meaning SET CUR Yes nVa mode On or Off can also be updated to set volume SET_MIN No NA SET_MAX No NA SET_RES No NA
128. to start any USB Host transfer without connecting a USB device The application can probe the USB Host port using the following API uint32 t HCD IsDeviceConnected USB OTG CORE HANDLE pdev sa Doc ID 18153 Rev 3 21 107 USB OTG low level driver UM1021 22 107 USB Host interrupt subroutines The HCD layer of the USB OTG Low Level Driver has one function to be called from the USB interrupt high speed or full speed uint32_t HCD_Handle_ISR USB_OTG_CORE_HANDLE pdev The hed int h file contains the function prototypes of the functions called from the library core layer to handle the USB events Internal DMA use in high speed mode The USB OTG High Speed core embeds an internal DMA capable of handling the FIFO I O request automatically without using the CPU However the data structures used in DMA mode must be 32 bit aligned The internal DMA feature is selected by enabling the USB OTG HS INTERNAL DMA ENABLED define in the usb_confth file Doc ID 18153 Rev 3 ky UM1021 USB device library 6 6 1 USB device library The USB device library Supports multi packet transfer features so that a large amount of data can be sent without having to split it into maximum packet size transfers Supports up to three back to back transfers on control endpoints compatible with OHCI controllers Uses configuration files to change the core and the library configurati
129. ucture Figure 2 illustrates the tree structure of the USB host and device library folder Figure 2 Folder structure C3 STM32_USB Host Device_Lib_VXYZ _htmresc Libraries CMSIS STM32_USB_Device_Library Class Core Release Notes html STM32 USB HOST Library Cass 5 Core Release Notes html STM32_USB_OTG_Driver STM32F10x_StdPeriph_Driver STM32F2e StdPeriph Driver Project USB Device Examples USB Host Device Examples USB Host Examples Utilities Binary STM32 EVAL Third Party Release Notes html The project is composed of three main directories organized as follows 1 Libraries contains the STM32 USB OTG low level driver the standard peripherals libraries the host and the device libraries 2 Project contains the workspaces and the sources files for the examples given with the package 3 Utilities contains the STM32 drivers relative to the used boards LCD SD card buttons joystick etc This folder contains also the FatFs generic file system used for the Host demos Doc ID 18153 Rev 3 ky UM1021 USB OTG core 4 4 1 4 2 USB OTG core USB OTG full speed core The OTG_FS is a dual role device DRD controller that supports both device and host functions It is fully compliant with the On The Go Supplement to the USB 2 0 Specification It can also be configured as a host only or device only controller fully compliant with
130. udio data transfer along with some control commands i e Mute The Audio device is natively supported by most of operating systems there is no need for specific driver setup The Audio device example works in full soeed mode only as specified in the USB Device Class Definition for Audio Devices V1 0 Mar 18 98 and has the following USB device information define USBD_VID 0x0483 ifdef STM32F2XX define USBD PID 0x5730 else define USBD PID 0x5730 endif STM32F2XX define USBD LANGID STRING 0x409 define USBD_MANUFACTURER_STRING STMicroelectronics define USBD_PRODUCT_FS_STRING STM32 AUDIO Streaming in FS Mode define USBD_SERIALNUMBER_FS_STRING 00000000034E define USBD_CONFIGURATION_FS_STRING AUDIO Config define USBD_INTERFACE_FS_STRING AUDIO Interface At power on the LCD displays the following messages Figure 30 USB audio device power on display message USB OTG AUDIO Device gt USB device Library started gt Device in suspend mode USB Device Library vx x x MS18197V1 When the USB cable is plugged in the LCD displays the following messages Doc ID 18153 Rev 3 73 107 USB device library UM1021 Figure 31 USB audio device cable connected display message USB OTG AUDIO Device gt USB device Library started Audio device gt Device in suspend mode configured and traffic USB Device Library vx x x FS
131. uests are not common for all USB devices The library does not handle any of the requests in these categories Whenever the library receives a request that it does not know the library calls a user defined callback function and passes the request to the user application code 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 typedef struct usb setup req uint8 t bmRequest uint8 t bRequest uint16_t wValue uint16 t windex uint16 t wLength USB SETUP REQ Standard requests Most of the requests specified in the following table of the USB specification are handled as standard requests in the library The table lists all the standard requ
132. uspend event uint8 t USBD SOF Handles the SOF event USB OTG CORE HANDLE pdev USBD Status USBD_SetCfg USB OTG CORE HANDLE pdev uint8 t Configures the device and starts the E interface cfgidx USBD_Status USBD_ClrCfg USB OTG CORE HANDLE pdev uint8_t Clears the current configuration cfgidx uint8 t T Handles incomplete isochron IN USBD_TsoINIncomplete USB_OTG_CORE_HANDLE p onous transfer tpdev uint8 t T Handles incomplete isochron T USBD IsoOUTIncomplete USB OTG CORE HANDLE p ochronous OU transfer tpdev uint8 t USBD DevConnected USB OTG CORE HANDLE Handles device connection event tpdev static uint8 t USBD DevDisconnected USB OTG CORE HANDLE Handles device disconnection event pdev Table 7 usbd ioreq c h files Functions Description USBD Status USBD_CtlSendData USB OTG CORE HANDLE pdev uint8 t Sends the data on the control pipe pbuf uint16 t len USBD Status USBD_CtlContinueSendData USB OTG CORE HANDLF pdev uint8 t DE pbuf uint16 t len pipa Continues sending data on the control USBD Status USBD CtlPrepareRx USB OTG CORE HANDLE pdev uint8 t pbuf uint16 t len Prepares the core to receive data on the control pipe USBD Status USBD_CtlContinueRx USB OTG CORE HANDLE pdev uint8 t
133. value Define Parameter Full Speed High Speed CDC_DATA_IN_PACKET_SIZE Size of each IN data packet 64 512 CDC_DATA_OUT_PACKET_SIZE Size of each OUT data packet 64 512 I Interval time between IN CDC IN FRAME INTERVAL 5 40 packets sending Hi Total size of circular temporary BEE DATA OTZAN buffer for IN data transfer cia AO usbd cdc xxx if c h i e usbd cdc vcp if c h This driver can be part of the user application It is not provided in the library but a template 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 xxx if c h driver manages the terminal interface configuration and communication i e USART interface configuration and data send receive This driver provides the structure pointer extern CDC IF Prop TypeDef APP FOPS where APP_FOPS should be defined in the usbd_conf h file as the low layer interface structure pointer i e define APP FOPS VCP_fops for using Virtual COM Port interface provided in the Virtual COM Port example sa Table 27 usbd cdc xxx if c h files Functions Description uint16 t pIf Init void Initializes the low layer CDC interface uint16 t pIf Delnit void De initializes the low layer CDC interface uint16 t pIf Ctrl uint32 t Cmd Handles CDC control request parsing and uint8 t4 Buf uint32 t Len execution uint16 t pIf_DataTx uint8_t Buf Handles CDC data transmi
134. wn layout by editing the H the usbh hid keybd c file Doc ID 18153 Rev 3 D KEY BRI D_Key array in UM1021 Troubleshooting 9 Troubleshooting When resetting USB device applications HS mode using the Reset button on the STM322xG Eval board RevB the device enters Suspend mode and cannot leave this state until the power cable is removed This issue is due to the fact that the ULPI Phy reset pin is always connected in high state by a hardware pull up In order to use the Reset button to reset the ULPI Phy interface the reset pin of the PHY must be connected by hardware to the Reset button After removing the USB cable on USB HID devices in Full Speed mode the core seems to enter Stop mode and the LEDs stop blinking Is this normal behavior Yes this is normal behavior When a suspend state is detected over the USB data bus the core enters Low Power mode and only a wakeup event or a new connection to the host can wake up the device This behavior can be changed by disabling Low Power mode in the usb_cont h file by commenting the define USB_OTG_FS_LOW_PWR_MGMT_SUPPORT define Even if the define USB_OTG_HS_LOW_PWR_MGMT_SUPPORT is uncommented the USB HID Device enters Low Power mode but cannot wakeup after a new Host connection This behavior is normal since the wakeup signal in the USB OTG HS Core is available only when the USB OTG HS core is working in Full Speed mode Doc ID 1815

Download Pdf Manuals

image

Related Search

Related Contents

evaporador rotatorio económico - Yamato Scientific America, Inc.  MP - 0004 - Regras Técnicas de uso do Terminal - Mercados    

Copyright © All rights reserved.
Failed to retrieve file