UM1734 User Manual: STM32Cube™ USB Device Library
UM1734 User Manual: STM32Cube™ USB Device Library
User manual
STM32Cube™ USB device library
Introduction
The STM32Cube™ is an STMicroelectronics original initiative to make developers’ lives
easier by reducing development effort, time and cost. STM32Cube™ covers the whole
STM32 portfolio.
STM32Cube™ includes:
• STM32CubeMX, a graphical software configuration tool that allows the generation of C
initialization code using graphical wizards.
• A comprehensive embedded software platform, delivered per Series (such as
STM32CubeF4 for STM32F4 Series)
– The STM32Cube™ HAL, STM32 abstraction layer embedded software ensuring
maximized portability across the STM32 portfolio,
– A consistent set of middleware components such as RTOS, USB, TCP/IP,
Graphics,
– All embedded software utilities, delivered with a full set of examples.
The Universal Serial Bus (USB) is the most successful interconnect in the history of
personal computing which is used to connect devices like mouse, game-pads and joysticks,
scanners, digital cameras, and printers. USB has also migrated into consumer electronics
and mobile products.
This user manual describes the STM32Cube™ USB device library which is part of the
STM32Cube™ MCU Package that can be downloaded free from ST website
(http://www.st.com/stm32cube). It is intended for developers who use STM32Cube™ MCU
Package on STM32 microcontrollers. It describes how to start and implement a USB device
applications for most common USB device classes (HID, MSC, Audio, CDC…) based on the
USB device stack that supports all STM32 microcontroller Series.
Note: This document is applicable to all STM32 Series that feature an USB peripheral. However
for simplicity reason, the STM32F4xx devices and STM32CubeF4 are used as reference
platform. To know more about the examples implementation on your STM32 device, refer to
the readme file provided within the associated STM32Cube™ MCU package.
Contents
1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.1 Acronyms and abbreviations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.2 General information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.3 Additional Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.4 References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
7 Frequently-asked questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
8 Revision history . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
List of tables
List of figures
1 Overview
1. Arm is a registered trademark of Arm Limited (or its subsidiaries) in the US and or elsewhere.
1.4 References
• Universal Serial Bus Specification, Revision 2.0, http: //www.usb.org
• USB device class specifications (Audio, HID, MSC, etc.): http://www.usb.org
2.1 Overview
STMicroelectronics offers to its customers new USB stacks (device stack and host stack)
that support all STM32 MCUs together with many development tools such as Atollic®
TrueSTUDIO, IAR Embedded Workbench for ARM ®, and Keil uVision®.
This document focuses on USB device stack. For the host stack, please refer to the related
users manual.
The USB device library is generic for all STM32 microcontrollers, only the HAL layer is
adapted to each STM32 device.
The USB device library comes on top of the STM32Cube™ USB device HAL driver and
offers all the APIs required to develop a USB device application. The present document
describes the STM32Cube™ USB device library middleware module and illustrates how the
user can develop easily his own USB device application by using this library.
The USB device library is a part of STM32Cube™ package for each STM32 Series.
It contains:
• The USB low level driver
• Commonly used USB class drivers
• A set of applications for the most common USB device classes supporting USB Full
speed and High speed transfer types (control, interrupt, bulk and isochronous).
The USB device library aim is to provide at least one firmware demonstration per USB
transfer type:
• Human Interface Device HID
HID Joystick demonstration based on the embedded joystick on the EVAL boards and
Custom HID examples
• Audio streaming
Audio device example for streaming audio data
• Communication Device (CDC)
VCP USB-to-RS232 bridge to realize a virtual COM port.
• Mass storage
Mass storage demonstration based on the microSD card available on the EVAL
boards.
• Device Firmware Upgrade
DFU for firmware downloads and uploads
• Dual Core devices demonstration
Based on mass storage with Human interface and mass storage with CDC device
examples
Among the topics covered are:
• USB device library architecture
• USB device library description
• USB device library state machine overview
• USB device classes overview.
2.2 Features
The main USB device library features are:
• Support of multi packet transfer features allowing sending big amount of data without
splitting it into max packet size transfers.
• Support of up to 3 back to back transfers on control endpoints (compatible with OHCI
controllers).
• Configuration files to change the core and the library configuration without changing
the library code (Read Only).
• 32-bits aligned data structures to handle DMA based transfer in High speed modes.
• Support of multi USB OTG core instances from user level (configuration file).
Note: The USB device library can be used with or without RTOS; the CMSIS RTOS wrapper is
used to make abstraction with OS kernel.
USB device examples do not display log messages.
8VHU$SSOLFDWLRQ
86%GHYLFH/LEUDU\
86%'HYLFH&ODVV'ULYHU
06&+,'&'&$8',2
')8
86%'HYLFH+$/'ULYHU
+DUGZDUH
069
1. The user application is shown in green, the USB library core blocks in orange and the USB Device HAL
driver in blue.
$SSOLFDWLRQ
86%'HYLFH&RUH 86%'HYLFH&ODVV
&RUH
/RJGHEXJ
+,'06&')8$8
86% ',2HWF
5HTXHVWV
,2
5HTXHVWV
86%'HYLFH&RQILJXUDWLRQ
86%'HYLFH+$/'ULYHU
'HYLFH&RQWUROOHU'ULYHU'&'
/RZ/HYHOGULYHU&RUH
069
1. The USB library core blocks are shown in orange, the USB Device Configuration in magenta and the USB
HAL driver in blue.
The low level driver can be used to connect the USB OTG core with the high level stack.
8SSHUOD\HUVWDFN
27* 'HYLFH DQGKLJKOHYHO
VRIWZDUH
3&'
VWPI[[[BKDOBSFGFK
/RZOHYHOGULYHU
/RZ/D\HU86%'ULYHU
VWPI[[[BOOBXVEFK
069
• The bottom layer (Low Layer USB driver) provides common APIs for device and OTG
modes. It performs the core initialization in each mode and controls of the transfer flow.
• The Peripheral controller driver (PCD) layer provides an API for device mode access
and the main interrupt routine for this mode.
• The OTG controller driver (OTG) layer provides an API for OTG mode access and the
main interrupt routine for this mode.
Note: For more details on how to use the PCD driver, please refer to UM1725 that describes all
PCD driver APIs.
Endpoint configuration
Once the USB core is initialized, the upper layer can call the low level driver to open or close
the active endpoint and start transferring data. The following two APIs can be used:
HAL_StatusTypeDef HAL_PCD_EP_Open(PCD_HandleTypeDef *hpcd, uint8_t ep_addr,
uint16_t ep_mps, uint8_t ep_type)
HAL_StatusTypeDef HAL_PCD_EP_Close(PCD_HandleTypeDef *hpcd, uint8_t ep_addr)
ep_addr, ep_mps and ep_type are respectively the endpoint address, the maximum data
transfer and transfer type.
Note: The USB specification (see Chapter 9) defines six USB device states:
Attached: the device is attached to the USB but is not powered by the USB.
Powered: the device is attached to the USB and has been powered but has not yet received
any reset request.
Default: the device is attached to the USB. It is powered and reset, but no unique address
has been assigned to it.
Address: the device is attached to the USB, it is powered and reset and has had a unique
address assigned to it.
Configured: the device is already in address state and configured. It is not in suspend state.
Suspended: the device is attached and configured, but has not detected any activity on the
bus for at least 3 ms.
Figure 4. USBD_HandleTypedef
typedef struct _USBD_HandleTypeDef
{
uint8_t id;
uint32_t dev_config;
uint32_t dev_default_config;
uint32_t dev_config_status;
USBD_SpeedTypeDef dev_speed;
USBD_EndpointTypeDef ep_in[15];
USBD_EndpointTypeDef ep_out[15];
uint32_t ep0_state;
uint32_t ep0_data_len;
uint8_t dev_state;
uint8_t dev_old_state;
uint8_t dev_address;
uint8_t dev_connection_status;
uint8_t dev_test_mode;
uint32_t dev_remote_wakeup;
USBD_SetupReqTypedef request;
USBD_DescriptorsTypeDef *pDesc;
USBD_ClassTypeDef *pClass;
void *pClassData;
void *pUserData;
void *pData;
} USBD_HandleTypeDef;
The USB device library is based on the generic USB low level driver. It has been developed
to work in Full speed and High speed mode.
It implements the USB device library machines as defined by Universal Serial Bus
Specification revision 2.0. The library functions are covered by the files located in the Core
folder within the USB device library firmware package (see Figure 5). The USB class
module is the class layer built in compliance with the protocol specification.
The format and the meaning of the class-specific requests and the vendor specific requests
are not common for all USB devices.
All SETUP requests are processed with a state machine implemented in an interrupt model.
An interrupt is generated at the end of the correct USB transfer. The library code receives
this interrupt. In the interrupt process routine, the trigger endpoint is identified. If the event is
a setup on endpoint 0, the payload of the received setup is saved and the state machine
starts.
Standard requests
Most of the requests specified in Table 4 of the USB specification are handled as standard
requests in the library. Table 4 lists all the standard requests and their valid parameters in
the library. Requests that are not in Table 4 are considered as non-standard requests.
High byte of
High byte of
Low byte of
Low byte of
wLength
wValue
wValue
wIndex
wIndex
State
ype
- Comments
bmRequestT
High byte of
High byte of
Low byte of
Low byte of
wLength
wValue
wValue
wIndex
wIndex
State
ype
- Comments
Note: In column State: D = Default state; A = Address state; C = Configured state; All = All states.
EP: D0-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->pClass->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 that the
application wants to interpret as valid requests
Invalid requests are the requests that are not standard requests and are not user-
interpreted requests. Since pdev->pClass->Setup (pdev, req) is called after the SETUP
stage and before the data stage, user code is responsible, in the pdev->pClass-
>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->pClass->Setup (pdev, req)
For a user-interpreted request, the user code prepares the data buffer for the following
data stage if the request has a data stage; otherwise the user code executes the
request and returns to the caller of pdev->pClass->Setup (pdev, req).
• DATA stage
The class layer uses the standard USBD_CtlSendData and USBD_CtlPrepareRx to
send or receive data. The data transfer flow is handled internally by the library and the
user does not need to split the data in ep_size packet.
• Status stage
The status stage is handled by the library after returning from the pdev->pClass->Setup
(pdev, req) callback.
86%'B+,'
+,'B'HVF
$8',2B'HVF $SSOLFDWLRQ 86%'B$8',2
&'&B'HVF 86%'B&'&
')8B'HVF 86%'B')8
86%'B,QLW 86%'B'HYLFH 86%'B5HJLVWHU&ODVV 86%'B'HYLFH
06&B'HVF 86%'B06&
86%/LEUDU\0RGXOH 86%'HYLFH&ODVV
+$/B3&'B,54+DQGOHU KSFG
86%+$/
069
The main application executes the user defined program. main.c, stm32fxx_it.c,
usbd_conf.c and usbd_desc.c together with their header files are the main files
(mandatory for the application) that the user needs to develop his own application. The user
can modify them according to his application requirements (class driver).
Only simple APIs are called. They allows interfacing between the application layer and the
USB library module which handles the USB initialization and getting the current status of the
USB.
To initialize the USB HAL driver, the USB device library and the hardware on the used board
(BSP) and to start the library, the user application must call these three APIs:
• USBD_Init (): This function initializes the device stack and loads the class driver.
The device descriptor is stored in the usbd_desc.c and usbd_desc.h (used for the
configuration descriptor type) files:
• USBD_RegisterClass(): This function links the class driver to the device core.
• USBD_Start(): This function allows user to start the USB device core
For example the user can add additional endpoints in the usbd_conf file, depending on the
class requirement. This is done by calling USBD_LL_Init() function. The dev_endpoints
should contain the number of required endpoints following the USB class specifications.
The USB device library provides several configurations thanks to the usbd_conf.h file (for
more details refer to Section 5.1.5: Configuring the USB device firmware library on
page 23).
Note: The HAL library initialization is done through the HAL_Init() API in the stm32fxxx_hal.c This
function performs the following operation:
- Reset of all peripherals
- Configuration of Flash prefetch, Instruction cache, Data cache
- Enabling of SysTick and configuration of 1 ms tick (default clock after Reset is HSI)
XVEGBLRUHTF
XVEGBLRUHTF 8VEGBFODVVBFRUHF
8VEGBFODVVBFRUHF
86%'B6WDWXV7\SH'HI86%'B&WO6HQG'DWD
86%'B6WDWXV7\SH'HI86%'B&WO&RQWLQXH6HQG'DWD
86%'B6WDWXV7\SH'HI86%'B&WO3UHSDUH5[
86%'B6WDWXV7\SH'HI86%'B&WO&RQWLQXH5[
86%'B*HW5[&RXQW
86%'B6WDWXV7\SH'HI86%'B&WO6HQG6WDWXV
86%'B6WDWXV7\SH'HI86%'B&WO5HFHLYH6WDWXV
86%'B*HW5[&RXQW
XVEGBFRUHF
XVEGBFRUHF
+$/B3&'B(3B7UDQVPLW
+$/B3&'B(3B5HFHLYH
+$/B3&'B(3B2SHQ
+$/B3&'B(3B7UDQVPLW +$/B3&'B(3B&ORVH
+$/B3&'B(3B5HFHLYH
VWPI[[[BKDOBSFGF
VWPI[[[BKDOBSFGF
069
8VHU)LOHV
h^ĞǀŝĐĞůĂƐƐ
86%'HYLFH/LEUDU\
ƉƉůŝĐĂƚŝŽŶ +,'06&')8
h^ĞǀŝĐĞŽƌĞ $8',2
&RUH HWF
/RJGHEXJ
86%
h^ĞƐĐƌŝƉƚŽƌ
5HTXHVWV
,2
h^ƌŝǀĞƌŽŶĨŝŐƵƌĂƚŝŽŶ UHTXHVWV
86%'HYLFH+$/'ULYHU
'ULYHU
ĞǀŝĐĞŽŶƚƌŽůůĞƌƌŝǀĞƌ;Ϳ
>Žǁ>ĞǀĞůĚƌŝǀĞƌŽƌĞ
069
Table 6 shows all the device library callback functions which are called from the low level
interface following some USB events.
Note: The user can start from the usbd_conf.c file provided within STM32Cube™ package. This
file could be also copied to the application folder and modified depending on the application
needs.
By default for USB device examples, library and user messages are not displayed on the
LCD.
However the user can implement his own messages. To redirect the library messages on
the LCD screen, lcd_log.c driver must be added to the application sources. He can choose
to display them or not by modifying define values in the usbd_conf.h configuration file
available under the project includes directory. For example:
0: No Log/Debug messages
1: log messages enabled
2: log and debug messages enabled
Device suspend
When the device detects a suspend condition on the USB, the library stops all the ongoing
operations and puts the system in suspend state (if low power mode management is
enabled in the usbd_conf.c file).
Device resume
When the device detects a resume signal on the USB, the library restores the USB core
clock and puts the system in idle state (if low power mode management is enabled in the
usbd_conf.c file).
This file contains the functions for handling all USB communication
usbd_core (.c, .h)
and state machine.
This file includes the requests implementation listed in Chapter 9 of
usbd_req(.c,.h)
the specification.
usbd_ctlreq(.c,.h) This file handles the results of the USB transactions.
Template file for the low layer interface file, should be customized
usbd_conf_template(.c,.h)
by user and included with application file.
usbd_def(.c, .h) Common library defines.
The Class folder contains all the files relative to the class implementation and complies with
the specification of the protocol built in these classes.
USBD_StatusTypeDef
Initializes the device library and loads
USBD_Init(USBD_HandleTypeDef *pdev, the class driver and the user call backs.
USBD_DescriptorsTypeDef *pdesc, uint8_t id)
USBD_StatusTypeDef
De-Initializes the device library.
USBD_DeInit(USBD_HandleTypeDef *pdev)
USBD_StatusTypeDef
USBD_RegisterClass(USBD_HandleTypeDef *pdev, Loads the class driver.
USBD_ClassTypeDef *pclass)
USBD_StatusTypeDef USBD_Start
Starts the device library process.
(USBD_HandleTypeDef *pdev)
USBD_StatusTypeDef USBD_Stop Stops the device library process and
(USBD_HandleTypeDef *pdev) frees related resources.
USBD_StatusTypeDef
USBD_LL_SetupStage(USBD_HandleTypeDef *pdev, Handles setup stage from ISR.
uint8_t *psetup)
USBD_StatusTypeDef
USBD_LL_DataOutStage(USBD_HandleTypeDef *pdev , Handles data out stage from ISR.
uint8_t epnum, uint8_t *pdata)
USBD_StatusTypeDef
USBD_LL_DataInStage(USBD_HandleTypeDef *pdev Handles data IN stage.
,uint8_t epnum, uint8_t *pdata)
USBD_StatusTypeDef
Handles USB Reset from ISR.
USBD_LL_Reset(USBD_HandleTypeDef *pdev)
USBD_StatusTypeDef
USBD_LL_SetSpeed(USBD_HandleTypeDef *pdev, Sets USB Core Speed
USBD_SpeedTypeDef speed)
USBD_StatusTypeDef
Handles Suspend Event.
USBD_LL_Suspend(USBD_HandleTypeDef *pdev)
USBD_StatusTypeDef
Handles Resume event.
USBD_LL_Resume(USBD_HandleTypeDef *pdev)
USBD_StatusTypeDef
Handles Start Of Frame Event.
USBD_LL_SOF(USBD_HandleTypeDef *pdev);
USBD_StatusTypeDef
Handles Incomplete ISO IN transaction
USBD_LL_IsoINIncomplete(USBD_HandleTypeDef
Event.
*pdev, uint8_t epnum)
USBD_StatusTypeDef
Handles Incomplete ISO OUT
USBD_LL_IsoOUTIncomplete(USBD_HandleTypeDef
transaction Event.
*pdev, uint8_t epnum)
USBD_StatusTypeDef Notifies about device connection from
USBD_LL_DevConnected(USBD_HandleTypeDef *pdev) ISR.
USBD_StatusTypeDef
Notifies about device disconnection from
USBD_LL_DevDisconnected(USBD_HandleTypeDef
ISR.
*pdev)
USBD_StatusTypeDef
USBD_CtlSendData (USBD_HandleTypeDef *pdev, Sends the data on the control pipe.
uint8_t *pbuf,uint16_t len)
USBD_StatusTypeDef
Continues sending data on the control
USBD_CtlContinueSendData (USBD_HandleTypeDef pipe.
*pdev, uint8_t *pbuf, uint16_t len)
USBD_StatusTypeDef
Prepares the core to receive data on the
USBD_CtlPrepareRx (USBD_HandleTypeDef control pipe.
*pdev,uint8_t *pbuf, uint16_t len)
USBD_StatusTypeDef USBD_CtlContinueRx Continues receiving data on the control
(USBD_HandleTypeDef *pdev, uint8_t *pbuf, uint16_t len) pipe.
USBD_StatusTypeDef Sends a zero length packet on the
USBD_CtlSendStatus (USBD_HandleTypeDef *pdev) control pipe.
USBD_StatusTypeDef
Handles standard USB device
USBD_StdDevReq (USBD_HandleTypeDef *pdev, requests.
USBD_SetupReqTypedef *req)
USBD_StatusTypeDef
Handles standard USB interface
USBD_StdItfReq (USBD_HandleTypeDef *pdev, requests.
USBD_SetupReqTypedef *req)
USBD_StatusTypeDef
Handles standard USB endpoint
USBD_StdEPReq (USBD_HandleTypeDef *pdev, requests.
USBD_SetupReqTypedef *req)
static void USBD_GetDescriptor(USBD_HandleTypeDef
Handles Get Descriptor requests.
*pdev ,USBD_SetupReqTypedef *req)
static void USBD_SetAddress(USBD_HandleTypeDef
Sets new USB device address.
*pdev , USBD_SetupReqTypedef *req)
static void USBD_SetConfig(USBD_HandleTypeDef *pdev, Handles Set device configuration
USBD_SetupReqTypedef *req) request.
static void USBD_GetConfig(USBD_HandleTypeDef *pdev, Handles Get device configuration
USBD_SetupReqTypedef *req) request.
static void USBD_GetStatus(USBD_HandleTypeDef *pdev,
Handles Get Status request.
USBD_SetupReqTypedef *req)
static void USBD_SetFeature(USBD_HandleTypeDef
Handles Set device feature request.
*pdev, USBD_SetupReqTypedef *req)
static void USBD_ClrFeature(USBD_HandleTypeDef
Handles Clear device feature request.
*pdev, USBD_SetupReqTypedef *req)
void USBD_CtlError( USBD_HandleTypeDef *pdev, Handles USB Errors on the control
USBD_SetupReqTypedef *req) pipe.
void USBD_GetString(uint8_t *desc, uint8_t *unicode, Converts ASCII string into unicode
uint16_t *len) one.
static uint8_t USBD_GetLen(uint8_t *buf) Returns the string length.
void USBD_ParseSetupRequest Copies request buffer into setup
(USBD_SetupReqTypedef *req, uint8_t *pdata) structure.
● 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.
● DeInit: This callback is called when the clear configuration request has been received;
this function closes the endpoints used by the class interface.
● Setup: This callback is called to handle the specific class setup requests.
● EP0_TxSent: This callback is called when the send status is finished.
● EP0_RxSent: This callback is called when the receive status is finished.
● DataIn: This callback is called to perform 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 SOF.
● 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.
● GetHSConfigDescriptor: This callback returns the HS USB Configuration descriptor.
● GetFSConfigDescriptor: This callback returns the FS USB Configuration descriptor.
● GetOtherSpeedConfigDescriptor: This callback returns the other configuration
descriptor of the used class in High Speed mode.
● GetDeviceQualifierDescriptor: This callback returns the Device Qualifier Descriptor.
The class module contains all the files related to the class implementation. It complies with
the specification of the protocol built in these classes. Table 13 shows the USB device class
files for the MSC, HID, DFU, Audio, CDC classes.
This file contains the HID class callbacks (driver) and the
HID usbd_hid (.c, .h)
configuration descriptors relative to this class.
This file contains the MSC class callbacks (driver) and
usbd_msc( .c, .h)
the 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.
MSC
This file contains the vital inquiry pages and the sense
usbd_msc_data (.c,.h)
data of the mass storage devices.
usbd_msc_storage_template This file provides a template driver which allows you to
(.c,.h) implement additional functions for MSC.
This file contains the DFU class callbacks (driver) and
usbd_dfu (.c,.h)
the configuration descriptors relative to this class.
DFU
usbd_dfu_media_template_if This file provides a template driver which allows you to
(.c,.h) implement additional memory interfaces.
This file contains the AUDIO class callbacks (driver) and
usbd_audio (.c,.h)
the configuration descriptors relative to this class.
Audio
usbd_audio_if_template This file provides a template driver which allows you to
(.c,.h) implement additional functions for Audio.
This file contains the CDC class callbacks (driver) and
usbd_cdc (.c,.h)
the configuration descriptors relative to this class.
CDC
This file provides a template driver which allows you to
usbd_cdc_if_template (.c,.h)
implement low layer functions for a CDC terminal.
Custom This file contains the Custom HID class callbacks (driver)
usbd_customhid (.c,.h)
HID and the configuration descriptors relative to this class.
static uint8_t USBD_HID_Init Initializes the HID interface and open the used
(USBD_HandleTypeDef *pdev, uint8_t cfgidx) endpoints.
static uint8_t USBD_HID_DeInit Un-Initializes the HID layer and close the used
(USBD_HandleTypeDef *pdev, uint8_t cfgidx) endpoints.
static uint8_t USBD_HID_Setup
(USBD_HandleTypeDef *pdev, Handles the HID specific requests.
USBD_SetupReqTypedef *req)
uint8_t USBD_HID_SendReport
(USBD_HandleTypeDef *pdev, uint8_t *report, Sends HID reports.
uint16_t len)
The HID stack is initialized by calling the USBD_HID_Init(), Then the application has to
call the USBD_HID_SendReport()function to send the HID reports.
The Following HID specific requests are implemented through the endpoint 0 (Control):
#define HID_REQ_SET_PROTOCOL 0x0B
#define HID_REQ_GET_PROTOCOL 0x03
#define HID_REQ_SET_IDLE 0x0A
#define HID_REQ_GET_IDLE 0x02
#define HID_REQ_SET_REPORT 0x09
#define HID_REQ_GET_REPORT 0x01
The IN endpoint address and the maximum number of bytes that can be sent are given by
these defines:
#define HID_EPIN_ADDR 0x81
#define HID_EPIN_SIZE 0x04
A general BOT transaction is based on a simple basic state machine. It begins in ready
state (idle state). If a CBW is received from the host, three cases can be managed:
• DATA-OUT-STAGE: when the direction flag is set to “0”, the device must be prepared to
receive an amount of data indicated in cbw.dDataLength in the CBW block. At the end
of data transfer, a CSW is returned with the remaining data length and the STATUS
field.
• DATA-IN-STAGE: when direction flag is set to “1”, the device must be prepared to send
an amount of data indicated in cbw.dDataLength in the CBW block. At the end of data
transfer, a CSW is returned with the remaining data length and the STATUS field.
• ZERO DATA: in this case, no data stage is required and the CSW block is sent
immediately after the CBW one.
5HDG\
&RPPDQG7UDQVSRUW&%:
'DWD287 'DWD,1
6WDWXV7UDQVSRUW
069
SCSI_PREVENT_REMOVAL,
SCSI_START_STOP_UNIT,
SCSI_TEST_UNIT_READY,
SCSI_INQUIRY,
SCSI_READ_CAPACITY10,
READ_FORMAT_CAPACITY
SCSI SCSI_READ_FORMAT_CAPACITY,
(0x23) is an UFI command.
SCSI_MODE_SENSE6,
SCSI_MODE_SENSE10
SCSI_READ10,
SCSI_WRITE10,
SCSI_VERIFY10
As required by the BOT specification, the Bulk-only mass storage reset request (class-
specific request) is implemented. This request is used to reset the mass storage device and
its associated interface. This class-specific request should prepare the device for the next
CBW from the host.
To generate the BOT Mass Storage Reset, the host must send a device request on the
default pipe of:
• bmRequestType: Class, interface, host to device
• bRequest field set to 255 (FFh)
• wValue field set to ‘0’
• wIndex field set to the interface number
• wLength field set to ‘0’
uint8_t USBD_MSC_Init (USBD_HandleTypeDef Initializes the MSC interface and opens the used
*pdev, uint8_t cfgidx) endpoints.
uint8_t USBD_MSC_DeInit De-initializes the MSC layer and close the used
(USBD_HandleTypeDef *pdev, uint8_t cfgidx) endpoints.
uint8_t USBD_MSC_Setup
(USBD_HandleTypeDef *pdev, Handles the MSC specific requests.
USBD_SetupReqTypedef *req)
uint8_t USBD_MSC_DataIn
Handles the MSC Data In stage.
(USBD_HandleTypeDef *pdev, uint8_t epnum)
uint8_t USBD_MSC_DataOut
Handles the MSC Data Out stage.
(USBD_HandleTypeDef *pdev, uint8_t epnum)
int8_t SCSI_ProcessCmd(USBD_HandleTypeDef
Processes the SCSI commands.
*pdev, uint8_t lun, uint8_t *params)
static int8_t
Processes the SCSI Test Unit Ready
SCSI_TestUnitReady(USBD_HandleTypeDef
command.
*pdev, uint8_t lun, uint8_t *params)
static int8_t SCSI_Inquiry(USBD_HandleTypeDef
Processes the Inquiry command.
*pdev, uint8_t lun, uint8_t *params)
static int8_t
SCSI_ReadCapacity10(USBD_HandleTypeDef Processes the Read Capacity 10 command.
*pdev, uint8_t lun, uint8_t *params)
static int8_t
Processes the Read Format Capacity
SCSI_ReadFormatCapacity(USBD_HandleTypeDef
command.
*pdev, uint8_t lun, uint8_t *params)
static int8_t SCSI_ModeSense6
(USBD_HandleTypeDef *pdev, uint8_t lun, uint8_t Processes the Mode Sense 6 command.
*params)
static int8_t SCSI_ModeSense10
(USBD_HandleTypeDef *pdev, uint8_t lun, uint8_t Processes the Mode Sense 10 command.
*params)
static int8_t SCSI_RequestSense
(USBD_HandleTypeDef *pdev, uint8_t lun, uint8_t Processes the Request Sense command.
*params)
void SCSI_SenseCode
(USBD_HandleTypeDef *pdev, uint8_t lun, uint8_t Loads the last error code in the error list.
sKey, uint8_t ASC)
static int8_t SCSI_StartStopUnit
(USBD_HandleTypeDef *pdev, uint8_t lun, uint8_t Processes the Start Stop Unit command.
*params)
static int8_t SCSI_Read10
(USBD_HandleTypeDef *pdev, uint8_t lun , uint8_t Processes the Read10 command.
*params)
static int8_t SCSI_Write10
(USBD_HandleTypeDef *pdev, uint8_t lun , uint8_t Processes the Write10 command.
*params)
static int8_t SCSI_Verify10
(USBD_HandleTypeDef *pdev, uint8_t lun , uint8_t Processes the Verify10 command.
*params)
static int8_t SCSI_CheckAddressRange
(USBD_HandleTypeDef *pdev, uint8_t lun , Checks if the LBA is inside the address range.
uint32_t blk_offset , uint16_t blk_nbr)
static int8_t SCSI_ProcessRead
Handles the Burst Read process.
(USBD_HandleTypeDef *pdev, uint8_t lun)
static int8_t SCSI_ProcessWrite
Handles the Burst Write process.
(USBD_HandleTypeDef *pdev, uint8_t lun)
Note: MicroSD is the default media interface provided by the library. However you can add other
media (Flash memory....) using the template file provided in usbd_msc_storage_template.c
The storage callback for MSC class is added in the user application by calling
USBD_MSC_RegisterStorage(&USBD_Device, &USBD_DISK_fops).
The standard inquiry data are given by the user inside the STORAGE_Inquiry data array.
They should be defined as shown in Figure 15.
appIDLE 0x00
appDETACH 0x01
dfuIDLE 0x02
dfuDNLOAD-SYNC 0x03
dfuDNBUSY 0x04
dfuDNLOAD-IDLE 0x05
dfuMANIFEST-SYNC 0x06
dfuMANIFEST 0x07
dfuMANIFEST-WAIT-RESET 0x08
dfuUPLOAD-IDLE 0x09
dfuERROR 0x0A
DSS,'/( DSS'(7$&+
'HWDFK7LPHRXW
$SSOLFDWLRQ3URJUDP0RGH
')83URJUDP0RGH
$Q\6WDWXV
86%5HVHW
H[FHSW2.
6WDWH $Q\6WDWH
GIX(5525 ([FHSWRU
')8B&/567$786 86%5HVHW
3RZHU2QUHVHW
')8B$%257
')8B83/2$' 5((QXPHUDWLRQ
&RUUXSW)LUPZDUH
')8B'1/2$'
ZOHQJWK! ')8B*(767$786EORFNLQ
GIX,'/( ELW&DQ'QORDG SURJUHVV
')8B83/2$'
ELWFDQ8SORDG
GIX'1/2$'6
GIX'1%86<
GIX83/2$' <1&
,'/( ')8B83/2$'
6KRUW)UDPH ')8B*(767$786 6WDWXV3ROO7LPHRXW
%ORFNFRPSOHWH
')8B'1/2$'
Z/HQJWK!
')8B'1/2$'
Z/HQJWK
GIX0$1,)(67 GIX'1/2$'
6<1& ,'/(
6WDWXV3ROO
7LPHRXW
%LW0DQLIHVWDWLRQ7R ')8B*(767$786
OHUDQW PDQLIHVWDWLRQLQ
SURJUHVV
6WDWH
6WDWH
GIX0$1,)(67
:$,7 GIX0$1,)(67
5(6(7
6WDWXV3ROO7LPHRXW
%LW0DQLIHVWDWLRQ7ROHUD
QW
')8B*(767$7( ')8B*(767$786
069
To protect the application from spurious accesses before initialization, the initial state of the
DFU core (after startup) is dfuERROR. The host must then clear this state by sending a
DFU_CLRSTATE request before generating another request.
The DFU core manages all supported requests (see Table 21).
Each transfer to the control endpoint belong to one of the two main categories:
• 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).
• No-Data transfers: These transfers are used to send control requests from host to
device (DFU_CLRSTATUS, DFU_ABORT and DFU_DETACH).
Note: Internal Flash memory is the default memory provided by the library. However you can add
other memories using the usbd_dfu_media_template.c template file.
To use the driver:
1. Use the file usbd_conf.h, to configure:
– The number of media (memories) to be supported (define
USBD_DFU_MAX_ITF_NUM).
– The application default address (where the image code should be loaded): define
USBD_DFU_APP_DEFAULT_ADD.
2. Call USBD_DFU_Init() function to initialize all memory interfaces and DFU state
machine.
3. All control/request operations are performed through control endpoint 0, through the
functions: USBD_DFU_Setup() and USBD_DFU_EP0_TxReady(). These functions
can be used to call each memory interface callback (read/write/erase/get state...)
depending on the generated DFU requests. No user action is required for these
operations.
4. To close the communication, call the USBD_DFU_DeInit() function.
Note: When the DFU application starts, the default DFU state is DFU_STATE_ERROR. This state is
set to protect the application from spurious operations before having a correct configuration
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:
• Using DMA for data transfer between USB buffer and output device registers (I2S).
• 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.
The low layer hardware interfaces are managed through their respective driver structure:
Each audio hardware interface driver should provide a structure pointer of type
USBD_AUDIO_ItfTypeDef. The functions and constants pointed by this structure are listed
in the following sections. If a functionality is not supported by a given memory interface, the
relative field is set as NULL value.
Note: The usbd_audio_if_template (.c,.h) file provides a template driver which allows you to
implement additional functions for your Audio application
The Audio player state is managed through the following states:
they are directly copied into the audiobuffer and the write buffer (wr_ptr) is
incremented.
4. The Audio Control requests are managed by the functions USBD_AUDIO_Setup() and
USBD_AUDIO_EP0_RxReady(). These functions route the Audio Control requests to
the lower layer (i.e. usbd_audio_if.c). In the current version, only SET_CUR and
GET_CUR requests are managed and are used for mute control only.
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):
• Any class-specific aspect relative to communication classes should be managed by
user application.
• All communication classes other than PSTN are not managed.
6.5.1 Communication
The CDC core uses two endpoint/transfer types:
• 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:
The low layer hardware interfaces are managed through their respective driver structure
}USBD_CDC_ItfTypeDef;
If a function is not supported by a given memory interface, the relative field is set as NULL
value.
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_cdc.h and
usbd_cdc_interface.h files):
CDC_DATA_HS_IN_PACKET_SIZE
Size of each IN data packet. 64 512
/CDC_DATA_FS_IN_PACKET_SIZE
CDC_DATA_HS_OUT_PACKET_SI
ZE/CDC_DATA_FS_OUT_PACKET Size of each OUT data packet. 64 512
_SIZE
Total size of circular temporary
APP_TX_DATA_SIZE 2048 2048
buffer for OUT data transfer.
Total size of circular temporary
APP_RX_DATA_SIZE 2048 2048
buffer for IN data transfer.
static int8_t CDC_Itf_Receive Handles CDC data reception from USB host to
(uint8_t* pbuf, uint32_t *Len); low layer terminal (OUT transfers).
In order to accelerate data management for IN/OUT transfers, the low layer driver
(usbd_cdc_interface.c/.h) use these global variables:
directory. This template contains all the functions that should be adapted to the
application's needs and may be also used to implement any type of USB Device class.
2. Customizing the descriptors:
The descriptors retrieved by the host must be configured to describe a device
depending on the specifications for the application class devices. The following list is
not complete but gives an overview about the various descriptors that may be required:
– Standard device descriptor
– Standard configuration descriptor
– Standard interface descriptor for the Class that is implemented
– Standard endpoint descriptors for IN and OUT endpoints
3. The firmware must configure the STM32 to enable USB transfer (isochronous, Bulk,
Interrupt or Control) depending on the user application:
– In the DataIn and DataOut functions, the user can implement the internal protocol
or state machine
– 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.
– 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 EP0_RxReady could be eventually used when the application
needs to handle events occurring before the Zero Length Packets (see the DFU
example).
4. Memory allocation process: Memory is allocated to the applications using the malloc
(USBD_malloc):
– USBD_malloc(sizeof (USBD_CUSTOM_CLASS_HandleTypeDef)): this is
dynamically allocates memory for a Class structure
Reduce the heap and stack size settings (in the Linker file)
The stack is the memory area where the program stores:
• Local variables
• Return addresses
• Function arguments
• Compiler temporaries
• Interrupt contexts
If your linker configuration reserves more amounts of heap and stack than necessary for
your application, you can determine accurately the appropriate sizes.
7 Frequently-asked questions
/* LUN 0 */
0x00,
0x80,
0x02,
0x02,
(USBD_STD_INQUIRY_LENGTH - 5),
0x00,
0x00,
0x00,
'S', 'T', 'M', ' ', ' ', ' ', ' ', ' ', /* Manufacturer:
8 bytes */
'm', 'i', 'c', 'r', 'o', 'S', 'D', ' ', /* Product:
16 Bytes */
'F', 'l', 'a', 's', 'h', ' ', ' ', ' ',
'1', '.', '0' ,'0', /* Version: 4 Bytes */
/* LUN 0 */
0x00,
0x80,
0x02,
0x02,
(USBD_STD_INQUIRY_LENGTH - 5),
0x00,
0x00,
0x00,
'S', 'T', 'M', ' ', ' ', ' ', ' ', ' ', /* Manufacturer:
8 bytes */
'N', 'a', 'n', 'd', ' ', ' ', ' ', ' ', /* Product:
16 Bytes */
'F', 'l', 'a', 's', 'h', ' ', ' ', ' ',
'1', '.', '0' ,'0', /* Version: 4 Bytes */
};
3. Where endpoints address are defined?
Endpoints address are defined in the header file of the class driver. In the case of the
MSC demo case for example, the IN/OUT endpoints address are defined in the
usbd_msc.h file as below:
#define MSC_EPIN_ADDR 0x81 For Endpoint 1 IN
#define MSC_EPOUT_ADDR 0x01 For Endpoint 1 OUT
4. Can the USB device library be configured to run in either High Speed or Full
Speed mode?
Yes, the library can handle the USB OTG HS and USB OTG FS core, if the USB OTG
FS core can only work in Full Speed mode, the USB OTG HS can work in High or Full
Speed mode.
To select the appropriate USB Core to work with, user must add the following macro
defines within the compiler preprocessor (already done in the preconfigured projects
provided with the examples):
- "USE_USB_HS" when using USB High Speed (HS) Core
- "USE_USB_FS" when using USB Full Speed (FS) Core
- "USE_USB_HS" and "USE_USB_HS_IN_FS" when using USB High Speed (HS)
Core in FS mode
5. How can the used endpoints be changed in the USB device class driver?
To change the endpoints or to add a new endpoint:
a) Perform the endpoint initialization using USBD_LL_OpenEP().
b) Configure the TX or the Rx FIFO size of the new defined endpoints in the
usb_conf.c file using these APIs in the USBD_LL_Init() function
– For STM32F2 and STM32F4 Series (FS and HS cores):
HAL_PCD_SetRxFiFo()
HAL_PCD_SetTxFiFo()
The total size of the Rx and Tx FIFOs should be lower than the total FIFO size of the
used core, that is 320 x 32 bits (1.25 Kbytes) for USB OTG FS core and 1024 x 32 bits
(4 Kbytes) for the USB OTG HS core.
– For STM32F0, STM32L0, STM32F1 and STM32F3 Series (FS core only):
HAL_PCD_PMA_Config()
6. Is the USB device library compatible with Real Time operating system (RTOS)?
Yes, The USB device library could be used with RTOS, the CMSIS RTOS wrapper is
used to make abstraction with OS kernel.
8 Revision history
STMicroelectronics NV and its subsidiaries (“ST”) reserve the right to make changes, corrections, enhancements, modifications, and
improvements to ST products and/or to this document at any time without notice. Purchasers should obtain the latest relevant information on
ST products before placing orders. ST products are sold pursuant to ST’s terms and conditions of sale in place at the time of order
acknowledgement.
Purchasers are solely responsible for the choice, selection, and use of ST products and ST assumes no liability for application assistance or
the design of Purchasers’ products.
Resale of ST products with provisions different from the information set forth herein shall void any warranty granted by ST for such product.
ST and the ST logo are trademarks of ST. All other product or service names are the property of their respective owners.
Information in this document supersedes and replaces information previously supplied in any prior versions of this document.