USBPlatform Middleware

Detailed Description

Gecko USB HOST and DEVICE protocol stacks.

Modules

USB_COMMON
Common parts for both HOST and DEVICE USB stacks, see USB device stack library and USB host stack library pages for device and host library documentation.
 
USB_DEVICE
Gecko USB DEVICE protocol stack, see USB device stack library page for detailed documentation.
 
USB_HOST
Gecko USB HOST protocol stack, see USB host 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 supporting crystal-less USB can 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.

You 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.


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_LFXO 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(); 

}


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;
}

USB host stack library

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


Introduction

The USB host protocol stack provides an API which makes it possible to create USB hosts with a minimum of effort. The host stack supports control, bulk and interrupt 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 USB host applications.


Getting started

To use an USB device, its pratical to divide the initial steps needed into :


Device connection

This framework can be used to establish a device connection.

// Initialize USB host stack
USBH_Init( &is );

for (;;)
{
  // Wait for ever on device attachment

  // The second parameter is timeout in seconds, 0 means for ever
  if ( USBH_WaitForDeviceConnectionB( tmpBuf, 0 ) == USB_STATUS_OK )
  {

    // Device is now connected and ready for enumeration !

  }

  // Wait for disconnection
  while ( USBH_DeviceConnected() ){}

  // Disable USB peripheral, power down USB port.
  USBH_Stop();
}


Device enumeration and configuration

This framework can be used to enumerate and activate the device.

  // Enumerate device, retrieve device and configuration descriptors from device
  USBH_QueryDeviceB( tmpBuf, sizeof( tmpBuf ), USBH_GetPortSpeed() );

  // Qualify the device
  if ( ( USBH_QGetDeviceDescriptor( tmpBuf )->idVendor  == 0x10C4               ) &&
       ( USBH_QGetDeviceDescriptor( tmpBuf )->idProduct == 0x0001               ) &&
       ( USBH_QGetDeviceDescriptor( tmpBuf )->bNumConfigurations == 1           ) &&
       ( USBH_QGetConfigurationDescriptor( tmpBuf, 0 )->bNumInterfaces  == 1    ) &&
       ( USBH_QGetInterfaceDescriptor(  tmpBuf, 0, 0 )->bInterfaceClass == 0xFF ) &&
       ( USBH_QGetInterfaceDescriptor(  tmpBuf, 0, 0 )->bNumEndpoints   == 2    )    )
  {
    // After having determined that the device is "our" device, it's time to
    // give it an USB address and activate the configuration.

    // Populate device and endpoint data structures with
    // data retrieved during enumeration.
    USBH_InitDeviceData( &device, tmpBuf, ep, 2, USBH_GetPortSpeed() );

    USBH_SetAddressB( &device, DEV_ADDR );
    USBH_SetConfigurationB( &device, device.confDesc.bConfigurationValue );

    // Assign host channels to device endpoints
    USBH_AssignHostChannel( &ep[ 0 ], 2 );
    USBH_AssignHostChannel( &ep[ 1 ], 3 );

    // We are now ready to use the device !

  }


The host stack API


Introduction

This section contains brief descriptions of all 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.

The functions in the API come in two flavours, they are either blocking or non-blocking. The blocking functions have an uppercase letter B at the end of the function name. Blocking functions can not be called when interrupts are disabled. Note that all API callback functions are called from within the USB peripheral interrupt handler with interrupts disabled.

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

Pitfalls:
An USB peripheral will fill host receive buffers in quantities of WORD's (4 bytes). When allocating storage for receive buffers, round size up to next WORD boundary. If it is possible that a device will send more data than host expects, round buffer size up to the next multiple of maxpacket size for the relevant endpoint to avoid buffer overflow.
Transmit and receive buffers must also be WORD aligned. Macros are available for allocating buffers, see UBUF and STATIC_UBUF.

Transmit buffers passed to non-blocking transfer functions must be statically allocated because these functions do not have their own buffers. The data in the transmit buffers must be valid until the transfer completes, times out or fails.


Top level control functions

USBH_Init()
Initial host stack initialization, call once in start of main().

USBH_Stop()
Terminates host operation, turns off VBUS.

USBH_WaitForDeviceConnectionB()
Wait for device connection with optional timeout.

USBH_AssignHostChannel()
Associate a device endpoint with a host channel.


USB transfer functions

USBH_ControlMsg(), USBH_ControlMsgB()
Perform a non-blocking or blocking USB control message transfer.

USBH_Read(), USBH_ReadB()
Perform a non-blocking or blocking USB IN data transfer. Data direction is from device to host.

USBH_Write(), USBH_WriteB()
Perform a non-blocking or blocking USB OUT data transfer. Data direction is from host to device.


USB Chapter 9 support functions

All Chapter 9 support functions are blocking with a timeout of 1 second.

USBH_GetConfigurationDescriptorB()
Read a configuration descriptor from a device.

USBH_GetDeviceDescriptorB()
Read a device descriptor from a device.

USBH_GetStringB()
Read a string descriptor from a device.

USBH_SetAddressB()
Set new USB device address on device currently on USB address 0.

USBH_SetAltInterfaceB()
Set alternate interface on a device.

USBH_SetConfigurationB()
Set device configuration.

USBH_StallEpB(), USBH_UnStallEpB()
These functions stalls or un-stalls an endpoint. Uses USB standard requests SET_FEATURE and CLEAR_FEATURE.


Host port control functions

USBH_DeviceConnected()
Check if a device is connected on the USB host port.

USBH_GetPortSpeed()
Get the bus speed (low speed or full speed) of the device currently connected to the USB host port.

USBH_PortReset()
Drive reset signalling on the USB host port.

USBH_PortResume()
Drive resume signalling on the USB host port.

USBH_PortSuspend()
Set the USB host port in suspend mode.


Enumeration and query functions

USBH_QueryDeviceB()
This function will read the device and configuration descriptors from a device at USB address 0. The application must allocate a buffer of sufficent size to hold the data. This data buffer can later be used by all USBH_Qxxx functions to retrieve pointers to any descriptor within any configuration descriptor. Data retrieved by this function must also be passed to USBH_InitDeviceData() before normal device communication can start. Ref. section Device enumeration and configuration.

USBH_QGetConfigurationDescriptor()
Get a pointer to a given configuration descriptor. Parses through a data buffer which must have been previously populated by a call to USBH_QueryDeviceB().

USBH_QGetDeviceDescriptor()
Get a pointer to the device descriptor. Parses through a data buffer which must have been previously populated by a call to USBH_QueryDeviceB().

USBH_QGetEndpointDescriptor()
Get a pointer to a given endpoint descriptor within a given interface within a given configuration. Parses through a data buffer which must have been previously populated by a call to USBH_QueryDeviceB().

USBH_QGetInterfaceDescriptor()
Get a pointer to an interface descriptor within a given configuration. Parses through a data buffer which must have been previously populated by a call to USBH_QueryDeviceB().

USBH_InitDeviceData()
Populates device and endpoint data structures with data which must have been retrieved from a device by a call to USBH_QueryDeviceB() . The application must allocate and provide device and endpoint data structures to the host stack. After this function is called the device and endpoint data structures can be used as parameters (handles) to other API functions as needed.


Utility functions

USBH_PrintString()
Print an USB string descriptor on the debug serial port with optional leader and trailer strings.

USBH_PrintConfigurationDescriptor(), USBH_PrintDeviceDescriptor(), USBH_PrintEndpointDescriptor(), USBH_PrintInterfaceDescriptor()
Pretty print descriptors on the debug serial port.

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 USBH_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 host stack

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

#define USB_HOST         // Compile the stack for host mode.
#define NUM_HC_USED n    // Your application use 'n' host channels in addition
                         // to channels 0 and 1 which are assigned by the
                         // host stack for device endpoint 0 communication. 


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 


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.

You 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.


The host stack can be configured to monitor a GPIO input pin for detection of VBUS overcurrent or short circuit conditions. The stack will by default use pin 2 on PortE and low polarity for this purpose. Override by using the following three #define's:

#define USB_VBUSOVRCUR_PORT       gpioPortB       // The port
#define USB_VBUSOVRCUR_PIN        7               // The pin number within the port
#define USB_VBUSOVRCUR_POLARITY   USB_VBUSOVRCUR_POLARITY_LOW 

Select any GPIO port for USB_VBUSOVRCUR_PORT or USB_VBUSOVRCUR_PORT_NONE if no overcurrent circuitry in the hw design. For USB_VBUSOVRCUR_POLARITY use USB_VBUSOVRCUR_POLARITY_LOW or USB_VBUSOVRCUR_POLARITY_HIGH.