USB Common API

USB Common Functions

void usb_os_sleep_ms(u32 ms)

Delays execution for a specified number of milliseconds.

参数:

ms -- [in] The duration to sleep in milliseconds.

void usb_os_delay_us(u32 us)

Delays execution for a specified number of microseconds.

参数:

us -- [in] The duration to delay in microseconds.

void usb_os_memset(void *buf, u8 val, u32 size)

Fills a block of memory with a specified value.

参数:
  • buf -- [out] Pointer to the memory block to fill.

  • val -- [in] The value to be set.

  • size -- [in] The number of bytes to be set to the value.

void usb_os_memcpy(void *dst, const void *src, u32 size)

Copies a block of memory from a source to a destination.

参数:
  • dst -- [out] Pointer to the destination array where the content is to be copied.

  • src -- [in] Pointer to the source of data to be copied.

  • size -- [in] The number of bytes to copy.

void *usb_os_malloc(u32 size)

Allocates a block of memory from the heap.

参数:

size -- [in] The size of the memory block to allocate, in bytes.

返回:

A pointer to the allocated memory, or NULL if the request fails.

void usb_os_mfree(void *handle)

Frees a previously allocated block of memory.

参数:

handle -- [in] A pointer to the memory block to be freed.

int usb_os_lock_create(usb_os_lock_t *lock)

Creates a new mutex.

参数:

lock -- [out] Pointer to the mutex handle to be created.

返回:

0 on success, non-zero on failure

int usb_os_lock_delete(usb_os_lock_t lock)

Deletes a mutex.

参数:

lock -- [in] The mutex handle to be deleted.

返回:

0 on success, non-zero on failure

int usb_os_lock(usb_os_lock_t lock)

Acquires a mutex (locks it).

参数:

lock -- [in] The mutex handle to be acquired.

返回:

0 on success, non-zero on failure

int usb_os_unlock(usb_os_lock_t lock)

Releases a mutex (unlocks it).

参数:

lock -- [in] The mutex handle to be released.

返回:

0 on success, non-zero on failure

int usb_os_enter_critical(u8 in_critical)

Enters a critical section (disables interrupts).

参数:

in_critical -- [in] Flag indicating if this should be a critical section.

返回:

0 on success, non-zero on failure

int usb_os_exit_critical(u8 in_critical)

Exits a critical section (enables interrupts).

参数:

in_critical -- [in] Flag indicating if this should be a critical section.

返回:

0 on success, non-zero on failure

int usb_os_sema_create(usb_os_sema_t *sema)

Creates a new binary or counting semaphore.

参数:

sema -- [out] Pointer to the semaphore handle to be created.

返回:

0 on success, non-zero on failure

int usb_os_sema_delete(usb_os_sema_t sema)

Deletes a semaphore.

参数:

sema -- [in] The semaphore handle to be deleted.

返回:

0 on success, non-zero on failure

int usb_os_sema_take(usb_os_sema_t sema, u32 timeout_ms)

Acquires a semaphore.

参数:
  • sema -- [in] The semaphore handle to acquire.

  • timeout_ms -- [in] The maximum time in milliseconds to wait for the semaphore.

返回:

0 on success, a negative error code on failure or timeout.

int usb_os_sema_give(usb_os_sema_t sema)

Releases a semaphore.

参数:

sema -- [in] The semaphore handle to release.

返回:

0 on success, non-zero on failure

int usb_os_queue_create(usb_os_queue_t *queue, u32 msg_num, u32 msg_size)

Creates a new message queue.

参数:
  • queue -- [out] Pointer to the queue handle to be created.

  • msg_num -- [in] The maximum number of messages the queue can hold.

  • msg_size -- [in] The size of each message in bytes.

返回:

0 on success, non-zero on failure

int usb_os_queue_delete(usb_os_queue_t queue)

Deletes a message queue.

参数:

queue -- [in] The queue handle to be deleted.

返回:

0 on success, non-zero on failure

int usb_os_queue_send(usb_os_queue_t queue, void *msg, u32 wait_ms)

Sends a message to a queue.

参数:
  • queue -- [in] The handle of the target queue.

  • msg -- [in] A pointer to the message to be sent.

  • wait_ms -- [in] The maximum time in milliseconds to wait if the queue is full.

返回:

0 on success, non-zero on failure

int usb_os_queue_receive(usb_os_queue_t queue, void *msg, u32 wait_ms)

Receives a message from a queue.

参数:
  • queue -- [in] The handle of the target queue.

  • msg -- [out] A pointer to a buffer to store the received message.

  • wait_ms -- [in] The maximum time in milliseconds to wait if the queue is empty.

返回:

0 on success, a negative error code on failure or timeout.

u32 usb_os_get_free_heap_size(void)

Gets the size of the free heap memory.

返回:

The number of free bytes in the heap.

USB Common Constants

USB_LEN_DEV_QUALIFIER_DESC

Defines for the standard lengths of various USB descriptors.

Length of Device Qualifier descriptor.

USB_LEN_DEV_DESC

Length of Device descriptor.

USB_LEN_BOS_DESC

Length of BOS descriptor.

USB_LEN_CFG_DESC

Length of Configuration descriptor.

USB_LEN_IAD_DESC

Length of IAD descriptor.

USB_LEN_IF_DESC

Length of Interface descriptor.

USB_LEN_EP_DESC

Length of Endpoint descriptor.

USB_LEN_OTG_DESC

Length of OTG descriptor.

USB_LEN_LANGID_STR_DESC

Length of Language ID String descriptor.

USB_LEN_OTHER_SPEED_DESC_SIZ

Length of Other Speed Configuration descriptor.

USB_DESC_DEVICE

High-byte values for the wValue field in a GET_DESCRIPTOR request.

USB_DESC_CONFIGURATION
USB_DESC_STRING
USB_DESC_INTERFACE
USB_DESC_ENDPOINT
USB_DESC_DEVICE_QUALIFIER
USB_DESC_OTHER_SPEED_CONFIGURATION
USB_DESC_INTERFACE_POWER
USB_DESC_BOS
USB_DESC_HUB_DESC
USB_REQ_DIR_MASK

Defines for the bits within the bmRequestType field of a setup request.

Mask for data transfer direction bit.

USB_REQ_NUM_MASK

Mask for endpoint number.

USB_H2D

Host-to-Device direction.

USB_D2H

Device-to-Host direction.

USB_EP_IS_IN(ep_addr)

Check if the endpoint direction is IN.

USB_EP_IS_OUT(ep_addr)

Check if the endpoint direction is OUT.

USB_EP_NUM(ep_addr)

Get endpoint number from address.

USB_REQ_TYPE_STANDARD

Standard request type.

USB_REQ_TYPE_CLASS

Class-specific request type.

USB_REQ_TYPE_VENDOR

Vendor-specific request type.

USB_REQ_TYPE_MASK

Mask for request type bits.

USB_REQ_RECIPIENT_DEVICE

Request recipient is the device.

USB_REQ_RECIPIENT_INTERFACE

Request recipient is an interface.

USB_REQ_RECIPIENT_ENDPOINT

Request recipient is an endpoint.

USB_REQ_RECIPIENT_MASK

Mask for request recipient bits.

USB_REQ_GET_STATUS

Defines for standard USB request codes (USB Spec Table 9-4).

Get Status request.

USB_REQ_CLEAR_FEATURE

Clear Feature request.

USB_REQ_SET_FEATURE

Set Feature request.

USB_REQ_SET_ADDRESS

Set Address request.

USB_REQ_GET_DESCRIPTOR

Get Descriptor request.

USB_REQ_SET_DESCRIPTOR

Set Descriptor request.

USB_REQ_GET_CONFIGURATION

Get Configuration request.

USB_REQ_SET_CONFIGURATION

Set Configuration request.

USB_REQ_GET_INTERFACE

Get Interface request.

USB_REQ_SET_INTERFACE

Set Interface request.

USB_REQ_SYNCH_FRAME

Synch Frame request.

USB_DESC_TYPE_DEVICE

Defines for standard USB descriptor types (USB Spec Table 9-5).

Device descriptor type.

USB_DESC_TYPE_CONFIGURATION

Configuration descriptor type.

USB_DESC_TYPE_STRING

String descriptor type.

USB_DESC_TYPE_INTERFACE

Interface descriptor type.

USB_DESC_TYPE_ENDPOINT

Endpoint descriptor type.

USB_DESC_TYPE_DEVICE_QUALIFIER

Device Qualifier descriptor type.

USB_DESC_TYPE_OTHER_SPEED_CONFIGURATION

Other Speed Configuration descriptor type.

USB_DESC_TYPE_INTERFACE_POWER

Interface Power descriptor type.

USB_DESC_TYPE_IAD

Interface Association Descriptor (IAD) type.

USB_DESC_TYPE_BOS

Binary Device Object Store (BOS) descriptor type.

USB_DESC_TYPE_HUB

Hub descriptor type.

USB_CONFIG_REMOTE_WAKEUP

Defines for standard feature selectors used in Set/Clear Feature requests.

Configuration-level remote wakeup feature.

USB_CONFIG_SELF_POWERED

Configuration-level self-powered feature.

USB_FEATURE_EP_HALT

Endpoint halt feature selector.

USB_FEATURE_REMOTE_WAKEUP

Device remote wakeup feature selector.

USB_FEATURE_TEST_MODE

Test mode feature selector.

USB_EP_XFER_TYPE_MASK

Macros related to endpoint descriptors and addresses.

Mask to extract transfer type from bmAttributes.

USB_EP_MPS_SIZE_MASK

Mask for packet size in wMaxPacketSize.

USB_EP_MPS_TRANS_MASK

Mask for additional transactions in wMaxPacketSize.

USB_EP_MPS_TRANS_POS

Position of additional transactions field.

USB_EP0_OUT

Endpoint 0 OUT address.

USB_EP0_IN

Endpoint 0 IN address.

USB_HS_MAX_PACKET_SIZE

Defines for maximum packet sizes for various speeds and endpoint types.

High-Speed maximum packet size.

USB_FS_MAX_PACKET_SIZE

Full-Speed maximum packet size.

USB_MAX_EP0_SIZE

Maximum packet size for Endpoint 0.

USB_CTRL_MAX_MPS

Maximum MPS for any Control endpoint.

USB_XFER_MAX_MPS

Maximum MPS for any transfer.

USB_BULK_FS_MAX_MPS

Full-Speed Bulk maximum MPS.

USB_BULK_HS_MAX_MPS

High-Speed Bulk maximum MPS.

USB_INTR_FS_MAX_MPS

Full-Speed Interrupt maximum MPS.

USB_INTR_HS_MAX_MPS

High-Speed Interrupt maximum MPS.

USB_ISOC_FS_MAX_MPS

Full-Speed Isochronous maximum MPS.

USB_ISOC_HS_MAX_MPS

High-Speed Isochronous maximum MPS.

USB_CLASS_HUB

Defines related to the USB Hub Class specification.

USB device class type

USB_PORT_FEAT_CONNECTION

Feature selectors for Hub Port Get/Set/Clear Feature requests.

Port Connection feature.

USB_PORT_FEAT_ENABLE

Port Enable feature.

USB_PORT_FEAT_SUSPEND

Port Suspend feature.

USB_PORT_FEAT_OVER_CURRENT

Port Over-current feature.

USB_PORT_FEAT_RESET

Port Reset feature.

USB_PORT_FEAT_POWER

Port Power feature.

USB_PORT_FEAT_LOWSPEED

Port Low-speed device attached feature.

USB_PORT_FEAT_HIGHSPEED

Port High-speed device attached feature.

USB_PORT_FEAT_C_CONNECTION

Port Connection change feature.

USB_PORT_FEAT_C_ENABLE

Port Enable change feature.

USB_PORT_FEAT_C_SUSPEND

Port Suspend change feature.

USB_PORT_FEAT_C_OVER_CURRENT

Port Over-current change feature.

USB_PORT_FEAT_C_RESET

Port Reset change feature.

USB_PORT_STAT_CONNECTION

Bit definitions for the wPortStatus field returned by GetPortStatus.

Device is connected to the port.

USB_PORT_STAT_ENABLE

Port is enabled.

USB_PORT_STAT_SUSPEND

Port is suspended.

USB_PORT_STAT_OVERCURRENT

Port is in an over-current condition.

USB_PORT_STAT_RESET

Port is in reset.

USB_PORT_STAT_POWER

Port power is on.

USB_PORT_STAT_LOW_SPEED

A low-speed device is attached.

USB_PORT_STAT_HIGH_SPEED

A high-speed device is attached (EHCI).

USB_PORT_STAT_SUPER_SPEED

A super-speed device is attached (XHCI).

USB_PORT_STAT_SPEED_MASK

Mask to get port speed.

USB_PORT_STAT_C_CONNECTION

Bit definitions for the wPortChange field returned by GetPortStatus.

Connection status has changed.

USB_PORT_STAT_C_ENABLE

Enable status has changed.

USB_PORT_STAT_C_SUSPEND

Suspend status has changed.

USB_PORT_STAT_C_OVERCURRENT

Over-current status has changed.

USB_PORT_STAT_C_RESET

Reset completion has occurred.

USB_VERSION_ID_0201

USB Specification version 2.01.

USB_DEV_DESC_OFFSET_VID

Offset to idVendor in device descriptor.

USB_DEV_DESC_OFFSET_PID

Offset to idProduct in device descriptor.

USB_CFG_DESC_OFFSET_TYPE

Offset to bDescriptorType in configuration descriptor.

USB_CFG_DESC_OFFSET_TOTAL_LEN

Offset to wTotalLength in configuration descriptor.

USB_CFG_DESC_OFFSET_ATTR

Offset to bmAttributes in configuration descriptor.

USB_CFG_DESC_OFFSET_ATTR_BIT_SELF_POWERED

Self-powered bit in bmAttributes.

USB_CFG_DESC_OFFSET_ATTR_BIT_REMOTE_WAKEUP

Remote wakeup bit in bmAttributes.

USB_DEVICE_CAPABITY_TYPE

Device Capability descriptor type.

USB_OS_SEMA_TIMEOUT

Defines the maximum timeout value for semaphore operations.

USB_DMA_ALIGNED

Ensures a variable is aligned to the cache line size for DMA operations.

This is critical for DMA buffers to prevent data corruption due to cache coherency issues.

USB_IS_MEM_DMA_ALIGNED(x)

Checks if a memory address is aligned to the cache line size.

参数:
  • x -- The memory address to check.

返回:

Non-zero if aligned, 0 otherwise.

USB_LOW_BYTE(x)

Extracts the low byte from a 16-bit value.

参数:
  • x -- The 16-bit value.

返回:

The low byte (u8).

USB_HIGH_BYTE(x)

Extracts the high byte from a 16-bit value.

参数:
  • x -- The 16-bit value.

返回:

The high byte (u8).

USB Common Types

typedef rtos_mutex_t usb_os_lock_t

Type definitions for abstracting OS objects.

Abstracted type for a mutex or lock.

typedef rtos_sema_t usb_os_sema_t

Abstracted type for a semaphore.

typedef rtos_queue_t usb_os_queue_t

Abstracted type for a message queue.

typedef rtos_task_t usb_os_task_t

Abstracted type for a task handle.

enum usb_ch_ep_type_t

Defines the transfer type of a USB endpoint.

Corresponds to the bmAttributes field in the endpoint descriptor.

Values:

enumerator USB_CH_EP_TYPE_CTRL

Control Endpoint/pipe.

enumerator USB_CH_EP_TYPE_ISOC

Isochronous Endpoint/pipe.

enumerator USB_CH_EP_TYPE_BULK

Bulk Endpoint/pipe.

enumerator USB_CH_EP_TYPE_INTR

Interrupt Endpoint/pipe.

enum usb_speed_type_t

Defines the operational speeds for the USB controller.

Values:

enumerator USB_SPEED_HIGH

High Speed (480 Mbps).

enumerator USB_SPEED_HIGH_IN_FULL

High Speed core running in Full Speed mode.

enumerator USB_SPEED_LOW

Low Speed (1.5 Mbps).

enumerator USB_SPEED_FULL

Full Speed (12 Mbps).

struct usb_setup_req_t
#include <usb_ch9.h>

Standard USB setup request packet structure.

This structure represents the 8-byte setup packet sent during the setup phase of a control transfer. (USB Spec 2.0, Table 9-2)

Public Members

u8 bmRequestType

Characteristics of the request.

u8 bRequest

Specific request code.

u16 wValue

Request-specific value, often used for descriptor type and index.

u16 wIndex

Request-specific index, often an interface or endpoint number.

u16 wLength

Number of bytes to transfer in the data phase.

USB Device API

USB Device Functions

Device CDC ACM Functions

int usbd_cdc_acm_init(u16 bulk_out_xfer_size, u16 bulk_in_xfer_size, usbd_cdc_acm_cb_t *cb)

Initializes class driver with application callback handler.

参数:
  • bulk_out_xfer_size -- [in] BULK OUT xfer buffer malloc length.

  • bulk_in_xfer_size -- [in] BULK IN xfer buffer malloc length.

  • cb -- [in] Pointer to the user-defined callback structure.

返回:

0 on success, non-zero on failure.

int usbd_cdc_acm_deinit(void)

De-initializes the CDC ACM class driver.

返回:

0 on success, non-zero on failure.

int usbd_cdc_acm_transmit(u8 *buf, u16 len)

Transmits data to the host over the BULK IN endpoint.

参数:
  • buf -- [in] Pointer to the data buffer to be transmitted.

  • len -- [in] Length of the data in bytes.

返回:

0 on success, non-zero on failure.

int usbd_cdc_acm_notify_serial_state(u16 serial_state)

Sets new line coding properties over the INTR IN endpoint.

参数:

serial_state -- [in] New line coding properties.

返回:

0 on success, non-zero on failure.

Device Core Functions For Applications

int usbd_init(usbd_config_t *cfg)

Initialize USB device core driver with configuration.

参数:

cfg -- [in] USB device configuration.

返回:

0 on success, non-zero on failure.

int usbd_deinit(void)

Deinitialize USB device core driver.

返回:

0 on success, non-zero on failure.

int usbd_get_status(void)

Get USB device attach status.

返回:

See usbd_attach_status_t.

int usbd_get_bus_status(u32 *status)

Get USB device bus status.

参数:

status -- [out] Return 0 on success, with the status parameter containing USB bus status represented as a bitwise combination of enumeration values:

  • USB_DEV_BUS_STATUS_DN = BIT0, // D- line status bit.

  • USB_DEV_BUS_STATUS_DP = BIT1, // D+ line status bit.

  • USB_DEV_BUS_STATUS_SUSPEND = BIT2, //Suspend indication bit.

返回:

0 on success, non-zero on failure.

int usbd_wake_host(void)

Sends a remote wakeup signal to the USB host to resume communication.

返回:

0 on success, non-zero on failure.

Device Core Functions For Classes

int usbd_register_class(const usbd_class_driver_t *driver)

Register a device class driver, called in class initialization function.

参数:

driver -- [in] USB class driver.

返回:

0 on success, non-zero on failure.

int usbd_unregister_class(void)

Un-register a class, called in class de-initialization function.

返回:

0 on success, non-zero on failure.

int usbd_ep_init(usb_dev_t *dev, usbd_ep_t *ep)

Initialize an endpoint.

备注

Typically called in following scenarios:

  • In the set_config callback function of the usbd_class_driver_t.

  • In the setup callback function of the usbd_class_driver_t, when receiving specific requests (such as SET_INTERFACE) that require endpoint (re-)initialization.

参数:
  • dev -- [in] USB device.

  • ep -- [in] USB endpoint.

返回:

0 on success, non-zero on failure.

int usbd_ep_deinit(usb_dev_t *dev, usbd_ep_t *ep)

Deinitialize an endpoint.

备注

Typically called in following scenarios:

  • In the clear_config callback function of the usbd_class_driver_t.

  • In the setup callback function of the usbd_class_driver_t, when receiving specific requests (such as SET_INTERFACE) that require endpoint deinitialization.

参数:
  • dev -- [in] USB device.

  • ep -- [in] USB endpoint.

返回:

0 on success, non-zero on failure.

int usbd_ep_transmit(usb_dev_t *dev, usbd_ep_t *ep)

Initiates an IN transfer to the USB host through a specified endpoint.

备注

  • The transfer executes asynchronously: function return doesn't indicate completion.

  • Check transfer status via ep_data_in/ep0_data_in callback of the usbd_class_driver_t.

  • Zero-Length Packet will be automatically transmitted as needed by device core driver.

参数:
  • dev -- [in] USB device.

  • ep -- [in] USB endpoint.

返回:

0 on success, non-zero on failure.

int usbd_ep_receive(usb_dev_t *dev, usbd_ep_t *ep)

Prepares to receive OUT transfer data from the USB host through a specified endpoint.

备注

  • The transfer executes asynchronously: function return doesn't indicate completion.

  • Retrieved data is available via the ep_data_out/ep0_data_out callback of the usbd_class_driver_t.

参数:
  • dev -- [in] USB device.

  • ep -- [in] USB endpoint.

返回:

0 on success, non-zero on failure.

int usbd_ep_set_stall(usb_dev_t *dev, usbd_ep_t *ep)

Sets the specified endpoint to STALL state.

参数:
  • dev -- [in] USB device.

  • ep -- [in] USB endpoint.

返回:

0 on success, non-zero on failure.

int usbd_ep_clear_stall(usb_dev_t *dev, usbd_ep_t *ep)

Clears the STALL state of the specified endpoint.

参数:
  • dev -- [in] USB device.

  • ep -- [in] USB endpoint.

返回:

0 on success, non-zero on failure.

int usbd_ep_is_stall(usb_dev_t *dev, usbd_ep_t *ep)

Checks whether the specified endpoint is in STALL state.

参数:
  • dev -- [in] USB device.

  • ep -- [in] USB endpoint.

返回:

  • 1: The endpoint is stalled.

  • 0: The endpoint is not stalled.

u16 usbd_get_str_desc(const char *str, u8 *desc)

Converts ASCII strings to UNICODE16-encoded USB string descriptors.

备注

The destination buffer must accommodate twice the source length plus 2 bytes (for the length, and type fields of string descriptor)

参数:
  • str -- [in] Pointer to the null-terminated source ASCII string.

  • desc -- [out] Formatted unicode string descriptor buffer where the USB descriptor will be written.

返回:

The total length of the generated descriptor in bytes.

USB Device Constants

Device CDC ACM Constants

CDC_SEND_ENCAPSULATED_COMMAND

Defines CDC class-specific request codes.

CDC request to send an encapsulated command.

CDC_GET_ENCAPSULATED_RESPONSE

CDC request to get an encapsulated response.

CDC_SET_COMM_FEATURE

CDC request to set a communication feature.

CDC_GET_COMM_FEATURE

CDC request to get a communication feature.

CDC_CLEAR_COMM_FEATURE

CDC request to clear a communication feature.

CDC_SET_LINE_CODING

CDC request to set the line coding properties.

CDC_GET_LINE_CODING

CDC request to get the line coding properties.

CDC_SET_CONTROL_LINE_STATE

CDC request to set the control line state.

CDC_SEND_BREAK

CDC request to send a break condition.

CDC_ACM_CTRL_OVERRUN

Defines the bitmask for the SERIAL_STATE notification.

bOverRun: Received data has been discarded.

CDC_ACM_CTRL_PARITY

bParity: A parity error has occurred.

CDC_ACM_CTRL_FRAMING

bFraming: A framing error has occurred.

CDC_ACM_CTRL_RI

bRingSignal: State of ring signal detection.

CDC_ACM_CTRL_BRK

bBreak: Break condition detected.

CDC_ACM_CTRL_DSR

bTxCarrier: State of DSR signal.

CDC_ACM_CTRL_DCD

bRxCarrier: State of DCD signal.

CDC_ACM_VID

Defines basic device parameters like VID, PID, and string descriptors.

Vendor ID.

CDC_ACM_PID

Product ID.

CDC_ACM_SELF_POWERED

Device is self-powered.

CDC_ACM_REMOTE_WAKEUP_EN

Remote wakeup is enabled.

CDC_ACM_LANGID_STRING

Language ID for string descriptors (0x0409 = English

CDC_ACM_MFG_STRING

Manufacturer string.

CDC_ACM_PROD_HS_STRING

Product string for High-Speed mode.

CDC_ACM_PROD_FS_STRING

Product string for Full-Speed mode.

CDC_ACM_SN_STRING

Serial number string.

CDC_ACM_BULK_IN_EP

Defines endpoint addresses for BULK and INTERRUPT transfers.

CDC_ACM_BULK_OUT_EP
CDC_ACM_INTR_IN_EP
CDC_ACM_HS_BULK_MAX_PACKET_SIZE

Defines maximum packet sizes for different speeds and endpoint types.

High speed BULK IN & OUT maximum packet size

CDC_ACM_FS_BULK_MAX_PACKET_SIZE

Full speed BULK IN & OUT packet size

CDC_ACM_HS_BULK_IN_PACKET_SIZE

High-Speed BULK IN packet size.

CDC_ACM_HS_BULK_OUT_PACKET_SIZE

High-Speed BULK OUT packet size.

CDC_ACM_FS_BULK_IN_PACKET_SIZE

Full-Speed BULK IN packet size.

CDC_ACM_FS_BULK_OUT_PACKET_SIZE

Full-Speed BULK OUT packet size.

CONFIG_CDC_ACM_NOTIFY

Enable/Disable notification feature.

CONFIG_CDC_ACM_NOTIFY_LOOP_TEST

Enable notification loopback test mode.

CONFIG_CDC_ACM_BULK_TX_SKIP_MEMCPY

Skip memcpy BULK IN DATA from application in class

CDC_NOTIFY_SERIAL_STATE

Notification code for serial state changes.

CDC_ACM_INTR_IN_PACKET_SIZE

INTR IN packet size

CDC_ACM_INTR_IN_REQUEST_SIZE

INTR IN request size

CDC_ACM_INTR_IN_DATA_SIZE

INTR IN data size

CDC_ACM_HS_INTR_IN_INTERVAL

High speed INTR IN interval

CDC_ACM_FS_INTR_IN_INTERVAL

Full speed INTR IN interval

CDC_ACM_CTRL_BUF_SIZE

Control transfer buffer size.

CDC_ACM_LINE_CODING_SIZE

Size of the Line Coding structure.

Device Core Constants

USBD_IDX_LANGID_STR

USB device string descriptor index.

USBD_IDX_MFC_STR
USBD_IDX_PRODUCT_STR
USBD_IDX_SERIAL_STR
USBD_IDX_MS_OS_STR
USBD_SOF_INTR

USB device interrupt enable flag.

Start of (micro)Frame Interrupt (GINTSTS.Sof).

USBD_EOPF_INTR

End of Periodic Frame Interrupt (GINTSTS.EOPF).

USBD_EPMIS_INTR

Endpoint Mismatch Interrupt (GINTSTS.EPMis).

USBD_TP_TRACE_DEBUG

This define is used to trace transfer performance

USBD_MAX_NUM_INTERFACES
USBD_MAX_NUM_CONFIGURATION

USB Device Types

Device CDC ACM Types

struct usbd_cdc_acm_line_coding_t
#include <usbd_cdc_acm.h>

Structure to define the line coding properties.

This structure holds the settings for the virtual serial port, such as baud rate, stop bits, parity, and data bits.

Public Members

u32 bitrate

Data terminal rate, in bits per second.

u8 format

Stop bits: 0: 1 Stop bit, 1: 1.5 Stop bits, 2: 2 Stop bits.

u8 parity_type

Parity: 0: None, 1: Odd, 2: Even, 3: Mark, 4: Space.

u8 data_type

Data bits: 5, 6, 7, 8, or 16.

struct usbd_cdc_acm_ntf_t
#include <usbd_cdc_acm.h>

Structure for CDC ACM notifications sent to the host.

This is a packed structure used for sending notifications like SERIAL_STATE over the INTERRUPT IN endpoint.

Public Members

u8 bmRequestType

D7: Data transfer direction (1=Device-to-Host), D6-5: Type (1=Class), D4-0: Recipient (1=Interface).

u8 bNotificationType

Notification code, e.g., CDC_NOTIFY_SERIAL_STATE.

u16 wValue

Varies by notification. For SERIAL_STATE, it's 0.

u16 wIndex

Interface number.

u16 wLength

Size of the notification data payload.

u8 buf[CDC_ACM_INTR_IN_DATA_SIZE]

Notification data payload.

struct usbd_cdc_acm_cb_t
#include <usbd_cdc_acm.h>

Structure containing callback functions for the CDC ACM class.

The user application should provide an instance of this structure to handle class-specific events.

Public Members

int (*init)(void)

Called when the CDC ACM class driver initialization for application resource setup.

Return:

0 on success, non-zero on failure.

int (*deinit)(void)

Called when the CDC ACM device is de-initialized for resource cleanup.

Return:

0 on success, non-zero on failure.

int (*setup)(usb_setup_req_t *req, u8 *buf)

Called to handle class-specific SETUP requests.

Param req:

[in] Pointer to the setup request packet.

Param buf:

[out] Pointer to a buffer for data stage of control transfers.

Return:

0 on success, non-zero on failure.

int (*received)(u8 *buf, u32 len)

Called when new data is received from the host on the BULK OUT endpoint.

Param buf:

[in] Pointer to the received data buffer.

Param len:

[in] Length of the received data in bytes.

Return:

0 on success, non-zero on failure.

void (*transmitted)(u8 status)

Called when a data transmission to the host on the BULK IN endpoint is complete.

Param status:

[in] The status of the transmission.

void (*status_changed)(u8 old_status, u8 status)

Called when USB attach status changes for application to support hot-plug events.

Param old_status:

[in] The previous attach status.

Param status:

[in] The new attach status.

Device Core Types

enum usbd_state_t

USB device state.

Values:

enumerator USBD_STATE_INIT

Initial state, before enumeration.

enumerator USBD_STATE_DEFAULT

Default state, after reset.

enumerator USBD_STATE_ADDRESSED

Addressed state, after SET_ADDRESS.

enumerator USBD_STATE_CONFIGURED

Configured state, after SET_CONFIGURATION.

enumerator USBD_STATE_SUSPENDED

Suspended state.

enum usbd_attach_status_t

USB device attach status.

Values:

enumerator USBD_ATTACH_STATUS_INIT

Initial status.

enumerator USBD_ATTACH_STATUS_ATTACHED

Device is attached to the host.

enumerator USBD_ATTACH_STATUS_DETACHED

Device is detached from the host.

typedef struct _usbd_class_driver_t usbd_class_driver_t

Defines the structure for the USB class driver callbacks.

备注

All the device class driver callback functions are invoked in interrupt context. Time-consuming or blocking operations must not be executed within these callback functions.

struct usbd_ep_t
#include <usbd.h>

Defines the structure for an USB endpoint.

Public Members

u8 *xfer_buf

Pointer to the transfer buffer.

u8 *rem_xfer_buf

Pointer to the remaining part of the transfer buffer.

u32 xfer_len

Total length of the data to transfer.

u32 rem_xfer_len

Remaining length of data to transfer (used for EP0).

u32 xfer_buf_len

Total length of the class transfer buffer.

u16 mps

Maximum Packet Size for this endpoint (0-64KB).

u8 addr

Endpoint address (includes direction).

u8 num

Endpoint number (0-15).

u8 type

Endpoint type (Control, Bulk, Isochronous, Interrupt).

u8 binterval

Polling interval for the endpoint.

u8 skip_dcache_pre_clean

Skip DCache_Clean in TRX API and it will be called in class.

u8 skip_dcache_post_invalidate

Skip DCache_Invalidate when RX complete and it will be called in class.

u8 xfer_state

Current state of the class transfer.

u8 tx_zlp

Flag to indicate if a Zero-Length Packet should be sent.

u8 dis_zlp

Flag to disable Zero-Length Packet for the current transfer.

u8 is_busy

Flag indicating if the endpoint is currently busy.

struct usbd_config_t
#include <usbd.h>

Defines the core driver configuration parameters for the USB device.

Public Members

u32 nptx_max_epmis_cnt

Threshold count of EPMis interrupts for non-periodic IN transfers.

If the mismatch count exceeds this value, the GINTSTS.EPMis interrupt is handled. This is only active if USBD_EPMIS_INTR is enabled (Shared FIFO mode only).

u32 ext_intr_enable

Enables extra interrupts.

Optional USB interrupt enable flags:

  • USBD_SOF_INTR: For SOF-based timing synchronization.

  • USBD_EOPF_INTR: For ISOC transfers parity setting in slave mode.

  • USBD_EPMIS_INTR: To handle endpoint mismatches in shared FIFO mode. For restarting IN transfers, applicable to scenarios with multiple non-periodic IN endpoints.

u16 rx_fifo_depth

RxFIFO depth in dwords which must not exceed hardware limits(Dedicated FIFO mode only).

u16 ptx_fifo_depth[USB_MAX_ENDPOINTS - 1]

Depth of TxFIFO n (for n=1 to USB_MAX_ENDPOINTS-1) in dwords which must not exceed hardware limits.

ptx_fifo_depth[i] corresponds to TxFIFO i+1 (Dedicated FIFO mode only).

备注

  • For SoCs with shared USB FIFO, no FIFO depth configuration is required.

  • For SoCs with dedicated USB FIFO, observe the following constraint: rx_fifo_depth + all ptx_fifo_depth[n] <= Hardware total FIFO depth

u8 speed

USB device speed mode. See usb_speed_type_t.

  • USB_SPEED_HIGH: USB 2.0 High-Speed PHY (for HS-capable SoCs).

  • USB_SPEED_HIGH_IN_FULL: USB 2.0 PHY operating in Full-Speed mode (for HS-capable SoCs with low bandwidth applcations like UAC).

  • USB_SPEED_FULL: USB 1.1 Full-Speed transceiver (for FS-only SoCs).

u8 isr_priority

Priority of the USB interrupt.

u8 isr_in_critical

Flag to process USB ISR within a critical section.

u8 intr_use_ptx_fifo

Use Periodic TxFIFO for Interrupt IN transfers (Shared TxFIFO mode only).

u8 tp_trace

Enable/disable tracing for transfer performance.

struct usb_dev_t
#include <usbd.h>

Defines the main USB device structure.

Public Members

u64 isr_process_time_max

[Debug] Maximum ISR handler processing time

u64 isr_process_time

[Debug] Current ISR handler processing time

u64 isr_enter_period_max

[Debug] Maximum interval between two consecutive ISR processing

u64 isr_enter_period

[Debug] Current time between last two consecutive ISR processing

u64 isr_enter_time

[Debug] Timestamp of current ISR handler entry

usbd_ep_t ep0_in

Control endpoint 0 IN.

usbd_ep_t ep0_out

Control endpoint 0 OUT.

struct _usbd_class_driver_t *driver

Pointer to the active class driver.

void *pcd

Pointer to the low-level PCD (Platform Controller Driver) handle.

u32 ep0_out_intr

Previous interrupt status for EP0 OUT.

u16 ep0_data_len

Data length for the current EP0 transfer.

u8 ep0_state

Current state of the EP0 state machine.

u8 ep0_old_state

Previous state of the EP0 state machine.

u8 dev_config

Current device configuration index.

u8 dev_speed

Current device speed. See usb_speed_type_t.

u8 dev_state

Current device state. See usbd_state_t.

u8 dev_old_state

Previous device state.

u8 dev_attach_status

Current device attach status. See usbd_attach_status_t.

u8 dev_old_attach_status

Previous device attach status.

u8 test_mode

Flag indicating if the device is in a test mode.

u8 self_powered

Power source status: 0 for bus-powered, 1 for self-powered.

u8 remote_wakeup_en

Remote wakeup enable or not, 0-disabled, 1-enabled

u8 remote_wakeup

Remote wakeup flag.

u8 is_ready

Device ready or not, 0-disabled, 1-enabled

u8 is_connected

Device connected or not,0-disabled, 1-enabled

struct _usbd_class_driver_t
#include <usbd.h>

Defines the structure for the USB class driver callbacks.

备注

All the device class driver callback functions are invoked in interrupt context. Time-consuming or blocking operations must not be executed within these callback functions.

Public Members

u16 (*get_descriptor)(usb_dev_t *dev, usb_setup_req_t *req, u8 *buf)

Callback to get a descriptor during enumeration when host requests USB descriptors.

备注

The class driver must return the descriptor data buffer and length againt the wValue value of host setup request:

  • USB_DESC_TYPE_DEVICE: Device Descriptor, mandatory.

  • USB_DESC_TYPE_CONFIGURATION: Configuration Descriptor, mandatory.

  • USB_DESC_TYPE_DEVICE_QUALIFIER: Device Qualifier Descriptor, required for dual-speed (FS/HS) devices |

  • USB_DESC_TYPE_OTHER_SPEED_CONFIGURATION:Other Speed Configuration Descriptor, required for dual-speed (FS/HS) devices.

  • USB_DESC_TYPE_STRING: String descriptors (language ID, manufacturer, product, serial), optional.

Param dev:

[in] USB device.

Param req:

[in] USB setup request.

Param buf:

[out] Buffer to store the requested descriptor.

Return:

The actual length of the descriptor.

int (*set_config)(usb_dev_t *dev, u8 config)

Callback to set the device configuration.

备注

Called upon SET_CONFIGURATION request in ADDRESSED state. The device class driver must:

Param dev:

[in] USB device.

Param config:

[in] The configuration index to be set.

Return:

0 on success, non-zero on failure.

int (*clear_config)(usb_dev_t *dev, u8 config)

Callback to clear the device configuration.

备注

Called upon:

  • Core driver receives SET_CONFIGURATION control request in CONFIGURED state and needs to switch configuration.

  • Core driver receives SET_CONFIGURATION control request in non-ADDRESSED/CONFIGURED state.

  • Core driver processes enumeration complete interrupt (GINTSTS.EnumDone).

  • Core driver processes Session end interrupt (GOTGINT.SesEndDet).

  • USB core driver API usbd_deinit is called. Typically, the device class driver shall call usbd_ep_deinit to deinitialize the endpoints.

Param dev:

[in] USB device.

Param config:

[in] The configuration index to be cleared.

Return:

0 on success, non-zero on failure.

int (*setup)(usb_dev_t *dev, usb_setup_req_t *req)

Callback to handle class-specific or vendor-specific setup requests at control transfer setup phase.

  • Standard interface requests (SET_INTERFACE/GET_INTERFACE/GET_STATUS).

  • Class-specific requests per relevant class specifications.

  • Vendor-defined requests for custom devices.

Param dev:

[in] USB device.

Param req:

[in] USB setup request.

Return:

0 on success, non-zero on failure.

int (*sof)(usb_dev_t *dev)

Callback invoked at the Start-of-Frame (SOF).

Called upon SOF interrupt (GINTSTS.Sof) for timing-sensitive operations (e.g. UAC clock synchronization).

Param dev:

[in] USB device.

Return:

0 on success, non-zero on failure.

int (*ep0_data_in)(usb_dev_t *dev, u8 status)

Callback invoked when an IN data transfer on EP0 is complete.

Param dev:

[in] USB device.

Param status:

[in] Status of the completed transfer.

Return:

0 on success, non-zero on failure.

int (*ep0_data_out)(usb_dev_t *dev)

Callback invoked when an OUT data transfer on EP0 is complete.

备注

The device driver does not need to re-enable the control OUT transfer since it is automatically done in core driver.

Param dev:

[in] USB device.

Return:

0 on success, non-zero on failure.

int (*ep_data_in)(usb_dev_t *dev, u8 ep_addr, u8 status)

Callback invoked when a bulk/interrupt/isochronous IN data transfer on EP is complete.

备注

The device class driver may mark endpoint ready for next transfer or retry failed transfers.

Param dev:

[in] USB device structure.

Param ep_addr:

[in] Endpoint address.

Param status:

[in] Status of the completed transfer.

Return:

0 on success, non-zero on failure.

int (*ep_data_out)(usb_dev_t *dev, u8 ep_addr, u16 len)

Callback invoked when a bulk/interrupt/isochronous OUT data transfer on EP is complete.

备注

Typically, the device class driver shall:

  • Process received data via application callback.

  • Prepare next OUT transfer via usbd_ep_receive.

Param dev:

[in] USB device.

Param ep_addr:

[in] Endpoint address.

Param status:

[in] Status of the completed transfer.

Return:

0 on success, non-zero on failure.

void (*status_changed)(usb_dev_t *dev, u8 old_status, u8 status)

Callback invoked when USB status change. See usbd_attach_status_t.

Called upon connection state changed for hot-plug support (e.g. do reinitialization on host disconnection)

Param dev:

[in] USB device.

Param old_status:

[in] Previous status of USB device.

Param status:

[in] Current status of USB device.

Return:

None

USB Host API

USB Host Functions

Host Core Functions For Applications

int usbh_init(usbh_config_t *cfg, usbh_user_cb_t *cb)

Initialize USB host core driver with user configuration and callback.

参数:
  • cfg -- [in] USB user configuration.

  • cb -- [in] USB user callback.

返回:

0 on success, non-zero on failure.

int usbh_deinit(void)

Deinitialize USB host core driver.

返回:

0 on success, non-zero on failure.

Host Core Functions For Classes

int usbh_register_class(usbh_class_driver_t *driver)

Register a host class driver, called in class initialization function.

参数:

driver -- [in] USB class driver.

返回:

0 on success, non-zero on failure.

int usbh_unregister_class(usbh_class_driver_t *driver)

Un-register a class, called in class de-initialization function.

参数:

driver -- [in] USB class driver.

返回:

0 on success, non-zero on failure.

int usbh_open_pipe(usb_host_t *host, usbh_pipe_t *pipe, usbh_ep_desc_t *ep_desc)

Open a pipe.

参数:
  • host -- [in] Host Handle.

  • pipe -- [in] Pipe struct handle.

  • ep_desc -- [in] Endpoint descriptor handle.

返回:

0 on success, non-zero on failure.

int usbh_close_pipe(usb_host_t *host, usbh_pipe_t *pipe)

Close a pipe.

参数:
  • host -- [in] Host Handle.

  • pipe -- [in] Pipe struct handle.

返回:

0 on success, non-zero on failure.

u8 usbh_get_configuration(usb_host_t *host, usbh_dev_id_t *id)

Get the config idx by devicd id information.

参数:
  • host -- [in] Host Handle.

  • id -- [in] Device id information.

返回:

config index

int usbh_set_configuration(usb_host_t *host, u8 cfg)

Set the config index for bNumConfigurations>1 in device descriptor.

参数:
  • host -- [in] Host Handle.

  • cfg -- [in] Config index.

返回:

0 on success, non-zero on failure.

usbh_itf_data_t *usbh_get_interface_descriptor(usb_host_t *host, usbh_dev_id_t *id)

Get the interface descriptor by devicd id information.

备注

NULL means interface not found.

参数:
  • host -- [in] Host Handle.

  • id -- [in] Device id information.

返回:

interface descriptor handler.

u8 *usbh_find_next_descriptor(u8 *buf, u32 *len, u8 desc_type)

Find next standard descriptor that matches the descriptor type.

参数:
  • buf -- [in] buffer to find.

  • len -- [in] buffer length.

  • desc_type -- [in] Descriptor type.

返回:

Pointer of next standard descriptor.

u32 usbh_get_tick(usb_host_t *host)

Get the current time ticks.

参数:

host -- [in] Host Handle.

返回:

tick count.

u32 usbh_get_elapsed_ticks(usb_host_t *host, u32 start_tick)

Get the elapse ticks.

参数:
  • host -- [in] Host Handle.

  • start_tick -- [in] Start tick count.

返回:

Tick count.

u32 usbh_get_current_frame_number(usb_host_t *host)

Get current frame number.

参数:

host -- [in] Host Handle.

返回:

Current frame number.

u32 usbh_get_elapsed_frame_cnt(usb_host_t *host, u32 start_frame)

Get the elapse frame number.

参数:
  • host -- [in] Host Handle.

  • start_frame -- [in] Start frame number.

返回:

Tick count.

usbh_urb_state_t usbh_get_urb_state(usb_host_t *host, usbh_pipe_t *pipe)

Get the URB state.

参数:
  • host -- [in] Host handle.

  • pipe -- [in] Pipe struct handle.

返回:

URB state.

int usbh_notify_composite_class_state_change(usb_host_t *host, u8 pipe_num, u8 owner)

Notify composite class state change.

参数:
  • host -- [in] Host Handle.

  • pipe_num -- [in] Pipe number.

  • owner -- [in] Notify owner class.

返回:

0 on success, non-zero on failure.

int usbh_ctrl_set_interface(usb_host_t *host, u8 itf_num, u8 alt_setting)

Send SET_INTERFACE standard request to device.

参数:
  • host -- [in] Host Handle.

  • itf_num -- [in] Interface number.

  • alt_setting -- [in] Interface alternate setting number.

返回:

0 on success, non-zero on failure.

int usbh_ctrl_set_feature(usb_host_t *host, u8 value)

Send SET_FEATURE standard request to device (remote wakeup feature,..)

参数:
  • host -- [in] Host handler.

  • value -- [in] Feature value.

返回:

0 on success, non-zero on failure.

int usbh_ctrl_clear_feature(usb_host_t *host, u8 ep_num)

Send CLEAR_FEATURE standard request to device.

参数:
  • host -- [in] Host Handle.

  • ep_num -- [in] Endpoint number.

返回:

0 on success, non-zero on failure.

int usbh_ctrl_request(usb_host_t *host, usbh_setup_req_t *req, u8 *buf)

Send control request to device.

参数:
  • host -- [in] Host Handle.

  • req -- [in] Control request.

  • buf -- [in] Data buffer.

返回:

0 on success, non-zero on failure.

int usbh_transfer_data(usb_host_t *host, usbh_pipe_t *pipe)

Start one data transfer.

参数:
  • host -- [in] Host Handle.

  • pipe -- [in] Pipe struct handle.

返回:

0 on success, non-zero on failure.

u32 usbh_get_last_transfer_size(usb_host_t *host, usbh_pipe_t *pipe)

Get the last transfer data size of specific pipe.

参数:
  • host -- [in] Host Handle.

  • pipe -- [in] Pipe struct handle.

返回:

None

int usbh_transfer_process(usb_host_t *host, usbh_pipe_t *pipe)

Start one transfer and handle result.

参数:
  • host -- [in] Host Handle.

  • pipe -- [in] Pipe struct handle.

返回:

0 on success, non-zero on failure.

int usbh_enable_nak_interrupt(usb_host_t *host, u8 pipe_num)

Enable NAK mask for the pipe.

参数:
  • host -- [in] Host Handle.

  • pipe_num -- [in] Pipe number.

返回:

0 on success, non-zero on failure.

int usbh_check_nak_timeout(usb_host_t *host, u8 pipe_num, u32 tick_cnt)

Check NAK time out.

参数:
  • host -- [in] Host Handle.

  • pipe_num -- [in] Pipe number.

  • tick_cnt -- [in] Timout tick count.

返回:

0 on success, non-zero on failure.

int usbh_increase_busy_cnt(usb_host_t *host, u8 pipe_num, u8 step)

Increase pipe busy count.

参数:
  • host -- [in] Host Handle.

  • pipe_num -- [in] Pipe number.

  • step -- [in] Increase step.

返回:

0 on success, non-zero on failure.

int usbh_prepare_retransfer(usb_host_t *host, u8 pipe_num)

Prepare for retransfer.

参数:
  • host -- [in] Host Handle.

  • pipe_num -- [in] Pipe number.

返回:

0 on success, non-zero on failure.

void usbh_suspend(void)

USB Host enter suspend.

返回:

None

void usbh_resume(void)

USB Host exit suspend.

返回:

None

int usbh_select_test_mode(u8 mode)

USB Host Port Test Control.

参数:

mode -- [in] Test mode.

返回:

0 on success, non-zero on failure.

USB Host Constants

Host Core Constants

USBH_DEV_ID_MATCH_VID

USBH_DEV_ID_MATCH_XX used in usbh_dev_id_t to specify which fields to match when searching for a device or interface.

USBH_DEV_ID_MATCH_PID
USBH_DEV_ID_MATCH_DEV_CLASS
USBH_DEV_ID_MATCH_DEV_SUBCLASS
USBH_DEV_ID_MATCH_DEV_PROTOCOL
USBH_DEV_ID_MATCH_ITF_CLASS
USBH_DEV_ID_MATCH_ITF_SUBCLASS
USBH_DEV_ID_MATCH_ITF_PROTOCOL
USBH_DEV_ID_MATCH_DEVICE
USBH_DEV_ID_MATCH_DEV_INFO
USBH_DEV_ID_MATCH_ITF_INFO
USBH_TP_TRACE_DEBUG
USBH_MAX_CLASS_NUM
USBH_MAX_HUB_PORT
USBH_EVENT_OWNER
USBH_SOF_INTR

Start of (micro)Frame GINTSTS.Sof. For host class driver to handle timing issues in SOF callback of usbh_class_driver_t

usbh_notify_class_state_change(host, pipe_num)

Notifies the host core that the class state has changed.

This is a convenience macro for usbh_notify_composite_class_state_change with owner set to USBH_EVENT_OWNER.

参数:
  • host -- Pointer to the usb_host_t.

  • pipe_num -- The pipe number associated with the change.

USB Host Types

Host Core Types

enum usbh_ep_xfer_state_t

Defines the transfer states for an endpoint's pipe.

Values:

enumerator USBH_EP_XFER_IDLE

The endpoint is idle and ready for a new transfer.

enumerator USBH_EP_XFER_WAIT_SOF

For periodic transfers, waiting for the correct SOF interval. Check interval in SOF callback.

enumerator USBH_EP_XFER_START

A new transfer is starting.

enumerator USBH_EP_XFER_BUSY

The endpoint is currently busy with a transfer.

enumerator USBH_EP_XFER_ERROR

An error occurred during the last transfer.

enumerator USBH_EP_XFER_STATE_MAX

Sentinel value for state validation.

enum usbh_state_t

Defines the connection states of the USB host.

Values:

enumerator USBH_STATE_IDLE

The host is idle.

enumerator USBH_STATE_DETACHED

A device has been detached.

enumerator USBH_STATE_ATTACH

A device has been attached and is being enumerated.

enumerator USBH_STATE_SETUP

The device is in the setup/configured phase.

enumerator USBH_STATE_MAX

Sentinel value for state validation.

enum usbh_urb_state_t

Defines the states of a USB Request Block (URB).

Values:

enumerator USBH_URB_IDLE

The URB is idle, no transfer is active.

enumerator USBH_URB_DONE

The URB has completed successfully.

enumerator USBH_URB_BUSY

The URB is currently being processed.

enumerator USBH_URB_ERROR

The URB completed with an error.

enumerator USBH_URB_STALL

The URB resulted in a STALL condition.

enum usbh_msg_t

Defines message types for user process callbacks of usbh_user_cb_t.

Values:

enumerator USBH_MSG_USER_SET_CONFIG

Message to request user to set the configuration.

enumerator USBH_MSG_CONNECTED

Message indicating a device has been successfully connected and configured.

enumerator USBH_MSG_DISCONNECTED

Message indicating a device has been disconnected.

enumerator USBH_MSG_ERROR

Message indicating a general error occurred.

enum usbh_tick_source_t

Defines the source for the USB host tick counter.

Values:

enumerator USBH_SW_TICK

Use a software-based timer (e.g., system timestamp) as the tick source. It does not require responding to additional interrupts, resulting in lower CPU usage. However, there may be deviations from SOF counting. Suitable for applications with low CPU usage requirements or when timing accuracy does not need to match SOF counting precision.

enumerator USBH_SOF_TICK

Use the SOF (Start-of-Frame) interrupt as the tick source. Since it needs to periodically respond to SOF interrupts, CPU usage is higher, but timing accuracy matches SOF counting precision.

enumerator USBH_TICK_ERROR
typedef struct _usbh_itf_data_t usbh_itf_data_t

A structure to hold information about all alternate settings for a single interface number.

This forms a linked list where each node represents a unique interface number. Inside each node, it points to another linked list (itf_desc_array) of all alternate settings for that interface.

typedef struct _usb_host_t usb_host_t

USB host.

struct usbh_desc_header_t
#include <usbh.h>

Generic USB descriptor header.

All standard USB descriptors start with these two fields.

Public Members

u8 bLength

Size of this descriptor in bytes.

u8 bDescriptorType

Descriptor type.

struct usbh_dev_desc_t
#include <usbh.h>

USB standard device descriptor structure.

Public Members

u8 bLength

Size of this descriptor in bytes.

u8 bDescriptorType

DEVICE Descriptor Type.

u16 bcdUSB

USB specification version number (e.g., 0x0200 for USB 2.0).

u8 bDeviceClass

Class code (assigned by the USB-IF).

u8 bDeviceSubClass

Subclass code (assigned by the USB-IF).

u8 bDeviceProtocol

Protocol code (assigned by the USB-IF). If equal to 0, each interface specifies its own class code if equal to 0xFF, the class code is vendor specified. Otherwise field is valid class code.

u8 bMaxPacketSize

Maximum packet size for endpoint zero (only 8, 16, 32, or 64 are valid).

u16 idVendor

Vendor ID (assigned by the USB-IF).

u16 idProduct

Product ID (assigned by the manufacturer).

u16 bcdDevice

Device release number in BCD format.

u8 iManufacturer

Index of string descriptor describing manufacturer.

u8 iProduct

Index of string descriptor describing product.

u8 iSerialNumber

Index of string descriptor for the serial number.

u8 bNumConfigurations

Number of possible configurations.

struct usbh_dev_bos_t
#include <usbh.h>

USB standard Binary Device Object Store (BOS) descriptor structure.

Public Members

u8 bLength

Size of this descriptor in bytes.

u8 bDescriptorType

BOS Descriptor Type.

u16 wTotalLength

Total length of the BOS descriptor and all its sub-descriptors.

u8 bNumDeviceCaps

The number of device capability descriptors in the BOS.

struct usbh_ep_desc_t
#include <usbh.h>

USB standard endpoint descriptor structure.

Public Members

u8 bLength

Size of this descriptor in bytes.

u8 bDescriptorType

ENDPOINT Descriptor Type.

u8 bEndpointAddress

The address of the endpoint on the USB device.

u8 bmAttributes

Endpoint attributes (transfer type, etc.).

u16 wMaxPacketSize

Maximum packet size this endpoint is capable of sending or receiving.

u8 bInterval

Interval for polling endpoint for data transfers.

struct usbh_itf_desc_t
#include <usbh.h>

USB standard interface descriptor structure.

Public Members

u8 bLength

Size of this descriptor in bytes.

u8 bDescriptorType

INTERFACE Descriptor Type.

u8 bInterfaceNumber

Number of this interface.

u8 bAlternateSetting

Value used to select this alternate setting.

u8 bNumEndpoints

Number of endpoints used by this interface (excluding endpoint zero).

u8 bInterfaceClass

Class code (assigned by the USB-IF).

u8 bInterfaceSubClass

Subclass code (assigned by the USB-IF).

u8 bInterfaceProtocol

Protocol code (assigned by the USB-IF).

u8 iInterface

Index of string descriptor describing this interface.

usbh_ep_desc_t *ep_desc_array

Endpoint descriptors

struct _usbh_itf_data_t
#include <usbh.h>

A structure to hold information about all alternate settings for a single interface number.

This forms a linked list where each node represents a unique interface number. Inside each node, it points to another linked list (itf_desc_array) of all alternate settings for that interface.

Public Members

struct _usbh_itf_data_t *next

Pointer to the next info structure for a different interface number but has the same class/subclass/protocol.

usbh_itf_desc_t *itf_desc_array

Pointer to a linked list of all alternate settings for this interface number (bAlternateSetting 0, 1, 2...).

u8 *raw_data

Pointer to the start of the raw interface descriptor data for class-specific parsing.

u32 raw_data_len

The total length of the entire interface descriptor in bytes.

u8 alt_setting_cnt

Count of alternate settings for this interface number.

struct usbh_cfg_desc_t
#include <usbh.h>

USB configuration descriptor.

Public Members

u8 bLength

Size of this descriptor in bytes.

u8 bDescriptorType

CONFIGURATION Descriptor Type.

u16 wTotalLength

Total length of data returned for this configuration.

u8 bNumInterfaces

The number of interfaces supported by this configuration.

u8 bConfigurationValue

Value to use as an argument to select this configuration.

u8 iConfiguration

Index of string descriptor describing this configuration.

u8 bmAttributes

Configuration characteristics (D7:Bus Powered, D6:Self Powered, D5:Remote Wakeup, D4..0 Reserved (0)).

u8 bMaxPower

Maximum power consumption of the device from the bus in 2mA units.

usbh_itf_data_t *itf_data_array

Save all interfaces info in this struct, total count is defined by bNumInterfaces, each interface is indentified by bInterfaceNumber: 0/1/2...

struct usbh_hub_desc_t
#include <usbh.h>

USB standard hub descriptor structure. (USB 2.0 Spec, 11.23.2.1).

Public Members

u8 bLength

Size of this descriptor in bytes.

u8 bDescriptorType

HUB Descriptor Type.

u8 bNbrPorts

Number of downstream ports that this hub supports.

u16 wHubCharacteristics

Hub characteristics (power switching, over-current protection, etc.). D1...D0: Logical Power Switching Mode D2: Identifies a Compound Device D4...D3: Over-current Protection Mode D6...D5: TT Think TIme D7: Port Indicators Supported D15...D8: Reserved

u8 bPwrOn2PwrGood

Time (in 2ms intervals) from when power is turned on to when power is good.

u8 bHubContrCurrent

Maximum current requirements of the hub controller in mA. add 1 bit for hub status change; round to bytes

u8 DeviceRemovable[(USBH_MAX_HUB_PORT + 1 + 7) / 8]

Indicates if a port has a removable device attached. Bit 0: Reserved for future use. Bit 1: Port 1 Bit n: Port n (implementation-dependent, up to a maximum of 255 ports).

u8 PortPwrCtrlMask[(USBH_MAX_HUB_PORT + 1 + 7) / 8]

Port power control mask (obsolete). This field exists for reasons of compatibility with software written for 1.0 compliant devices. All bits in this field should be set to 1B. This field has one bit for each port on the hub with additional pad bits, if necessary, to make the number of bits in the field an integer multiple of 8.

union usbh_setup_req_t
#include <usbh.h>

Union for a standard USB setup request packet.

Public Members

u32 d32[2]

64-bit access to the setup packet data.

usb_setup_req_t req

Access as a structured setup request.

struct usbh_event_msg_t
#include <usbh.h>

Packed structure for a USB event message.

Public Members

u16 tick

Tick count when the event occurred.

u8 pipe_num

Pipe number associated with the event.

u8 type

Message type, corresponds to usbh_event_type_t.

u8 owner

Owner of the message (e.g., core, class).

union usbh_event_t
#include <usbh.h>

Union for a USB event.

Public Members

u32 d32

32-bit access to the event data.

usbh_event_msg_t msg

Access as a structured event message.

struct usbh_config_t
#include <usbh.h>

USB host user configuration structure.

Public Members

u32 ext_intr_enable

Allows class drivers to enable optional interrupts, (e.g., USBH_SOF_INTR is used for host class driver to handle timing issues in SOF callback).

u16 rx_fifo_depth

RxFIFO depth in dwords (Dedicated FIFO only). Min value 16 and max value restricted by SoC hardware.

u16 nptx_fifo_depth

Non-periodic TxFIFO depth in dwords (Dedicated FIFO only). Min value 16 and max value restricted by SoC hardware.

u16 ptx_fifo_depth

Periodic TxFIFO depth in dwords (Dedicated FIFO only). Min value 16 and max value restricted by SoC hardware.

u8 isr_priority

USB ISR priority.

u8 isr_in_critical

Flag to process USB ISR within a critical section (0: Disable, 1: Enable).

u8 main_task_priority

USB main task priority, the main task processes the USB host messages.

u8 speed

USB speed mode. See usb_speed_type_t.

  • USB_SPEED_HIGH: USB 2.0 High-Speed mode(for HS-capable SoCs).

  • USB_SPEED_HIGH_IN_FULL: USB 2.0 PHY operating in Full-Speed mode(for HS-capable SoCs with low bandwidth applcations like UAC).

  • USB_SPEED_FULL: USB 1.1 Full-Speed mode(for FS-only SoCs).

u8 tick_source

Tick source for getting the usb host tick of USB host core driver, see usbh_tick_source_t. Which is used to trigger periodic transfers based on the endpoint interval and to detect transfer timeouts.

u8 xfer_retry_max_cnt

Maximum number of retries for a failed transfer.

u8 hub_support

Support 1-level HUB (0: Disable, 1: Enable).

u8 tp_trace

Enable/disable tracing for transfer performance.

struct usbh_pipe_t
#include <usbh.h>

USB pipe structure for managing data transfers to/from an endpoint.

Public Members

u8 *xfer_buf

Pointer to the transfer buffer.

u32 xfer_len

Total length of the data to transfer.

u32 frame_num

Frame number for the transfer (from HFNUM register, max 0x3FFF).

u32 tick

Host tick count at the start of the transfer (based on SOF or timestamp).

u16 max_timeout_tick

Maximum wait timeout in ticks for this transfer.

u16 ep_interval

Endpoint polling interval in ticks.

u16 ep_mps

Endpoint Maximum Packet Size (0-64KB).

u8 ep_trans

Number of transactions per microframe (1-3, for HS isochronous).

u8 ep_is_in

Endpoint direction: 1 for IN, 0 for OUT.

u8 ep_addr

Endpoint address (including direction bit).

u8 ep_type

Endpoint type, USB_CH_EP_TYPE_XXX (Control, Bulk, Interrupt, Isochronous).

u8 pipe_num

Host pipe/channel number assigned to this endpoint.

u8 xfer_state

Current transfer state. See usbh_ep_xfer_state_t.

u8 trx_zlp

Flag to indicate if a Zero-Length Packet is required, only for BULK xfer with xfer_len is N*mps.

u8 retry_cnt

Current retry count for the transfer.

struct usbh_dev_id_t
#include <usbh.h>

Structure for defining device/interface properties to match against.

This is used by class drivers to identify supported devices.

Public Members

u16 mMatchFlags
u16 idVendor
u16 idProduct
u8 bDeviceClass
u8 bDeviceSubClass
u8 bDeviceProtocol
u8 bInterfaceClass
u8 bInterfaceSubClass
u8 bInterfaceProtocol
struct usbh_class_driver_t
#include <usbh.h>

Structure defining the interface for a USB class driver.

Public Members

const usbh_dev_id_t *id_table

A table of device IDs that this driver supports.

int (*attach)(struct _usb_host_t *host)

Called after SET_CONFIGURATION request when a supported device is attached.

Param host:

[in] USB host.

Return:

0 on success, non-zero on failure.

int (*detach)(struct _usb_host_t *host)

Called when a supported device is detached.

Param host:

[in] USB host.

Return:

0 on success, non-zero on failure.

int (*setup)(struct _usb_host_t *host)

Called after attach to handle class-specific standard control requests.

Param host:

[in] USB host.

Return:

0 on success, non-zero on failure.

int (*process)(struct _usb_host_t *host, u32 msg)

Main processing loop for the class driver after class setup to process class-specific transfers.

Param host:

[in] USB host.

Param msg:

[in] usbh_msg_t.

Return:

0 on success, non-zero on failure.

int (*sof)(struct _usb_host_t *host)

Called at each Start-of-Frame (SOF) interrupt for class-specific timing process.

Param host:

[in] USB host.

Return:

0 on success, non-zero on failure.

int (*completed)(struct _usb_host_t *host, u8 pipe)

Called when a transfer on a specific pipe completes.

Param host:

[in] USB host.

Param pipe:

[in] Pipe number.

Return:

0 on success, non-zero on failure.

struct usbh_user_cb_t
#include <usbh.h>

Structure defining user-level callbacks.

Public Members

int (*process)(struct _usb_host_t *host, u8 msg)

Callback to handle class-independent events in the application.

Param host:

[in] USB host.

Param msg:

[in] usbh_msg_t.

Return:

0 on success, non-zero on failure.

int (*validate)(struct _usb_host_t *host, u8 cfg_max)

Callback to validate a device when multiple devices are connected to a hub.

备注

The class can get all the config descriptor and check the interface class. if find the device, return HAL_OK, the enum process will use this device as the target device, else return !HAL_OK, the enum process will discard this device, and switch to check next hub port.

Param host:

[in] USB host.

Param cfg_max:

[in] bNumConfigurations.

Return:

0 on success, non-zero on failure.

struct _usb_host_t
#include <usbh.h>

USB host.

ISR Time Tracing

These fields are used for debugging time-sensitive transfers (like isochronous for audio applications) by measuring the execution time of the interrupt handler. Enabled by tp_trace in usbh_config_t.

  • if the isr_process_time is relatively large, check whether the callback of the class has taken a long time.

  • if the isr_enter_period is relatively large, check whether there is an operation to mask interrupts in the class.

u64 isr_enter_time

[Debug] Record the timestamp of interrupt handler entry.

u64 isr_enter_period

[Debug] The interval between two consecutive interrupt processing.

u64 isr_enter_period_max

[Debug] The maximum value of the interval between two consecutive interrupt processing.

u64 isr_process_time

[Debug] Time consumption for a complete interrupt handler processing.

u64 isr_process_time_max

[Debug] The maximum time recorded for a complete interrupt handler processing

Public Members

const usbh_dev_id_t *dev_id

Pointer to the active device ID.

usbh_dev_desc_t *dev_desc

Pointer to the device's descriptor.

usbh_user_cb_t *cb

Pointer to the user-provided callbacks.

void *core

Pointer for USB host core.

u8 dev_addr

The address of the attached device.

u8 dev_speed

The speed of the attached device.

u8 connect_state

The current connection state. See usbh_state_t.