Composite Device Solution

Overview

The USB Composite Device specification defines the device architecture and enumeration standards for carrying multiple independent function classes (such as Audio, HID, Storage, Serial, etc.) through a single physical USB interface.

Based on the USB specification officially released by the USB-IF, Ameba implements a flexible composite device functional framework. It supports aggregating multiple functional interfaces via Interface Descriptors or Interface Association Descriptors (IAD), providing capabilities for parallel enumeration, independent driver loading, and collaborative operation of multiple logical devices on the host side.

../../../_images/usb_device_composite_overview.svg

Features

  • Supports the following function combinations:

    • CDC ACM + HID

    • CDC ACM + MSC

    • CDC ACM + UAC

    • HID + UAC

  • Supports USB hot-plug

  • Supports fully customizable descriptors

  • Supports configuration of parameters such as transfer buffer size and speed mode

Application Scenarios

As a USB composite device, Ameba can simultaneously enumerate multiple device classes through a single USB physical interface, enabling parallel processing of data transmission and control interaction. It is suitable for a wide range of complex application scenarios. For example,

  • USB Audio Device with Remote Control (UAC + HID): Ameba provides USB audio input/output functionality (UAC) while utilizing the HID interface for media control. Users can enjoy a high-quality audio streaming experience (such as listening to music through headphones or recording with a microphone), and also interact with features like volume adjustment, muting, song switching, or RGB lighting effects control through the HID channel.

  • Smart Industry and 3D Printing Control (MSC + CDC ACM): Ameba combines the MSC high-capacity storage and CDC virtual serial port functions. In 3D printer or data logger scenarios, the MSC interface can be simulated as a USB flash drive for storing G-code slicing files or sensor historical data, while the CDC interface simultaneously serves as a console for the host computer to send AT commands in real time, monitor temperature, or calibrate parameters.

  • Automated Testing and Assistive Input (HID Mouse + CDC ACM): Ameba combines the HID mouse and CDC serial port functions. In this scenario, the CDC interface is responsible for receiving raw data (such as coordinate instructions, head tracking data) from backend scripts or sensors, while the HID interface simulates cursor movement and click actions based on these instructions. It is widely used in hardware automated testing tools or assistive input devices for the disabled.

Protocol Introduction

The USB Composite Device specification defines a device architecture capable of supporting multiple independent function interfaces via a single physical interface within the USB framework.

This mechanism enables the host to identify and enumerate a single physical device as a collection of logical functions, facilitating parallel processing and independent control across different device classes (e.g., HID, MSC, CDC).

Common implementations include wireless keyboard/mouse receivers, USB headsets with integrated audio cards, and industrial devices combining storage and debugging capabilities.

Descriptor Structure

While adhering to standard USB descriptors (Device and Configuration Descriptors), composite devices define multi-functionality by aggregating multiple Interface Descriptors within the Configuration Descriptor set.

Single-Interface Function Class

When a single interface represents a standalone function, the composite device simply aggregates these functional classes. Typical examples of single-interface function classes include HID and MSC.

Taking a HID Keyboard + HID Mouse composite device as an example, the descriptor topology is illustrated below:

Device Descriptor
|  bDeviceClass: 0xEF (Miscellaneous)
|  bDeviceSubClass: 0x02 (Common Class)
|  bDeviceProtocol: 0x01 (Interface Association Descriptor)
│
└── Configuration Descriptor
   |   bNumInterfaces: 2  (2 Interfaces)
   │   ...
   ├── Interface Descriptor 0 (HID Keyboard)
   │   bInterfaceNumber: 0
   │   bInterfaceClass: 0x03 (HID)
   │   bInterfaceSubClass: 0x01 (Boot Interface)
   │   bInterfaceProtocol: 0x01 (Keyboard)
   │
   └── Interface Descriptor 1 (HID Mouse)
       bInterfaceNumber: 1
       bInterfaceClass: 0x03 (HID)
       bInterfaceSubClass: 0x01 (Boot Interface)
       bInterfaceProtocol: 0x02 (Mouse)

HID Keyboard + HID Mouse composite device compared to individual keyboard/mouse devices, with descriptor characteristics as follows:

Descriptor Level

Single Function Device

Composite Device

Device Descriptor

bDeviceClass defines the type

bDeviceClass is typically 0xEF (Misc) or 0x00 (Defined by Interface)

Configuration Descriptor

1 Configuration

1 Configuration

Interface Descriptor

1 Interface

2 (or more) Interfaces

Endpoint Descriptor

Belong to the single interface

Each interface has independent endpoints

Note

bDeviceClass = 0xEF: This is a standard flag for composite devices, which triggers the host driver to parse the IAD (optional) and multiple interface descriptors in the configuration descriptor, decompose different device functions, and create these logical sub-devices. Then load the keyboard driver for Interface 0 and the mouse driver for Interface 1.

Multi-Interface Function Class

If a logical function requires the use of multiple interfaces to complete, the Interface Association Descriptor (IAD) must be included when using this type of function to associate these interfaces.

Typical multi-interface functional class

  • CDC (Communication Device Class): Typically requires 1 Control Interface (CCI) + 1 Data Interface (DCI).

  • UVC (USB Video Class): Requires 1 Video Control Interface (VC) + 1 or more Video Streaming Interfaces (VS).

  • UAC (USB Audio Class): Requires 1 Audio Control Interface (AC) + 1 or more Audio Stream Interfaces (AS).

Interface Association Descriptor (IAD)

IAD declares to the host that a set of consecutive interfaces that follow closely belong to the same function and should be loaded and managed by the same driver. Without IAD, the host sometimes recognizes them as two separate devices, or the driver fails to load.

Interface Association Descriptor (IAD)
├── bLength                 : 1 byte  → 0x08 (Fixed Length)
├── bDescriptorType         : 1 byte  → 0x0B (IAD type code)
├── bFirstInterface         : 1 byte  → First Interface Number
├── bInterfaceCount         : 1 bytes → Count of associated interfaces
├── bFunctionClass          : 1 byte  → Function Class Code
├── bFunctionSubClass       : 1 byte  → Function SubClass Code
├── bFunctionProtocol       : 1 byte  → Function Protocol Code
└── iFunction               : 1 byte  → Function String Descriptor Index

IAD Usage Example

../../../_images/usb_iad_descriptor.svg
  • Function 1: Class utilize two interfaces. In order for the host to recognize them as a single logical function, it is necessary to use IAD to associate these two interfaces.

  • Function 2: Class utilize a separate interface, eliminating the need for IAD association.

Class-specific request

The USB protocol specification does not define a specific “composite class request”. Their core logic lies in precisely directing Class-Specific Requests to the designated interface through the addressing mechanism in USB standard requests.

In the bmRequestType field of the SETUP packet, the lower 5 bits (Bits 0..4) represent the Recipient.

  • General single-function device: Control requests are typically sent to the “entire device”, meaning the Recipient is set to Device (00000).

  • Composite device: A large number of control requests must be precisely sent to a “specific interface”, which means setting the Recipient to Interface (00001).

The following are the most notable key points regarding the handling of control requests by composite devices:

Field

Value

Meaning

Implementation in Composite Devices

bmRequestType

0x21 / 0xA1

Class Request, Recipient=Interface

Most common scenario. Examples include setting CDC baud rates or controlling HID keyboard LEDs.

wIndex

Interface Number

Interface Number

When the Recipient is Interface, wIndex must specify the target interface index (e.g., 0, 1, 2). The driver routes the request to the corresponding function driver based on this value.

Class Driver

This section provides a detailed analysis of how to design and implement a USB composite device class driver. The composite class driver acts as a “parent class,” responsible for managing resource scheduling, request dispatching, and data processing for multiple “child classes” (such as CDC ACM, HID, MSC, etc.).

Descriptor Structure

To allow the host to correctly identify the composite device and the multiple functions it contains, the driver must dynamically assemble a complete and precise set of descriptors at runtime. The following points must be noted when generating device descriptors:

  • Device Descriptor

    bDeviceClass: Usually set to 0xEF (Miscellaneous) or 0x00 (defined by the interface).

  • Configuration Descriptor

    This is a dynamically generated “aggregate” that contains the descriptors for all sub-functions.

    • bNumInterfaces: Must be the sum of the number of interfaces for all sub-functions. For example, for a composite device consisting of a CDC function (occupying 2 interfaces) and an MSC function (occupying 1 interface), this value should be 3.

    • wTotalLength: Must be the sum of the lengths of all descriptors (Configuration, IAD, Interface, Endpoint). This value needs to be calculated precisely at runtime.

    • Interface Association Descriptor (IAD): If a sub-function contains multiple interfaces (e.g., CDC ACM), an IAD must be used to “bundle” these interfaces together, declaring that they belong to the same function.

  • Endpoint Descriptor

    The configuration of endpoints must be tailored to the hardware capabilities of the chip. Please refer to Hardware Configuration for details.

    • Endpoint selection: Available endpoints must be selected based on functional requirements (IN/OUT) and hardware support.

    • Maximum Packet Size (MPS): Hardware limitations need to be considered. Especially when using a dedicated transmit buffer, it is important to ensure that the size of the transmit buffer area of the IN endpoint can accommodate at least one maximum packet.

CDC ACM + MSC Example

The following section illustrates the descriptor topology of the CDC ACM + MSC composite device. These structures correspond to the standard descriptor definitions in the USB protocol specifications.

  • CDC ACM (Virtual Serial Port): Occupies two interfaces. To ensure the host recognizes them as a single logical function, an IAD (Interface Association Descriptor) must be used to associate these two interfaces.

  • MSC (Mass Storage): Operates as an independent interface and does not require IAD association.

The composite device (CDC ACM + MSC) solution utilizes 5 non-zero endpoints (excluding the default control endpoint EP0).

Interface number

Interface Class

Endpoints

Description

Interface 0

CDC Control (ACM)

1x Interrupt IN

Used to notify Serial State and management commands.

Interface 1

CDC Data

1x Bulk OUT, 1x Bulk IN

Responsible for sending (OUT) and receiving (IN) virtual serial port data.

Interface 2

MSC (Mass Storage)

1x Bulk OUT, 1x Bulk IN

Responsible for data read/write of the mass storage device (SCSI commands/data).

In the class driver, various descriptors are generally defined as arrays. When obtaining configuration descriptors, the callback function get_descriptor of each sub-function class driver is called sequentially to aggregate them together.

/* USB Standard Device Descriptor */
static const u8 usbd_composite_dev_desc[USB_LEN_DEV_DESC] = {
   //...
   0xEF,       /* bDeviceClass: Miscellaneous */
   0x02,       /* bDeviceSubClass: Common Class */
   0x01,       /* bDeviceProtocol: Interface Association Descriptor */
   //...
};

The configuration descriptor is not a fixed array. The framework builds it at enumeration time from the descriptors of every registered sub-function, directly into the EP0 control transfer buffer:

configuration descriptor
├── configuration header      (bNumInterfaces, wTotalLength filled in here)
├── sub-function 1            <-- contributed by the first usbd_composite_xxx_init()
│   ├── IAD (if multi-interface)
│   ├── interface descriptor(s)
│   └── endpoint descriptors
├── sub-function 2            <-- contributed by the next one
└── ...

Three consequences follow from that design:

  • wTotalLength and bNumInterfaces are computed, not written by hand.

  • The order of the usbd_composite_xxx_init() calls decides the interface numbering the host sees.

  • The assembled descriptor cannot be truncated. usbd_config_t’s ctrl_xfer_buf_len shall therefore cover its total length at every supported speed; if it does not, enumeration fails rather than producing a short descriptor.

A sub-function that owns several interfaces (CDC ECM, for example) contributes an Interface Association Descriptor so the host groups them as one function, and the framework counts its interfaces for bNumInterfaces.

The complete topology structure of the device descriptor is as follows:

Device Descriptor
|  bDeviceClass: 0xEF (Miscellaneous)
|  bDeviceSubClass: 0x02 (Common Class)
|  bDeviceProtocol: 0x01 (Interface Association Descriptor)
|
└── Configuration descriptor
    |   bNumInterfaces: 3 (3 Interfaces)
    |
    |   /* Function 1: CDC ACM */
    |
    ├── Interface Association Descriptor (IAD)
    |    bFirstInterface: 0
    |    bInterfaceCount: 2 (Associate Interface 0 with Interface 1)
    |    bFunctionClass:  0x02 (CDC Control)
    |    bFunctionSubClass: 0x02 (ACM)
    |
    ├── Interface Descriptor 0 (CDC Control Interface)
    |   |  bInterfaceNumber: 0
    |   |  bInterfaceClass:  0x02 (CDC Control)
    |   |  bInterfaceSubClass: 0x02 (ACM)
    |   |  ...
    |   ├── CDC Class Specific Descriptors (Header, Call Mgmt, ACM...)
    |   └── Endpoint Descriptor (Interrupt IN)
    |
    ├── Interface Descriptor 1 (CDC Data Interface)
    |   |  bInterfaceNumber: 1
    |   |  bInterfaceClass:  0x0A (CDC Data)
    |   |  ...
    |   ├── Endpoint Descriptor (Bulk OUT)
    |   └── Endpoint Descriptor (Bulk IN)
    |
    |   /* Function 2: MSC */
    |
    └── Interface Descriptor 2 (MSC Interface)
        |  bInterfaceNumber: 2
        |  bInterfaceClass:  0x08 (Mass Storage)
        |  bInterfaceSubClass: 0x06 (SCSI Transparent Command Set)
        |  bInterfaceProtocol: 0x50 (Bulk-Only Transport / BBB)
        |   ...
        ├── Endpoint Descriptor (Bulk OUT)
        └── Endpoint Descriptor (Bulk IN)

Note

Composite Class Driver Implementation

The composite device is assembled from two parts: the sub-function class drivers, which are ordinary class drivers, and a small framework in usbd_composite.c that owns the descriptor assembly and event dispatch. An application does not write a composite class driver.

  • Sub-function Class Driver

    Each sub-function (such as CDC, MSC, HID) is an independent class driver; refer to the corresponding chapters of the sub-function solutions for details.

    • Independent driver structure: Each sub-driver defines a standard usbd_class_driver_t structure implementing its own process logic.

    • Independent resource management: Each sub-driver manages its own endpoints, data buffers, and transfer handling.

    • Composite awareness: besides the standalone usbd_xxx_init(), every class exposes a usbd_composite_xxx_init() variant. That variant builds the class configuration from the caller’s class configuration structure (usbd_cdc_acm_config_t, usbd_msc_config_t, …) and registers the class driver with the composite framework through usbd_composite_register_driver().

  • Composite Framework

    The framework, not the application, owns the composite-level usbd_class_driver_t. It registers as the single class driver with the USB core and dispatches to the sub-functions:

    • get_descriptor — assembles the configuration descriptor from every registered sub-function, directly in the EP0 control transfer buffer.

    • set_config / clear_config — initializes and releases the endpoints and resources of every sub-function.

    • setup, ep0_data_out, ep0_data_in, ep_data_in, ep_data_out — route a request or transfer to the sub-function that owns the addressed interface or endpoint.

    • sof / status_changed — forwarded to every sub-function.

    The number of sub-functions is bounded by USBD_COMP_MAX_FUNCS (4).

  • Composite Device State

    The framework keeps one internal usbd_composite_dev_t instance holding the registered driver array, the interface counts parsed from the descriptor, and the in-flight request state. The application never touches it; it only supplies the optional usbd_composite_cb_t (currently a single status_changed callback) to usbd_composite_init().

CDC ACM + MSC Example

The following section uses CDC ACM + MSC as an example to detail how an application assembles a composite device.

/*
 * The composite framework owns the composite-level class driver. The
 * sub-function drivers are registered into it, one per class, and the
 * framework dispatches descriptor assembly, endpoint setup and every
 * transfer to the sub-function that owns the interface or endpoint.
 */

/********************** Function 1: CDC ACM class *********************/
static const usbd_cdc_acm_config_t cdc_acm_class_cfg = {
   .bulk_in_addr       = COMP_CDC_BULK_IN_EP,
   .bulk_out_addr      = COMP_CDC_BULK_OUT_EP,
   .intr_in_addr       = COMP_CDC_INTR_IN_EP,
   .bulk_in_xfer_size  = CDC_BULK_IN_XFER_SIZE,
   .bulk_out_xfer_size = CDC_BULK_OUT_XFER_SIZE,
   .notify_en          = 1,
};

static const usbd_cdc_acm_cb_t composite_cdc_acm_usr_cb = {
   .init     = composite_cdc_acm_cb_init,
   .deinit   = composite_cdc_acm_cb_deinit,
   .setup    = composite_cdc_acm_cb_setup,
   .received = composite_cdc_acm_cb_received,
};

/********************** Function 2: MSC class *********************/
static const usbd_msc_config_t msc_class_cfg = {
   .bulk_in_addr  = COMP_MSC_BULK_IN_EP,
   .bulk_out_addr = COMP_MSC_BULK_OUT_EP,
};

static const usbd_msc_cb_t composite_msc_usr_cb = {
   .status_changed = NULL,
};

/********************** Register both sub-functions *********************/
/*
 * Each usbd_composite_xxx_init() registers its class driver with the
 * composite framework via usbd_composite_register_driver(), so there is no
 * composite class driver to write by hand.
 */
ret = usbd_composite_cdc_acm_init(&composite_cdc_acm_usr_cb, &cdc_acm_class_cfg);
if (ret != RTK_SUCCESS) {
   RTK_LOGS(TAG, RTK_LOG_ERROR, "CDC ACM init failed\r\n");
   goto exit_usbd_init;
}

ret = usbd_composite_msc_init(&composite_msc_usr_cb, &msc_class_cfg);
if (ret != RTK_SUCCESS) {
   RTK_LOGS(TAG, RTK_LOG_ERROR, "MSC init failed\r\n");
   goto exit_cdc_acm_init;
}

/* Start the framework only once every sub-function is registered: the
   configuration descriptor is assembled from them here. */
ret = usbd_composite_init(&composite_usr_cb);
if (ret != RTK_SUCCESS) {
   RTK_LOGS(TAG, RTK_LOG_ERROR, "Composite init failed\r\n");
   goto exit_msc_init;
}

Application Callback API

The framework provides callback interfaces for the application layer, allowing application code to respond to USB events and handle business logic. There are two levels, and they are supplied separately.

  • Composite Application Callback API

    usbd_composite_cb_t reports the status of the whole composite device. It carries a single status_changed callback, invoked once when the USB attach status changes, regardless of how many sub-functions are registered.

  • Function Class Application Callback API

    Each sub-function keeps its own callback type, the same one its standalone mode uses: usbd_cdc_acm_cb_t, usbd_msc_cb_t, usbd_hid_usr_cb_t, usbd_uac_cb_t, and so on. You pass it to that class’s usbd_composite_xxx_init(); it is not merged into one composite structure.

    The exact set of callbacks differs per class — consult that class’s chapter. The members shared by most classes are:

    API

    Description

    init

    Called during class driver initialization; used to initialize application-specific resources.

    deinit

    Called during class driver de-initialization; used to release application-specific resources.

    setup

    Called during the setup or data stage of a control transfer; used to handle application-specific control requests.

    set_config

    Called when the class is configured; notifies the application that the class is ready for transfers.

    status_changed

    Called when the USB connection status changes; used to handle hot-plug events.

    transmitted

    Called upon completion of an IN transfer; used to asynchronously obtain the IN transfer status.

    received

    Called upon completion of an OUT transfer; used to asynchronously obtain the received data.

CDC ACM + MSC Example

The following section takes CDC ACM + MSC as an example to show how the two callback levels are supplied (MSC uses the default callbacks and leaves them empty).

/* Composite level: one callback for the whole device */
static const usbd_composite_cb_t composite_usr_cb = {
   .status_changed = composite_cb_status_changed,
};

/* Sub-function level: each class keeps its own callback type */
static const usbd_cdc_acm_cb_t composite_cdc_acm_usr_cb = {
   .init     = composite_cdc_acm_cb_init,      /* Application resource setup */
   .deinit   = composite_cdc_acm_cb_deinit,    /* Application resource cleanup */
   .setup    = composite_cdc_acm_cb_setup,     /* Class-specific control requests */
   .received = composite_cdc_acm_cb_received,  /* Data arrived on the BULK OUT endpoint */
};

/* MSC needs no application callbacks beyond the optional status change */
static const usbd_msc_cb_t composite_msc_usr_cb = {
   .status_changed = NULL,
};

The composite-level callback is passed to usbd_composite_init() and fires once per attach-status change. The per-class callbacks are passed to their own usbd_composite_xxx_init(), exactly as in standalone mode — the framework stores a pointer to each and routes events to the owning class.

API for Application

The application layer brings up a composite device in three ordered steps, and tears it down in the reverse order:

  • Start the core: call usbd_init() once with a usbd_config_t whose ctrl_xfer_buf_len covers the assembled configuration descriptor of every sub-function.

  • Initialize each sub-function: call the usbd_composite_xxx_init() variant of every class (for example usbd_composite_cdc_acm_init()). Each takes that class’s own callback set and class configuration, and registers its class driver with the composite framework.

  • usbd_composite_init(): start the composite framework, after every class has been initialized. It takes the optional composite-level user callback. All class drivers must already be registered, because the configuration descriptor is assembled from them here.

De-initialization walks the same list backwards: usbd_composite_deinit() first, then each class’s usbd_xxx_deinit(), then usbd_deinit().

Both teardown calls share one constraint: they must run in task context. usbd_composite_deinit() blocks the USB ISR and clears the configuration of every registered function; usbd_unregister_class() (called inside each class’s deinit) refuses to run from an interrupt handler, because the class would otherwise still be reachable from the ISR while its resources are released. Calling either from an ISR returns -RTK_ERR_BADARG and changes nothing, so the caller shall not free anything in that case. A class deinit that runs while the composite device is still registered touches nothing for the same reason, which is why the composite teardown has to come first.

CDC ACM + MSC Example

The following section takes CDC ACM + MSC as an example to introduce the implementation of application-layer-oriented APIs for composite device class drivers.

/**
* @brief  Init composite stack: core -> each class -> composite framework
* @return Status
*/
int composite_init_stack(void)
{
   int ret;

   /* Step 1: Initialize storage disk (must be done before usbd_init) */
   ret = usbd_msc_disk_init();
   if (ret != RTK_SUCCESS) {
      RTK_LOGS(TAG, RTK_LOG_ERROR, "MSC disk init failed\r\n");
      return ret;
   }

   /* Step 2: Start USB device stack */
   ret = usbd_init(&composite_cfg);
   if (ret != RTK_SUCCESS) {
      RTK_LOGS(TAG, RTK_LOG_ERROR, "usbd_init failed\r\n");
      goto exit_disk_init;
   }

   /* Step 3: Initialize each class driver with its own callback set and EP config.
      Each composite_init registers its class driver with the composite framework. */
   ret = usbd_composite_cdc_acm_init(&composite_cdc_acm_usr_cb, &cdc_acm_class_cfg);
   if (ret != RTK_SUCCESS) {
      RTK_LOGS(TAG, RTK_LOG_ERROR, "CDC ACM init failed\r\n");
      goto exit_usbd_init;
   }

   ret = usbd_composite_msc_init(&composite_msc_usr_cb, &msc_class_cfg);
   if (ret != RTK_SUCCESS) {
      RTK_LOGS(TAG, RTK_LOG_ERROR, "MSC init failed\r\n");
      goto exit_cdc_acm_init;
   }

   /* Step 4: Start composite framework (drivers already registered in step 3) */
   ret = usbd_composite_init(COMP_CB);
   if (ret != RTK_SUCCESS) {
      RTK_LOGS(TAG, RTK_LOG_ERROR, "Composite init failed\r\n");
      goto exit_msc_init;
   }

   return RTK_SUCCESS;

exit_msc_init:
   usbd_msc_deinit();
exit_cdc_acm_init:
   usbd_cdc_acm_deinit();
exit_usbd_init:
   usbd_deinit();
exit_disk_init:
   usbd_msc_disk_deinit();
   return ret;
}

/**
* @brief  DeInit composite stack, in the reverse order: framework -> classes -> core
* @param  void
* @return Status
*/
void composite_deinit_stack(void)
{
   usbd_composite_deinit();
   usbd_msc_deinit();
   usbd_cdc_acm_deinit();
   usbd_deinit();
   usbd_msc_disk_deinit();
}

Note

For detailed class driver descriptions, please refer to: Vendor-Specific Device Solution

API Reference

For detailed function prototypes and usage, please refer to the Driver API

Application Example

This section takes USB Composite (CDC ACM + MSC) as an example to introduce the complete application implementation and the method of running example application.

Application Design

This section provides a detailed introduction to the complete development and design process of composite device drivers, covering driver initialization, hotplug management, and resource release.

Driver Initialization

The initialization process involves sequentially completing USB Core initialization, and Composite class driver loading. Defining the configuration structure and registering user callback functions are essential steps.

  • Configuration: Configure USB speed mode and interrupt priority.

  • Callback Registration: Define the user callback structure:cpp:struct:usbd_composite_cb_t 和 usbd_composite_fucntion_xx_usr_cb and mount handler functions for each stage.

  • Core Initialization: Call usbd_init() to initialize the USB core.

  • Class Driver Init: Call usbd_composite_init() to initialize the composite class driver.

The following section uses CDC ACM + MSC as an example to introduces the implementation of composite device driver initialization.

Most of the interactions with the MSC are automatically handled by the protocol stack, while the application layer primarily focuses on disk initialization and deinitialization. Prior to USB initialization, it is essential to ensure that the storage medium (such as an SD card or Flash) is ready and invoke the disk initialization interface.

static usbd_config_t composite_cfg = {
   .speed = CONFIG_USBD_COMPOSITE_SPEED,
   .isr_priority = CONFIG_USBD_COMPOSITE_ISR_THREAD_PRIORITY,
   .intr_use_ptx_fifo = 0U,
};

/* CDC ACM class configuration: endpoint addresses and transfer sizing */
static const usbd_cdc_acm_config_t cdc_acm_class_cfg = {
   .bulk_in_addr       = COMP_CDC_BULK_IN_EP,
   .bulk_out_addr      = COMP_CDC_BULK_OUT_EP,
   .intr_in_addr       = COMP_CDC_INTR_IN_EP,
   .bulk_in_xfer_size  = CDC_BULK_IN_XFER_SIZE,
   .bulk_out_xfer_size = CDC_BULK_OUT_XFER_SIZE,
   .notify_en          = 1,
   .bulk_in_zero_copy  = 0,
};

/* MSC class configuration */
static const usbd_msc_config_t msc_class_cfg = {
   .bulk_in_addr  = COMP_MSC_BULK_IN_EP,
   .bulk_out_addr = COMP_MSC_BULK_OUT_EP,
};

/* Per-class user callbacks */
static const usbd_cdc_acm_cb_t composite_cdc_acm_usr_cb = {
   .init       = composite_cdc_acm_cb_init,
   .deinit     = composite_cdc_acm_cb_deinit,
   .setup      = composite_cdc_acm_cb_setup,
   .received   = composite_cdc_acm_cb_received,
};

static const usbd_msc_cb_t composite_msc_usr_cb = {
   .status_changed = NULL,
};

/* Composite-level callback, optional */
static const usbd_composite_cb_t composite_usr_cb = {
   .status_changed = composite_cb_status_changed,
};

int ret = 0;

/* Step 1: Initializes the underlying storage disk (must precede usbd_init). */
ret = usbd_msc_disk_init();
if (ret != RTK_SUCCESS) {
   return;
}

/* Step 2: Initialize USB device core driver with configuration. */
ret = usbd_init(&composite_cfg);
if (ret != RTK_SUCCESS) {
   usbd_msc_disk_deinit();
   return;
}

/* Step 3: Initialize each class driver. Each registers itself with the composite framework. */
ret = usbd_composite_cdc_acm_init(&composite_cdc_acm_usr_cb, &cdc_acm_class_cfg);
if (ret != RTK_SUCCESS) {
   usbd_deinit();
   usbd_msc_disk_deinit();
   return;
}

ret = usbd_composite_msc_init(&composite_msc_usr_cb, &msc_class_cfg);
if (ret != RTK_SUCCESS) {
   usbd_cdc_acm_deinit();
   usbd_deinit();
   usbd_msc_disk_deinit();
   return;
}

/* Step 4: Start the composite framework, after all classes are registered. */
ret = usbd_composite_init(&composite_usr_cb);
if (ret != RTK_SUCCESS) {
   usbd_msc_deinit();
   usbd_cdc_acm_deinit();
   usbd_deinit();
   usbd_msc_disk_deinit();
   return;
}

USB Hot-plug Event Handling

Monitor USB connection status changes (connected/disconnected) by registering the status_changed callback function.

Refer to Device Connection Status Detection for more details.

Note

It is recommended to use a semaphore to notify a dedicated task thread for processing, to avoid executing time-consuming operations within the interrupt context.

The following section uses CDC ACM + MSC as an example to introduces the USB Hot-plug Event Handling of composite device driver.

static u8 composite_attach_status;
static rtos_sema_t composite_attach_status_changed_sema;

/* Composite-level USB status change callback */
static const usbd_composite_cb_t composite_usr_cb = {
   .status_changed = composite_cb_status_changed,
};

/* Callback executed in ISR context */
static void composite_cb_status_changed(u8 old_status, u8 status)
{
   composite_attach_status = status;
   rtos_sema_give(composite_attach_status_changed_sema);
}

/* Thread Context: Handle the state machine */
static void composite_hotplug_thread(void *param)
{
   UNUSED(param);

   for (;;) {
      /* Wait for status change signal */
      if (rtos_sema_take(composite_attach_status_changed_sema, RTOS_SEMA_MAX_COUNT) == RTK_SUCCESS) {
         if (composite_attach_status == USBD_ATTACH_STATUS_DETACHED) {
            RTK_LOGS(TAG, RTK_LOG_INFO, "DETACHED\n");
            /* 1. Tear the whole stack down, framework first */
            composite_deinit_stack();
            /* 2. Rebuild it for the next connection */
            if (composite_init_stack() != RTK_SUCCESS) {
               break;
            }
         } else if (composite_attach_status == USBD_ATTACH_STATUS_ATTACHED) {
            RTK_LOGS(TAG, RTK_LOG_INFO, "ATTACHED\n");
         } else {
            RTK_LOGS(TAG, RTK_LOG_INFO, "INIT\n");
         }
      }
   }
   RTK_LOGS(TAG, RTK_LOG_ERROR, "Hotplug thread fail\n");
   rtos_task_delete(NULL);
}

Driver Deinitialization

When the USB function is no longer needed or the system is shut down, resources need to be released in the reverse order of initialization. The following section uses CDC ACM + MSC as an example to introduces the implementation of composite device driver deinitialization.

/* Tear down in the reverse order of composite_init_stack():
   framework -> classes -> core -> disk */
usbd_composite_deinit();
usbd_msc_deinit();
usbd_cdc_acm_deinit();
usbd_deinit();
usbd_msc_disk_deinit();

Operation method

This example demonstrates how to use the composite device protocol stack to configure the Ameba development board as a device featuring both CDC ACM (Virtual Serial Port) and MSC (Mass Storage) capabilities simultaneously.

When the development board is connected to a USB Host (e.g., a PC), the system will recognize two independent logical devices. Users can communicate with the board via a serial tool and, at the same time, read from and write to the on-board SD card just like operating a standard USB flash drive.

The example code path is: {SDK}/example/usb/usbd_composite_cdc_acm_msc. It provides provides a complete reference solution for developers to design custom Composite products.

Configuration and Compilation

  • Compilation and Flashing

    Execute the following commands in the SDK root directory to configure the environment, select the target SoC, compile the project, and flash the generated Image file to the development board.

    # Initialize environment (required for every new terminal)
    source env.sh or env.bat(Windows system)
    
    # Select Target SoC (replace xxx with your specific SoCs)
    ameba.py soc xxx
    
    ameba.py build -a usbd_composite_cdc_acm_msc -p
    
  • Confirmation of Menuconfig configuration

    If compilation fails, please execute ameba.py menuconfig and confirm that Composite function enable is set and that both CDC ACM and MSC are selected under USB Device Class Selection.

    - Choose `CONFIG USB --->`:
    
       [*] Enable USB
             USB Mode (Device)  --->
          *** USB Device Global Settings ***
       [*] Composite function enable
          *** USB Device Class Selection ***
       [*] CDC ACM
       [*] MSC
             Select storage media (SD card, SDIO mode)  --->
    

    Composite function enable is the switch that turns on the composite framework. Each function you select below it is added to the same device descriptor.

    The storage media is a single choice; the default is SD card, SDIO mode:

    Menu entry

    Symbol

    Notes

    FLASH (on-chip)

    USBD_MSC_FLASH

    On-chip primary flash, mounted through VFS FATFS.

    Second FLASH (NOR)

    USBD_MSC_SECOND_FLASH

    External SPI NOR. NAND is not supported: leave CONFIG_VFS_SECOND_FLASH_NAND unset, otherwise the build fails.

    SD card, SDIO mode

    USBD_MSC_SD_CARD

    Default. Requires an SD card in the board’s SDIOH slot.

    SD card, SPI mode

    USBD_MSC_SD_SPI

    SD card or SD NAND behind a generic SPI master.

    RAM disk

    USBD_MSC_RAM

    VFS RAM disk in SRAM or PSRAM. Volatile: every attach formats an empty disk.

    FLASH and RAM mount a FATFS volume through VFS; the other media are driven by the MSC class through ll_diskio_drv directly. For the FLASH medium, COMP_MSC_FLASH_VFS_REGION in example_usbd_composite_cdc_acm_msc.c picks the region (VFS1 or VFS2, default VFS2).

Verification

  • Device Startup

    Reset the development board and observe the serial log. The test passes when the lines below appear and no error-level log (-E) is reported:

    [COMP-I] USBD ACM+MSC comp demo start
    [MSC-I] Disk init
    [USBD-A] INIT
    [MSC-I] Init
    [COMP-I] ATTACHED
    
  • Connect to Host

    Connect the development board to a PC using a USB cable.

    When the device is connected to a Windows PC host, the Device Manager will present the following hierarchical structure:

    • Under Universal Serial Bus Controller, there appears: USB Composite Device (driven by usbccgp.sys).

    • Under the Universal Serial Bus Controller, there appears: USB Mass Storage Device (corresponding to the MSC function).

    • Under Ports (COM and LPT), there appears: USB Serial Device (COMx) (corresponding to the CDC ACM function).

  • Function verification 1: CDC ACM (virtual serial port)

    • Open the serial port debugging tool (such as Realtek Trace Tool) on the PC.

    • Select the virtual serial port number enumerated by the development board.

    • Send any character, and the development board will echo the received data as is to verify normal communication.

  • Function verification 2: MSC (mass storage)

    A new removable disk drive letter should automatically pop up in the PC’s file explorer. Users can double-click to open the drive letter and perform file read and write operations on the inserted SD card.

    Note

    This example uses an SD card as the underlying storage medium for the MSC. Please ensure that a formatted SD card is inserted into the on-board SDIOH slot of the development board. Please avoid removing the SD card or disconnecting the USB connection during data reading and writing to prevent damage to the file system.