Detailed Description

Gecko USB DEVICE protocol stack.

Modules

USB_COMMON
Common parts for both HOST and DEVICE USB stacks, see USB device stack library pages for device library documentation.
 
USB_DEVICE
Gecko USB DEVICE protocol stack, see USB device stack library page for detailed documentation.
 

USB device stack library

The source files for the USB device stack resides in the usb directory and follows the naming convention: em_usbdnnn.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_ClockSelectSet(cmuClock_HF, cmuSelect_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;
}