USB Device

Description

Gecko USB device protocol stack.

The source files for the USB device stack resides in the usb directory and follows the naming convention: em_usbd nnn .c/h.


Introduction

The USB device protocol stack provides an API which makes it possible to create USB devices with a minimum of effort. The device stack supports control, bulk, interrupt and isochronous transfers.

The stack is highly configurable to suit various needs, it does also contain useful debugging features together with several demonstration projects to get you started fast.

We recommend that you read through this documentation, then proceed to build and test a few example projects before you start designing your own device.


The device stack API

This section contains brief descriptions of the functions in the API. You will find detailed information on input and output parameters and return values by clicking on the hyperlinked function names. It is also a good idea to study the code in the USB demonstration projects.

Your application code must include one header file: em_usb.h .

All functions defined in the API can be called from within interrupt handlers.

The USB stack use a hardware timer to keep track of time. TIMER0 is the default choice, refer to Configuring the device stack for other possibilities. Your application must not use the selected timer.

Pitfalls:
The USB peripheral will fill your receive buffers in quantities of WORD's (4 bytes). Transmit and receive buffers must be WORD aligned, in addition when allocating storage for receive buffers, round size up to next WORD boundary. If it is possible that the host will send more data than your device expects, round buffer size up to the next multiple of maxpacket size for the relevant endpoint to avoid data corruption.

Transmit buffers passed to USBD_Write() must be statically allocated because USBD_Write() only initiates the transfer. When the host decide to actually perform the transfer, your data must be available.


USBD_Init()
This function is called to register your device and all its properties with the device stack. The application must fill in a USBD_Init_TypeDef structure prior to calling. Refer to DeviceInitCallbacks for the optional callback functions defined within this structure. When this function has been called your device is ready to be enumerated by the USB host.

USBD_Read() , USBD_Write()
These functions initiate data transfers.
USBD_Read() initiate a transfer of data from host to device (an OUT transfer in USB terminology).
USBD_Write() initiate a transfer of data from device to host (an IN transfer).

When the USB host actually performs the transfer, your application will be notified by means of a callback function which you provide (optionally). Refer to TransferCallback for details of the callback functionality.

USBD_AbortTransfer() , USBD_AbortAllTransfers()
These functions terminate transfers that are initiated, but has not yet taken place. If a transfer is initiated with USBD_Read() or USBD_Write(), but the USB host never actually peform the transfers, these functions will deactivate the transfer setup to make the USB device endpoint hardware ready for new (and potentially) different transfers.

USBD_Connect() , USBD_Disconnect()
These functions turns the data-line (D+ or D-) pullup on or off. They can be used to force reenumeration. It's good practice to delay at least one second between USBD_Disconnect() and USBD_Connect() to allow the USB host to unload the currently active device driver.

USBD_EpIsBusy()
Check if an endpoint is busy.

USBD_StallEp() , USBD_UnStallEp()
These functions stalls or un-stalls an endpoint. This functionality may not be needed by your application, but the USB device stack use them in response to standard setup commands SET_FEATURE and CLEAR_FEATURE. They may be useful when implementing some USB classes, e.g. a mass storage device use them extensively.

USBD_RemoteWakeup()
Used in SUSPENDED state (see USB_Status_TypeDef ) to signal resume to host. It's the applications responsibility to adhere to the USB standard which states that a device can not signal resume before it has been SUSPENDED for at least 5 ms. The function will also check the configuration descriptor defined by the application to see if it is legal for the device to signal resume.

USBD_GetUsbState()
Returns the device USB state (see USBD_State_TypeDef ). Refer to Figure 9-1. "Device State Diagram" in the USB revision 2.0 specification.

USBD_GetUsbStateName()
Returns a text string naming a given USB device state.

USBD_SafeToEnterEM2()
Check if it is ok to enter energy mode EM2. Refer to the Energy-saving modes section for more information.


The transfer complete callback function:

USB_XferCompleteCb_TypeDef() is called when a transfer completes. It is called with three parameters, the status of the transfer, the number of bytes transferred and the number of bytes remaining. It may not always be needed to have a callback on transfer completion, but you should keep in mind that a transfer may be aborted when you least expect it. A transfer will be aborted if host stalls the endpoint, if host resets your device, if host unconfigures your device or if you unplug your device cable and the device is selfpowered. USB_XferCompleteCb_TypeDef() is also called if your application use USBD_AbortTransfer() or USBD_AbortAllTransfers() calls.

Note
This callback is called from within an interrupt handler with interrupts disabled.


Optional callbacks passed to the stack via the USBD_Init() function:

These callbacks are all optional, and it is up to the application programmer to decide if the application needs the functionality they provide.

Note
These callbacks are all called from within an interrupt handler with interrupts disabled.

USBD_UsbResetCb_TypeDef() is called each time reset signalling is sensed on the USB wire.


USBD_SofIntCb_TypeDef() is called with framenumber as a parameter on each SOF interrupt.


USBD_DeviceStateChangeCb_TypeDef() is called whenever the device state change. Useful for detecting e.g. SUSPENDED state change in order to reduce current consumption of buspowered devices. The USB HID keyboard example project has a good example on how to use this callback.


USBD_IsSelfPoweredCb_TypeDef() is called by the device stack when host queries the device with a standard setup GET_STATUS command to check if the device is currently selfpowered or buspowered. This feature is only applicable on selfpowered devices which also works when only buspower is available.


USBD_SetupCmdCb_TypeDef() is called each time a setup command is received from host. Use this callback to override or extend the default handling of standard setup commands, and to implement class or vendor specific setup commands. The USB HID keyboard example project has a good example on how to use this callback.


Utility functions:

USB_PUTCHAR() Transmit a single char on the debug serial port.

USB_PUTS() Transmit a zero terminated string on the debug serial port.

USB_PRINTF() Transmit "printf" formated data on the debug serial port.

USB_GetErrorMsgString() Return an error message string for a given error code.

USB_PrintErrorMsgString() Format and print a text string given an error code, prepends an optional user supplied leader string.

USBTIMER_DelayMs() Active wait millisecond delay function. Can also be used inside interrupt handlers.

USBTIMER_DelayUs() Active wait microsecond delay function. Can also be used inside interrupt handlers.

USBTIMER_Init() Initialize the timer system. Called by USBD_Init(), but your application must call it again to reinitialize whenever you change the HFPERCLK frequency.

USBTIMER_Start() Start a timer. You can configure the USB device stack to provide any number of timers. The timers have 1 ms resolution, your application is notified of timeout by means of a callback.

USBTIMER_Stop() Stop a timer.


Configuring the device stack

Your application must provide a header file named usbconfig.h . This file must contain the following #define's:

#define USB_DEVICE       // Compile the stack for device mode.
#define NUM_EP_USED n    // Your application use 'n' endpoints in
                         // addition to endpoint 0. 


usbconfig.h may define the following items:

#define NUM_APP_TIMERS n // Your application needs 'n' timers

#define DEBUG_USB_API    // Turn on API debug diagnostics.

// Some utility functions in the API needs printf. These
// functions have "print" in their name. This macro enables
// these functions.
#define USB_USE_PRINTF   // Enable utility print functions.

// Define a function for transmitting a single char on the serial port.
extern int RETARGET_WriteChar(char c);
#define USER_PUTCHAR  RETARGET_WriteChar

#define USB_TIMER USB_TIMERn  // Select which hardware timer the USB stack
                              // is allowed to use. Valid values are n=0,1,2...
                              // corresponding to TIMER0, TIMER1, ...
                              // If not specified, TIMER0 is used

#define USB_VBUS_SWITCH_NOT_PRESENT  // Hardware does not have a VBUS switch

#define USB_CORECLK_HFRCO   // Devices in the Happy family use USHFRCO as USB
                            // clock thus supporting crystal-less USB operation.
                            // The Cortex core can be clocked from HFRCO or
                            // HFXO. Define this macros to use HFRCO as core
                            // clock, default is HFXO.


You are strongly encouraged to start application development with DEBUG_USB_API turned on. When DEBUG_USB_API is turned on and USER_PUTCHAR is defined, useful debugging information will be output on the development kit serial port. Compiling with the DEBUG_EFM_USER flag will also enable all asserts in both emlib and in the USB stack. If asserts are enabled and USER_PUTCHAR defined, assert texts will be output on the serial port.

Your application must include retargetserial.c if DEBUG_USB_API is defined and retargetio.c if USB_USE_PRINTF is defined. These files reside in the drivers directory in the software package for your development board. Refer to Energy-saving modes for energy-saving mode configurations.


Giant GG11 Gecko's are very flexible in terms of using different clock sources to clock the USB peripheral. The clock source selected must be 48MHz (2500 ppm). Select one of the following macros:

In usbconfig.h:

#define   USB_CLKSRC_HFXO        // Use HFXO as USB clock (must be 48MHz)
#define   USB_CLKSRC_USHFRCO     // Use USHFRCO as USB clock
#define   USB_CLKSRC_HFRCODPLL   // Use HFRCO and DPLL as USB clock

// If DPLL is selected, additional settings are required. Here are two examples:

// Using DPLL with 32 kHz LFXO as reference clock:
#define USB_DPLL_FREQUENCY    48005120UL
#define USB_DPLL_M            0U
#define USB_DPLL_N            1464U
#define USB_DPLL_SRC          USB_DPLL_SRC_LFXO

// Using DPLL with 50 MHz HFXO as reference clock:
#define USB_DPLL_FREQUENCY    48000000UL
#define USB_DPLL_M            349U
#define USB_DPLL_N            335U
#define USB_DPLL_SRC          USB_DPLL_SRC_HFXO


Energy-saving modes

The device stack provides two energy saving levels. The first level is to set the USB peripheral in energy saving mode, the next level is to enter Energy Mode 2 (EM2). These energy saving modes can be applied when the device is suspended by the USB host, or when when the device is not connected to a USB host. In addition to this an application can use energy modes EM1 and EM2. There are no restrictions on when EM1 can be entered, EM2 can only be entered when the USB device is suspended or detached from host.

Energy-saving modes are selected with a #define in usbconfig.h , default selection is to not use any energy saving modes.

#define USB_PWRSAVE_MODE (USB_PWRSAVE_MODE_ONSUSPEND | USB_PWRSAVE_MODE_ENTEREM2)

There are three flags available, the flags can be or'ed together as shown above.

#define USB_PWRSAVE_MODE_ONSUSPEND
Set USB peripheral in low power mode on suspend.

#define USB_PWRSAVE_MODE_ONVBUSOFF
Set USB peripheral in low power mode when not attached to a host. This mode assumes that the internal voltage regulator is used and that the VREGI pin of the chip is connected to VBUS. This option can not be used with bus-powered devices.

#define USB_PWRSAVE_MODE_ENTEREM2
Enter EM2 when USB peripheral is in low power mode.

When the USB peripheral is set in low power mode, it must be clocked by a 32kHz clock. Both LFXO and LFRCO can be used, but only LFXO guarantee USB specification compliance. Selection is done with a #define in usbconfig.h .

#define USB_USBC_32kHz_CLK   USB_USBC_32kHz_CLK_LFXO 

Two flags are available, USB_USBC_32kHz_CLK_LFXO and USB_USBC_32kHz_CLK_LFRCO . USB_USBC_32kHz_CLK_LFRCO is selected by default.

The USB HID keyboard and Mass Storage device example projects demonstrate different energy-saving modes.

Example 1: Leave all energy saving to the stack, the device enters EM2 on suspend and when detached from host.

In usbconfig.h:

#define USB_PWRSAVE_MODE (USB_PWRSAVE_MODE_ONSUSPEND | USB_PWRSAVE_MODE_ONVBUSOFF | USB_PWRSAVE_MODE_ENTEREM2)


Example 2: Let the stack control energy saving in the USB periheral but let your application control energy modes EM1 and EM2.

In usbconfig.h:

#define USB_PWRSAVE_MODE (USB_PWRSAVE_MODE_ONSUSPEND | USB_PWRSAVE_MODE_ONVBUSOFF)

In application code:

if ( USBD_SafeToEnterEM2() ) {
  EMU_EnterEM2(true);
} else {
  EMU_EnterEM1();
} 


Giant GG11 and Happy Gecko's have further energy saving modes (LEM). These are activated by default, but the clocksource of the LEM module is configurable.

In usbconfig.h:

#define USB_USBLEM_CLK    USB_USBLEM_CLK_LFXO

Two clock sources are available, USB_USBLEM_CLK_LFXO and USB_USBLEM_CLK_LFRCO . Clock source USB_USBLEM_CLK_LFRCO is selected by default.


Vendor unique device example application

This example represents the most simple USB device imaginable. It's purpose is to turn user LED's on or off under control of vendor unique setup commands. The device will rely on libusb device driver on the host, a host application EFM32-LedApp.exe is bundled with the example.

The main() is really simple !

#include "em_usb.h"

#include "descriptors.h"

int main( void )
{
  BSP_Init(BSP_INIT_DEFAULT); // Initialize DK board register access
  CMU_CLOCK_SELECT_SET(HF, HFXO);
  BSP_LedsSet(0);             // Turn off all LED's

  ConsoleDebugInit();         // Initialize UART for debug diagnostics

  USB_PUTS("\nEFM32 USB LED Vendor Unique Device example\n");

  USBD_Init(&initstruct);     // GO !

  //When using a debugger it is pratical to uncomment the following three
  //lines to force host to re-enumerate the device.

  //USBD_Disconnect();
  //USBTIMER_DelayMs(1000);
  //USBD_Connect();

  for (;;) {}
} 


Configure the device stack in usbconfig.h :

#define USB_DEVICE                        // Compile stack for device mode.

// **************************************************************************
**                                                                         **
** Specify number of endpoints used (in addition to EP0).                  **
**                                                                         **
*****************************************************************************
#define NUM_EP_USED 0                     // EP0 is the only endpoint used.

// **************************************************************************
**                                                                         **
** Configure serial port debug output.                                     **
**                                                                         **
*****************************************************************************
// Prototype a function for transmitting a single char on the serial port.
extern int RETARGET_WriteChar(char c);
#define USER_PUTCHAR RETARGET_WriteChar

// Enable debug diagnostics from API functions (illegal input params etc.)
#define DEBUG_USB_API 


Define device properties and fill in USB initstruct in descriptors.h :

SL_ALIGN(4)
static const USB_DeviceDescriptor_TypeDef deviceDesc SL_ATTRIBUTE_ALIGN(4)=
{
  .bLength            = USB_DEVICE_DESCSIZE,
  .bDescriptorType    = USB_DEVICE_DESCRIPTOR,
  .bcdUSB             = 0x0200,
  .bDeviceClass       = 0xFF,
  .bDeviceSubClass    = 0,
  .bDeviceProtocol    = 0,
  .bMaxPacketSize0    = USB_FS_CTRL_EP_MAXSIZE,
  .idVendor           = 0x10C4,
  .idProduct          = 0x0001,
  .bcdDevice          = 0x0000,
  .iManufacturer      = 1,
  .iProduct           = 2,
  .iSerialNumber      = 3,
  .bNumConfigurations = 1
};

SL_ALIGN(4)
static const uint8_t configDesc[] SL_ATTRIBUTE_ALIGN(4)=
{
  // *** Configuration descriptor ***
  USB_CONFIG_DESCSIZE,            // bLength
  USB_CONFIG_DESCRIPTOR,          // bDescriptorType
  USB_CONFIG_DESCSIZE +           // wTotalLength (LSB)
  USB_INTERFACE_DESCSIZE,
  (USB_CONFIG_DESCSIZE +          // wTotalLength (MSB)
  USB_INTERFACE_DESCSIZE)>>8,
  1,                              // bNumInterfaces
  1,                              // bConfigurationValue
  0,                              // iConfiguration
  CONFIG_DESC_BM_RESERVED_D7 |    // bmAttrib: Self powered
  CONFIG_DESC_BM_SELFPOWERED,
  CONFIG_DESC_MAXPOWER_mA( 100 ), // bMaxPower: 100 mA

  // *** Interface descriptor ***
  USB_INTERFACE_DESCSIZE,         // bLength
  USB_INTERFACE_DESCRIPTOR,       // bDescriptorType
  0,                              // bInterfaceNumber
  0,                              // bAlternateSetting
  NUM_EP_USED,                    // bNumEndpoints
  0xFF,                           // bInterfaceClass
  0,                              // bInterfaceSubClass
  0,                              // bInterfaceProtocol
  0,                              // iInterface
};

STATIC_CONST_STRING_DESC_LANGID( langID, 0x04, 0x09 );
STATIC_CONST_STRING_DESC( iManufacturer, 'E','n','e','r','g','y',' ',       \
                                         'M','i','c','r','o',' ','A','S' );
STATIC_CONST_STRING_DESC( iProduct     , 'V','e','n','d','o','r',' ',       \
                                         'U','n','i','q','u','e',' ',       \
                                         'L','E','D',' ',                   \
                                         'D','e','v','i','c','e' );
STATIC_CONST_STRING_DESC( iSerialNumber, '0','0','0','0','0','0',           \
                                         '0','0','1','2','3','4' );

static const void * const strings[] =
{
  &langID,
  &iManufacturer,
  &iProduct,
  &iSerialNumber
};

// Endpoint buffer sizes
// 1 = single buffer, 2 = double buffering, 3 = tripple buffering ...
static const uint8_t bufferingMultiplier[ NUM_EP_USED + 1 ] = { 1 };

static const USBD_Callbacks_TypeDef callbacks =
{
  .usbReset        = NULL,
  .usbStateChange  = NULL,
  .setupCmd        = SetupCmd,
  .isSelfPowered   = NULL,
  .sofInt          = NULL
};

static const USBD_Init_TypeDef initstruct =
{
  .deviceDescriptor    = &deviceDesc,
  .configDescriptor    = configDesc,
  .stringDescriptors   = strings,
  .numberOfStrings     = sizeof(strings)/sizeof(void*),
  .callbacks           = &callbacks,
  .bufferingMultiplier = bufferingMultiplier
};  


Now we have to implement vendor unique USB setup commands to control the LED's (see callbacks variable above). Notice that the buffer variable below is statically allocated because USBD_Write() only initiates the transfer. When the host actually performs the transfer, the SetupCmd() function will have returned !

#define VND_GET_LEDS 0x10
#define VND_SET_LED  0x11

static int SetupCmd( const USB_Setup_TypeDef *setup )
{
  int retVal;
  uint16_t leds;
  static uint32_t buffer;
  uint8_t *pBuffer = (uint8_t*)&buffer;

  retVal = USB_STATUS_REQ_UNHANDLED;

  if ( setup->Type == USB_SETUP_TYPE_VENDOR ) {
    switch ( setup->bRequest ) {
      case VND_GET_LEDS:
      // ********************
        *pBuffer = BSP_LedsGet() & 0x1F;
        retVal = USBD_Write( 0, pBuffer, setup->wLength, NULL );
        break;

      case VND_SET_LED:
      // ********************
        leds = DVK_getLEDs() & 0x1F;
        if ( setup->wValue )
        {
          leds |= LED0 << setup->wIndex;
        }
        else
        {
          leds &= ~( LED0 << setup->wIndex );
        }
        BSP_LedsSet( leds );
        retVal = USB_STATUS_OK;
        break;
    }
  }

  return retVal;
}

Data Structures

struct USBD_Init_TypeDef
USB Device stack initialization structure.
struct USBD_Callbacks_TypeDef
USB Device stack callback structure.

Functions

void USBD_AbortAllTransfers (void)
Abort all pending transfers.
int USBD_AbortTransfer (int epAddr)
Abort a pending transfer on a specific endpoint.
void USBD_Connect (void)
Start USB device operation.
void USBD_Disconnect (void)
Stop USB device operation.
bool USBD_EpIsBusy (int epAddr)
Check if an endpoint is busy doing a transfer.
USBD_State_TypeDef USBD_GetUsbState (void)
Get current USB device state.
const char * USBD_GetUsbStateName ( USBD_State_TypeDef state)
Get a string naming a device USB state.
int USBD_Init (const USBD_Init_TypeDef *p)
Initializes USB device hardware and internal protocol stack data structures, then connects the data-line (D+ or D-) pullup resistor to signal host that enumeration can begin.
int USBD_Read (int epAddr, void *data, int byteCount, USB_XferCompleteCb_TypeDef callback)
Start a read (OUT) transfer on an endpoint.
int USBD_RemoteWakeup (void)
Perform a remote wakeup signalling sequence.
bool USBD_SafeToEnterEM2 (void)
Check if it is ok to enter energy mode EM2.
int USBD_StallEp (int epAddr)
Set an endpoint in the stalled (halted) state.
void USBD_Stop (void)
Stop USB device stack operation.
int USBD_UnStallEp (int epAddr)
Reset stall state on a stalled (halted) endpoint.
int USBD_Write (int epAddr, void *data, int byteCount, USB_XferCompleteCb_TypeDef callback)
Start a write (IN) transfer on an endpoint.

Macros

#define USB_PWRSAVE_MODE_OFF 0
No energy saving mode selected.
#define USB_PWRSAVE_MODE_ONSUSPEND 1
Enter USB power-save mode on suspend.
#define USB_PWRSAVE_MODE_ONVBUSOFF 2
Enter USB power-save mode when not attached to host.
#define USB_PWRSAVE_MODE_ENTEREM2 4
Enter EM2 while in power-save mode.
#define USB_USBC_32kHz_CLK_LFXO 1
Use 32kHz LFXO clock while in powersave mode.
#define USB_USBC_32kHz_CLK_LFRCO 2
Use 32kHz LFRCO clock while in powersave mode.
#define USB_USBLEM_CLK_LFXO 1
Use LFXO as USB LEM clock.
#define USB_USBLEM_CLK_LFRCO 2
Use LFRCO as USB LEM clock.

Typedefs

typedef void(* USBD_UsbResetCb_TypeDef ) (void)
USB Reset callback function.
typedef void(* USBD_SofIntCb_TypeDef ) (uint16_t sofNr)
USB Start Of Frame (SOF) interrupt callback function.
typedef void(* USBD_DeviceStateChangeCb_TypeDef ) ( USBD_State_TypeDef oldState, USBD_State_TypeDef newState)
USB State change callback function.
typedef bool(* USBD_IsSelfPoweredCb_TypeDef ) (void)
USB power mode callback function.
typedef int(* USBD_SetupCmdCb_TypeDef ) (const USB_Setup_TypeDef *setup)
USB setup request callback function.

Enumerations

enum USBD_State_TypeDef {
USBD_STATE_NONE = 0,
USBD_STATE_ATTACHED = 1,
USBD_STATE_POWERED = 2,
USBD_STATE_DEFAULT = 3,
USBD_STATE_ADDRESSED = 4,
USBD_STATE_CONFIGURED = 5,
USBD_STATE_SUSPENDED = 6,
USBD_STATE_LASTMARKER = 7
}
USB device state enumerator.

Function Documentation

USBD_AbortAllTransfers()

void USBD_AbortAllTransfers ( void )

Abort all pending transfers.

Aborts transfers for all endpoints currently in use. Pending transfers on the default endpoint (EP0) are not aborted.

USBD_AbortTransfer()

int USBD_AbortTransfer ( int epAddr )

Abort a pending transfer on a specific endpoint.

Parameters
[in] epAddr The address of the endpoint to abort.
Returns
USB_STATUS_OK on success, else an appropriate error code enumerated in USB_Status_TypeDef .

USBD_Connect()

void USBD_Connect ( void )

Start USB device operation.

Device operation is started by connecting a pullup resistor on the appropriate USB data line.

USBD_Disconnect()

void USBD_Disconnect ( void )

Stop USB device operation.

Device operation is stopped by disconnecting the pullup resistor from the appropriate USB data line. Often referred to as a "soft" disconnect.

USBD_EpIsBusy()

bool USBD_EpIsBusy ( int epAddr )

Check if an endpoint is busy doing a transfer.

Parameters
[in] epAddr The address of the endpoint to check.
Returns
True if endpoint is busy, false otherwise.

USBD_GetUsbState()

USBD_State_TypeDef USBD_GetUsbState ( void )

Get current USB device state.

Returns
Device USB state. See USBD_State_TypeDef .

USBD_GetUsbStateName()

const char* USBD_GetUsbStateName ( USBD_State_TypeDef state )

Get a string naming a device USB state.

Parameters
[in] state Device USB state. See USBD_State_TypeDef .
Returns
State name string pointer.

USBD_Init()

int USBD_Init ( const USBD_Init_TypeDef * p )

Initializes USB device hardware and internal protocol stack data structures, then connects the data-line (D+ or D-) pullup resistor to signal host that enumeration can begin.

Note
You may later use USBD_Disconnect() and USBD_Connect() to force reenumeration.
Parameters
[in] p Pointer to device initialization struct. See USBD_Init_TypeDef .
Returns
USB_STATUS_OK on success, else an appropriate error code enumerated in USB_Status_TypeDef .

USBD_Read()

int USBD_Read ( int epAddr,
void * data,
int byteCount,
USB_XferCompleteCb_TypeDef callback
)

Start a read (OUT) transfer on an endpoint.

Note
The transfer buffer length must be a multiple of 4 bytes in length and WORD (4 byte) aligned. When allocating the buffer, round buffer length up. If it is possible that the host will send more data than your device expects, round buffer size up to the next multiple of maxpacket size.
Parameters
[in] epAddr Endpoint address.
[in] data Pointer to transfer data buffer.
[in] byteCount Transfer length.
[in] callback Function to be called on transfer completion. Supply NULL if no callback is needed. See USB_XferCompleteCb_TypeDef .
Returns
USB_STATUS_OK on success, else an appropriate error code enumerated in USB_Status_TypeDef .

USBD_RemoteWakeup()

int USBD_RemoteWakeup ( void )

Perform a remote wakeup signalling sequence.

Note
It is the responsibility of the application to ensure that remote wakeup is not attempted before the device has been suspended for at least 5 miliseconds. This function should not be called from within an interrupt handler.
Returns
USB_STATUS_OK on success, else an appropriate error code enumerated in USB_Status_TypeDef .

USBD_SafeToEnterEM2()

bool USBD_SafeToEnterEM2 ( void )

Check if it is ok to enter energy mode EM2.

Note
Before entering EM2 both the USB hardware and the USB stack must be in a certain state, this function checks if all conditions for entering EM2 is met. Refer to the Energy-saving modes section for more information.
Returns
True if ok to enter EM2, false otherwise.

USBD_StallEp()

int USBD_StallEp ( int epAddr )

Set an endpoint in the stalled (halted) state.

Parameters
[in] epAddr The address of the endpoint to stall.
Returns
USB_STATUS_OK on success, else an appropriate error code enumerated in USB_Status_TypeDef .

USBD_Stop()

void USBD_Stop ( void )

Stop USB device stack operation.

The data-line pullup resistor is turned off, USB interrupts are disabled, and finally the USB pins are disabled.

USBD_UnStallEp()

int USBD_UnStallEp ( int epAddr )

Reset stall state on a stalled (halted) endpoint.

Parameters
[in] epAddr The address of the endpoint to un-stall.
Returns
USB_STATUS_OK on success, else an appropriate error code enumerated in USB_Status_TypeDef .

USBD_Write()

int USBD_Write ( int epAddr,
void * data,
int byteCount,
USB_XferCompleteCb_TypeDef callback
)

Start a write (IN) transfer on an endpoint.

Parameters
[in] epAddr Endpoint address.
[in] data Pointer to transfer data buffer. This buffer must be WORD (4 byte) aligned.
[in] byteCount Transfer length.
[in] callback Function to be called on transfer completion. Supply NULL if no callback is needed. See USB_XferCompleteCb_TypeDef .
Returns
USB_STATUS_OK on success, else an appropriate error code enumerated in USB_Status_TypeDef .

Macro Definition Documentation

USB_PWRSAVE_MODE_OFF

#define USB_PWRSAVE_MODE_OFF   0

No energy saving mode selected.


USB_PWRSAVE_MODE_ONSUSPEND

#define USB_PWRSAVE_MODE_ONSUSPEND   1

Enter USB power-save mode on suspend.


USB_PWRSAVE_MODE_ONVBUSOFF

#define USB_PWRSAVE_MODE_ONVBUSOFF   2

Enter USB power-save mode when not attached to host.


USB_PWRSAVE_MODE_ENTEREM2

#define USB_PWRSAVE_MODE_ENTEREM2   4

Enter EM2 while in power-save mode.


USB_USBC_32kHz_CLK_LFXO

#define USB_USBC_32kHz_CLK_LFXO   1

Use 32kHz LFXO clock while in powersave mode.


USB_USBC_32kHz_CLK_LFRCO

#define USB_USBC_32kHz_CLK_LFRCO   2

Use 32kHz LFRCO clock while in powersave mode.


USB_USBLEM_CLK_LFXO

#define USB_USBLEM_CLK_LFXO   1

Use LFXO as USB LEM clock.


USB_USBLEM_CLK_LFRCO

#define USB_USBLEM_CLK_LFRCO   2

Use LFRCO as USB LEM clock.


Typedef Documentation

USBD_UsbResetCb_TypeDef

typedef void(* USBD_UsbResetCb_TypeDef) (void)

USB Reset callback function.

Called whenever USB reset signalling is detected on the USB port.

USBD_SofIntCb_TypeDef

typedef void(* USBD_SofIntCb_TypeDef) (uint16_t sofNr)

USB Start Of Frame (SOF) interrupt callback function.

Called at each SOF interrupt (if enabled),

Parameters
[in] sofNr Current frame number. The value rolls over to 0 after 16383 (0x3FFF).

USBD_DeviceStateChangeCb_TypeDef

typedef void(* USBD_DeviceStateChangeCb_TypeDef) ( USBD_State_TypeDef oldState, USBD_State_TypeDef newState)

USB State change callback function.

Called whenever the device change state.

Parameters
[in] oldState The device USB state just leaved. See USBD_State_TypeDef .
[in] newState New (the current) USB device state. See USBD_State_TypeDef .

USBD_IsSelfPoweredCb_TypeDef

typedef bool(* USBD_IsSelfPoweredCb_TypeDef) (void)

USB power mode callback function.

Called whenever the device stack needs to query if the device is currently self- or bus-powered. Typically when host has issued an GET_STATUS setup command.

Returns
True if self-powered, false otherwise.

USBD_SetupCmdCb_TypeDef

typedef int(* USBD_SetupCmdCb_TypeDef) (const USB_Setup_TypeDef *setup)

USB setup request callback function.

Called on each setup request received from host. This gives the application a possibility to extend or override standard requests, and to implement class or vendor specific requests. Return USB_STATUS_OK if the request is handled, return USB_STATUS_REQ_ERR if it is an illegal request or return USB_STATUS_REQ_UNHANDLED to pass the request on to the default request handler.

Parameters
[in] setup Pointer to an USB setup packet. See USB_Setup_TypeDef .
Returns
An appropriate status/error code. See USB_Status_TypeDef .

Enumeration Type Documentation

USBD_State_TypeDef

USB device state enumerator.

Enumerator
USBD_STATE_NONE

Device state is undefined/unknown.


USBD_STATE_ATTACHED

Device state is ATTACHED.


USBD_STATE_POWERED

Device state is POWERED.


USBD_STATE_DEFAULT

Device state is DEFAULT.


USBD_STATE_ADDRESSED

Device state is ADDRESSED.


USBD_STATE_CONFIGURED

Device state is CONFIGURED.


USBD_STATE_SUSPENDED

Device state is SUSPENDED.


USBD_STATE_LASTMARKER

Device state enum end marker.