Introduction to USB with STM32

Revision as of 17:43, 2 August 2020 by Registered User (→‎USB Device Library Overview)
Under construction.png Coming soon

On this article, you will find application examples, document references, tips and tricks and so on related to STM32 USB

1. What is the Universal Serial Bus (USB)

The large diversity of ports (parallel, serial, midi, joystick, etc) with their specific requirements and the lack of plug-and-play feature were almost the main reasons that pushed the most known companies in the technology domain to seek for a substitution. These companies developed the USB standard and formed the USB Implementers Forum.
The USB provided the most successful serial interface having the following characteristics:

  • simplicity and flexibility (plug-and-play)
  • bi-directionality
  • increasing speeds
  • low cost

Since developed, the USB has been continuously ameliorated always keeping compatibility with the new technologies evolution and requirements.
The STM32 USB hardware and software are compliant with USB1.1 and USB2.0 specifications and all the following sections will speak about these standard devices.
This section focuses on the USB2.0 standard and provides a general overview about the rich characteristics of this standard.

1.1. Speed

The USB2.0 supports three speeds:

  • Low speed (LS): supports the transfer rate of 1.5 Mb/s. This speed is mainly dedicated to interactive devices (mouse, keyboard, etc)
  • Full speed (FS): supports the transfer rate of 12 Mb/s. This speed is mainly dedicated to phone and audio devices (microphone, speaker, etc)
  • High speed (HS): supports the transfer rate of 480 Mb/s. This speed is mainly dedicated to video and storage devices (printer, camera, etc)

At protocol level, the USB grants a very high compatibility, so users can not see big differences between dealing with different speeds

1.2. USB interconnect components

The USB interconnect has three main components:

  • Host or Root Hub: it is unique for every USB system. It is responsible of initiating all transactions.
  • Function or Device: the final point in the interconnect ensuring the user's required roles (keyboard, mouse, microphone, etc)
  • Hub: a bridge ensuring the communication between the host and many devices. It has one upstream port to be connected directly (point to point connection through USB cable) or indirectly (connection through another hub) to the host and many downstream ports to be connected directly or indirectly to the USB Functions.

The previous components can be connected to each other through USB cables with a maximum length of 5 meters.
The maximum number of hubs connected in series allowed by the USB specification is 5. Thus, a function or device can be connected to the host through one or more hub(s).
In every USB system, there is a host that can communicate with up to 127 devices and hubs. The following figure provides an example of USB system components connection.

File:typical USB system topology.png
USB system topology example

1.3. USB interconnect topology

The USB physical interconnect is characterized by a tired star topology. Each star has a hub at the center with one upstream connection directly or indirectly with the host and one or more downstream connection(s) with function or other hub.
A maximum of 127 devices (functions or hubs) can be connected to one host (root hub) with a maximum of 5 hubs connected in series.

1.4. Power

Generally, the host (root hub) provides power for functions direct connection. Some hubs may supply power for directly connected downstream functions. For the functions, there are two types:

  • Bus powered functions: these devices rely totally on the bus power coming from the upstream hub.
  • Self powered functions: these devices are capable of providing their own power independently from the bus.

1.5. System configuration

The USB system has an intelligent mechanism to detect the device attachment and detachment at any time.

  • Device attachment: the host can detect at any time the detachment of a device by continuously querying a bit for all the connected hub ports. Once a device is attached, the host enables the port and gives the device a unique address then establish a communication with this newly connected device to conclude if it is a function or a hub.
  • Device detachment: once a device is detached, the corresponding port will be disabled. If a hub is detached, all the downstream devices' ports that were attached to the removed hub will be disabled and the detached hub's upstream port will be disabled.
  • Bus enumeration: it is a set of hardware and software events allowing the host to continuously detect and address and recognize the newly connected device. It includes also the set of events ensuring the removal of a device.

1.6. Class

Depending on the required USB device functionality and application, the device and the host features very. The USB IF defines a variety of classes ensuring the classification according to the required functionality. Every class defines an association of:

  • Data including characteristics that must be stored within the device and given to the host when requested
  • Software drivers stored within the host and loaded after negotiation with the device and after discovery of its characteristics.

An overview of all the defined USB classes and codes is provided by the USB IF at this link.

1.7. USB Data transfers

USB communication is based on four main transfer types:

  • Control transfer: mainly used for the configuration data of the newly attached device.
  • Bulk transfer: used for large amounts of data transmission or reception.
  • Interrupt transfer: used for limited data transmission with minimal latency.
  • Isochronous transfer: used for data transfer with real-time requirements.

More detailed explanations of the USB characteristics and data flow will be explained with code examples in the following pages.

1.8. Data direction

As it was outlined in the previous section, the USB supports only 4 transfer types. For all the transfers, it is always the host who initiates the communication with the device. In fact, the USB can transfer data in two directions where the reference is always the host:

  • data out is the data that will be transferred from the host to the device
  • data in is the data that will be transferred from the device into the host

1.9. Transactions

Each transfer independently from its type is based on one or more transaction to ensure the information exchange between a host and a device. Each transaction itself consists of up to three phases or packets:

  • Token: it is always required to start every transaction. It is USB packet sent from the host to the device providing some information about the transaction (type, destination, data phase direction, etc.)
  • Data: this phase is optional. Its existence, direction and size are indicated within the token packet. During this phase, the source of data will send the specified data if it exists.
  • Handshake: this phase is optional. Its existence and direction can be inferred from the token packet. In fact, depending on the direction of data specified in the token packet, the data destination will send this packet to acknowledge the data reception status.

1.10. Requests

As mentioned previously, the host always initiates the communication with the device by sending request. All USB requests have common fields. Each field size, value and signification is known by the device and the host. It is always the host who is responsible of filling a request fields and sending it and, on the other side, the device receives the request and decodes it to be prepared for the next communication phase.

1.11. Descriptor

It is a set of data blocks stocked within the device and organized in a defined manner known by the device and the host. Some descriptors are required for all the devices and the host cannot continue the communication with any device missing a required descriptor. Some descriptors are optional and can differ from a device to another depending on its functionalities. Every descriptor includes some information about the device and will be send to the host as answer to a defined request.

1.12. Endpoint

It is a source or destination data buffer that must be implemented on the device side. Each amount of data that will be received from or sent to the host will be placed into an endpoint. Each endpoint is uniquely characterized by a number and direction which means that for a given number, there is a unique pair of endpoints of the same type and number but each one deals with the data of only one direction:

  • Endpoint in for data that will be transferred into the host.
  • Endpoint out for data that will be transferred from the host.

A device has always more than one endpoint identified by their numbers:

  • Endpoint zero: it is a pair of out and in endpoints dedicated for control data transfers which means it is a control endpoint. It is required to establish the first communication transfers between the host and the device while the other endpoints are not yet configured.
  • Other endpoints: will be configured after negotiation between the host and the device. Each endpoint is independent from the other and can handle a different transfer type.

1.13. Address

A unique value assigned by the host and it varies from 1 to 127. Address 0 is always given to the newly attached device before being addressed by the host.

1.14. Enumeration

It is the procedure ensuring the control of the device status changes and the real time management of any device attachment and detachment. During this step, there is a combination of hardware and software negotiation allowing the host to decode the device nature. At device software level, this procedure ensures the correct reception and decoding of the host request and then device state modification accordingly.

1.15. Device status

From being completely detached until being completely recognized by the USB Host and ensuring its function, the USB device goes through consecutive stages:

  • Attached: it is the stage when the device is physically connected to the USB host but not yet powered. This stage is transparent at the device software level.
  • Powered: it is the second stage and is corresponding to a device that was attached to USB Host and just powered. This stage is transparent at the device software level.
  • Default: this stage is reached when the attached device has been powered then reset by the host. This stage is assigned to the device by its software each time the device is newly attached then powered then reset or an old attached device received a reset. At this stage, The USB Device operates with convenient speed (selected by hardware during reset) and has the default address which is the address number 0.
  • Addressed: after going through all the previous stages, the USB device reaches this state by receiving its unique address (different from 0) from the host. This stage is reached after correct process of the host request by the device software.
  • Configured: the device reaches this stage after receiving the convenient request from the host with a non-zero configuration number. This stage is reached after correct process of the host request by the device software.
  • Suspended: the device must enter this stage if there is no data on the traffic for a known period that depends on the speed. In fact, the host forces the device to enter this state electrically depending on the speed. When detecting this electrical indication, the USB device software must change its state into suspended.

2. Getting started with STM32 and USB

This section provides answers that can be asked when starting the use of the STM32 MCU's USB.

2.1. What does the STM32 support?

All the STM32 families (not all products) include the USB IP. Depending on the hardware, each STM32 MCU including the USB can support:

  • Device in FS speed only.
  • OTG ( dual role: device and host) in FS speed.
  • OTG in HS speed.

Some STM32 MCUs include two USB peripherals and support both OTG in FS and HS speeds.
An overview of the USB hardware over the STM32 MCUs will be provided in the next pages.

2.2. What role can the STM32 MCU play within a USB system?

A basic USB system can be established by a host and a device attached with a USB cable. The following figure shows the possible roles that can keep the STM32 MCU's USB:

STM32 USB role within a basic USB system

For more complex USB system, the device can be attached to the host through one or more hub(s). For such system, currently, the STM32 USB can play the role of the device as shown in the figure below.

STM32 USB role within a complex USB system

2.3. How can I select one STM32 MCU for my USB application?

For every USB application, it is important to select the correct STM32 with required USB role (Host or Device) and speed (LS or FS or HS). But there are many STM32 MCUs having the same USB hardware implementation, how to choose? Besides the USB features, the STM32 MCUs offer a large set of peripherals with large features portfolio. The diversity of peripherals and features guarantees the flexibility and ease of the required application's implementation. In fact, the convenient MCU selection is one of the most secrets of a successful USB application.
To select the convenient MCU, the following features must be taken into consideration depending on the application requirements:

  • The MCU performance have a direct impact on data transfer and processing in the STM32 system.
  • The memories (RAM and ROM) availability and sizes are very important for applications processing large amounts of data.
  • the required peripherals availability and features must be checked when selecting the STM32 MCU because peripherals versions and combinations can largely differ from one MCU to another.
  • The power consumption is a very important requirement for some applications

The STM32 compliant with USB section provides an overview of all the STM32 MCUs including USB, it also includes some of the most important features for USB applications requirements.

2.4. Where can I find more detailed information about the USB for the selected STM32 MCU?

For every STM32 MCU, there is a set of documents providing information about all the integrated peripherals and among others the USB. All the STM32 MCUs have a page providing a generic overview with a direct link to the MCU's datasheet. In fact, all the STM32 MCU's USB peripheral information are integrated mainly in the datasheet (specially the electrical characterization) and the reference manual (includes all the MCU's peripherals information thus it provides a detailed information about the integrated USB peripheral(s)).
All the STM32 MCUs technical documents can be found using this link.

2.5. Is there any provided STM32 USB code examples?

Every STM32 Family has a package that includes the MCU's drivers and peripherals examples called the STM32Cube Firmware package. This package includes the USB Device and Host (if supported by the MCU) drivers and code examples for all the supported speeds.
To access the USB code, the STM32Cube Firmware package must be installed. When opening the installed folder, the following steps must be followed:

  • Open "Projects" sub-folder.
  • Open the folder having the name of the convenient board including the selected MCU.
  • Open "Applications" sub-folder
  • Select the USB convenient sub-folder ("USB_Device" for device applications and USB_Host for host applications if supported by the MCU)
  • Select the convenient application
  • Select the convenient IDE (IAR, STM32CubeIDE, KEIL)

At this level, the application's code can be debugged and can be loaded into the STM32 t check the results as mentioned in the readme.txt file which is provided within the application sub-folder. All the STM32 MCUs tools and software can be accessed using this link.
A detailed explanation of all the STM32 USB code parts will be explained in the following pages.

3. Video related to STM32 USB

Special STM32 USB training videos were published to facilitate the understanding of the USB concepts and the STM32 USB supported features. It provides also an explanation of the STM32 USB host and device provided libraries. These videos cover many Hardware and Software concepts that target different USB knowledge levels.

pc videol.png

MOOC - STM32 USB training

In the following pages, some parts of the videos will be explained in more details with some code examples extracted from the STM32Cube firmware.

4. STM32 compliant with USB

The following table provides an overview about the USB hardware implementation through STM32 series. Some part numbers may not include same USB hardware compared to other part numbers in the same family include as shown in the table below:

STM32 series USB Device only USB OTG FS USB OTG HS USB OTG FS&HS
STM32F0
STM32F1
STM32F2
STM32F3
STM32F4
STM32F7
STM32G4
STM32H7
STM32L0
STM32L1
STM32L4
STM32L4+
STM32L5
STM32WB


More detailed information about every STM32 MCU and Board features and peripherals can be found using the ST-MCU-FINDER.

5. USB Device Library Overview

With the STM32 MCUs and boards, a full and free development environment called the STM32Cube is offered including two main parts:

  • Graphical software tools.
  • Embedded software packages (STM32Cube firmware).

More details about the STM32Cube offer can be found here. Each STM32Cube firmware provides full set of drivers and examples ensuring the ease of use of the different peripherals supported by one stm32 MCUs Family. The STM32Cube firmware covers the different levels by offering:

  • Low layer and optimized drivers.
  • Hardware abstraction layer and portable drivers.
  • Middleware libraries.
  • Examples and applications.

As almost of middleware components, the STM32 USB device offer is based mainly on STMicroelectronics Device library but also on some low and hardware abstraction layers drivers besides many applications.

5.1. USB Device library folders architecture within STM32Cube firmware

Within every STM32Cube firmware package, there is “Middlewares” folder including all ST and third party’s middleware libraries. The STM32 USB device library is part of the “Middlewares/ST” offer. The “STM32_USB_Device_Library” includes the “Core” module for the USB device standard peripheral control APIs and “Classes” model for the commonly supported classes APIs. The following figures shows the folders structure of the STM32 USB device library.

File:STM32 Device Library Folders Architecture.png
USB Device library folders architecture

5.2. USB Device Applications folders architecture within STM32Cube firmware

Within every STM32Cube firmware package, a dedicated folder for applications is offered including a list of all the middlewares that are supported by the selected STM32 board and, among others, the USB device Applications will be found. These applications code can be run, debugged, and tested directly on the convenient STM32 by following the steps described in the readme.txt provided within every application’s folder. Generally, to guarantee more flexibility, every application is offered with the support of three IDEs. The following figure shows an example of USB Device applications supported by one STM32 board. The applications number differs from one STM32 Board to another.

File:STM32 Device Applications Folders Architecture.png
STM32 Device Applications Folders Architecture.png

5.3. STM32 USB Device Library description

As mentioned previously, the STM32 USB Device Library includes the Core and the Classes folders.

5.3.1. Core

this folder includes the files ensuring USB 2.0 standard code implementation. These files’ APIs will be called within every USB device application regardless of the desired functionality. It includes five main modules that are:

  • usbd_core (.c, .h): this file includes all the functions ensuring the control of the USB core state machine and the different events processing.
Function Description
USBD_Init Initializes the Device Handler and state machine
USBD_DeInit De-initializes the Device Handler
USBD_RegisterClass Links the device handler to the class handler
USBD_Start Starts the device core
USBD_Stop Stops the device core and class
USBD_SetClassConfig Initializes the device’s class with the input configuration
USBD_ClrClassConfig Clears a device’s class configuration
USBD_LL_SetupStage Handles the setup stage requests
USBD_LL_DataOutStage Handles the data reception from the host on the convenient endpoint
USBD_LL_DataInStage Handles the data sending to the host on the convenient endpoint
USBD_LL_Reset Reinitializes the Device’s handler
USBD_LL_SetSpeed Sets the device’s speed
USBD_LL_Suspend Modifies the device status into suspended
USBD_LL_Resume Resumes the device old status before being suspended
USBD_LL_SOF Handles the Start Of Frame event
USBD_LL_IsoINIncomplete Handles the Iso In Incomplete event
USBD_LL_IsoOUTIncomplete Handles the Iso Out Incomplete event
USBD_LL_DevConnected Handles the Device connected event
USBD_LL_DevDisconnected Handles the Device disconnected event


6. Specific tools

Links and explanations for the tech domain dedicated tools

7. STMicroelectronics Resources

The place for AN, UM... direct links

8. Examples

The area where FAE's, collab... can put examples (linked to Github)




[[Category:]]