emUSB-Host
User Guide & Reference Manual
Document: UM10001
Software Version: 2.36.2
Document revision: 0
Introduction
This chapter provides an introduction to using emUSB-Host. It explains the basic
concepts behind emUSB-Host.
What is emUSB-Host
emUSB-Host is a CPU-independent USB Host stack.
emUSB-Host is a high-performance library that has been optimized for speed, versatility and small memory footprint.
emUSB-Host features
emUSB-Host is written in ANSI C and can be used on virtually any CPU. Here is a list of emUSB-Host features:
- ISO/ANSI C source code.
- High performance.
- Small footprint.
- No configuration required.
- Runs out-of-the-box.
- Control, bulk, interrupt and isochronous transfers.
- Very simple host controller driver structure.
- USB Mass Storage Device Class available.
- Works seamlessly with embOS, emFile (for MSD) and emNET (for LAN).
- Support for class drivers.
- Support for external USB hub devices.
- Support for devices with alternate settings.
- Support for multi-interface devices.
- Support for multi-configuration devices.
- Royalty-free.
Basic concepts
emUSB-Host consists of three layers: a driver for hardware access, the emUSB-Host
core and a USB class driver. For a functional emUSB-Host, the core component and at
least one of the hardware drivers is necessary. emUSB-Host handles all USB operations independently in a separate task(s) beside the target application task. This
implicitly means that an RTOS is required.
A recommendation is using embOS since it perfectly fits the requirements of emUSB
Host and works seamlessly with emUSB-Host, not requiring any integration work.
Tasks and interrupt usage
emUSB-Host uses two dedicated tasks. One of the tasks processes the interrupts
generated by the USB host controller. The function USBH_ISRTask() must run as
this task with the highest priority. The other task manages the internal software timers. Its routine must be the USBH_Task() function. The priorities of both tasks have
to be higher than the priority of any other application task which uses emUSB-Host.
To recap:
- USBH_ISRTask runs with the highest priority
- USBH_Task runs with a priority lower than USBH_ISRTask
- All application tasks run with a priority lower than USBH_Task
emUSBH API functions must not be called from interrupt functions, only from any task context.
Especially when using MSD it is easy to forget that the file system functions actually
call emUSB-Host functions underneath. Therefore a task operating on the file system
of a connected USB medium is considered an application task and must have a
lower priority than USBH_Task.
Tasks which do not use emUSB-Host in any way can run at a higher priority than
USBH_ISRTask. Even if a different high-priority task blocks the CPU for extended
periods of time, USB communication should not be affected. USB communication is
host-controlled, there are no timeouts on the device side and the host is free to delay
the communication depending on how busy it is.
Your application must properly configure these two tasks at startup. The examples in
the Application folder show how to do this.
Development environment (compiler)
The CPU used is of no importance; only an ANSI-compliant C compiler complying with
at least one of the following international standard is required:
- ISO/IEC 9899:1999 (C99)
- ISO/IEC 14882:1998 (C++)
If your compiler has some limitations, let us know and we will inform you if these will
be a problem when compiling the software. Any compiler for 16/32/64-bit CPUs or
DSPs that we know of can be used.
A C++ compiler is not required, but can be used. The application program can therefore
also be programmed in C++ if desired.
Use of undocumented functions
Functions, variables and data-types which are not explained in this manual are considered internal. They are in no way required to use the software. Your application
should not use and rely on any of the internal elements, as only the documented API
functions are guaranteed to remain unchanged in future versions of the software.
If you feel that it is necessary to use undocumented (internal) functions, please get
in touch with SEGGER support in order to find a solution.
This is a short introduction to USB. The fundamentals of USB are explained and links
to additional resources are given.
Short Overview
The Universal Serial Bus (USB) is an external bus architecture for connecting peripherals to a host computer. It is an industry standard - maintained by the USB Implementers Forum - and because of its many advantages it enjoys a huge industry-wide
acceptance. Over the years, a number of USB-capable peripherals appeared on the
market, for example printers, keyboards, mice, digital cameras etc. Among the top
benefits of USB are:
- Excellent plug-and-play capabilities allow devices to be added to the host system
without reboots (“hot-plug”). Plugged-in devices are identified by the host and
the appropriate drivers are loaded instantly.
- USB allows easy extensions of host systems without requiring host-internal
extension cards.
- Device bandwidths may range from a few Kbytes/second to hundreds of Mbytes/
second.
- A wide range of packet sizes and data transfer rates are supported.
- USB provides internal error handling. Together with the hot-plug capability mentioned before this greatly improves robustness.
- The provisions for powering connected devices dispense the need for extra power
supplies for many low power devices.
- Several transfer modes are supported which ensures the wide applicability of
USB.
These benefits have not only led to broad market acceptance, but have also produced
several other advantages, such as low costs of USB cables and connectors or a wide
range of USB stack implementations. Last but not least, the major operating systems
such as Microsoft Windows XP, Mac OS X, or Linux provide excellent USB support.
Important USB Standard Versions
USB 1.1 (September 1998)
This standard version supports isochronous and asynchronous data transfers.
It has dual speed data transfer of 1.5 Mbit/s for low speed and 12 Mbit/s for full-speed devices.
The maximum cable length between host and device is five meters.
Up to 500 mA of electric current may be distributed to low power devices.
USB 2.0 (April 2000)
As all previous USB standards, USB 2.0 is fully forward and backward compatible.
Existing cables and connectors may be reused.
A new high-speed transfer speed of 480 Mbit/s (40 times faster than USB 1.1 at full-speed) was added.
USB 3.0 (November 2008)
As all previous USB standards, USB 3.0 is fully forward and backward compatible.
Existing cables and connectors may be reused but the new speed can only be used with new USB 3.0 cables and devices.
The new speed class is named USB Super-Speed, which offers a maximum rate of 5 Gbit/s.
USB 3.1 (July 2013)
As all previous USB standards, USB 3.1 is fully forward and backward compatible.
The new specification replaces the 3.0 standard and introduces new transfer speeds of up to 10 Gbit/s.
USB System Architecture
A USB system is composed of three parts - a host side, a device side and a physical
bus. The physical bus is represented by the USB cable and connects the host and the
device.
The USB system architecture is asymmetric. Every single host can be connected to
multiple devices in a tree-like fashion using special hub devices. You can connect up
to 127 devices to a single host, but the count must include the hub devices as well.
USB Host
A USB host consists of a USB host controller hardware and a layered software stack.
This host stack contains:
- A driver for the USB host controller hardware.
- The USB host stack which implements the high level functions used by
the USB class drivers (including enumeration and hub support).
- One or more USB class drivers providing generic access to certain types of
USB devices such as printers or mass storage devices.
USB Device
Two types of devices exist: Hubs and functions. Hubs usually provide four ore more additional
USB attachment points. Functions provide capabilities to the host and are able to
transmit or receive data or control information over the USB bus. Every peripheral
USB device represents at least one function but may implement more than one function. A USB printer for instance may provide file system like access in addition to
printing.
In this guide we treat the term USB device as synonymous with functions and will not
consider hubs.
Each USB device contains configuration information which describes its capabilities
and resource requirements. Before it can be used a USB device must be configured
by the host. When a new device is connected for the first time, the host enumerates
it, requests the configuration from the device, and performs the actual configuration.
For example, if a memory stick is connected to a USB host, it will
appear as a USB mass storage device, and the host will use a standard MSD
class implementation to access the device.
Descriptors
A device reports its attributes via descriptors. Descriptors are data structures with a
standard defined format. A USB device has one device descriptor which contains
information applicable to the device and all of its configurations. It also contains the
number of configurations supported by the device. For each configuration, a configuration
descriptor contains configuration-specific information. The configuration descriptor
also contains the number of interfaces provided by the configuration. An interface
groups the endpoints into logical units. Each interface descriptor contains information
about the number of endpoints. Each endpoint has its own endpoint descriptor which
states the endpoint’s address, transfer types etc.
Transfer Types
The USB standard defines four transfer types: control, isochronous, interrupt, and
bulk. Control transfers are used in the setup phase. The application can basically
select one of the other three transfer types. For most embedded applications, bulk is
the best choice because it allows the highest possible data rates.
Control transfers
Typically used for configuring a device when attached to the host. It may also be
used for other device-specific purposes, including control of other pipes on the
device.
Isochronous transfers
Typically used for applications which need guaranteed speed. Isochronous transfer is
fast but with possible data loss. A typical use is for audio data which requires a constant data rate.
Interrupt transfers
Typically used by devices that need guaranteed quick responses (bounded latency).
Bulk transfers
Typically used by devices that generate or consume data in relatively large and
burstly quantities. Bulk transfer has wide dynamic latitude in transmission constraints. It can use all remaining available bandwidth, but with no guarantees on
bandwidth or latency. Because the USB bus is normally not very busy, there is typically 90% or more of the bandwidth available for USB transfers.
Setup phase / Enumeration
The host first needs to get information from the target before the target can start
communicating with the host. This information is gathered in the initial setup phase.
The information is contained in the descriptors. The most important part of target
device identification are the Product and Vendor IDs. During the setup phase, the
host also assigns an address to the device. This part of the setup is called enumeration.
Product / Vendor IDs
Each USB device can be identified by its a Vendor and Product ID. A USB host does not have
a Vendor and Product ID.
Predefined device classes
The USB Implementers Forum has defined device classes for different purposes. In
general, every device class defines a protocol for a particular type of application such
as a mass storage device (MSD), human interface device (HID), etc.
Running emUSB-Host on target hardware
This chapter explains how to integrate and run emUSB-Host on your target hardware.
Integrating emUSB-Host
We assume that you are familiar with the tools you have selected for your project
(compiler, project manager, linker, etc.). You should therefore be able to add files,
add directories to the include search path, and so on.
In this document the Embedded Studio IDE is used for all examples and screenshots, but every other
ANSI C toolchain can also be used. It is also possible to use makefiles; in this case,
when we say “add to the project”, this translates into “add to the makefile”.
Procedure to follow
Integration of emUSB-Host is a relatively simple process, which consists of the
following steps:
- Take a running project for your target hardware.
- Add emUSB-Host files to the project.
- Add hardware dependent configuration to the project.
- Prepare and run the application.
Take a running project
The project to start with should include the setup for
basic hardware (e.g. CPU, PLL, DDR SDRAM) and initialization of the RTOS.
emUSB-Host is designed to be used
with embOS, SEGGER’s real-time operating system. We recommend to start with an
embOS sample project and include emUSB-Host into this project.
Add emUSB-Host files
Add all necessary source files from the USBH folder to your project.
You may simply add all files and let the linker drop everything not needed
for your configuration. But there are some source files containing dependencies
to emFile or embOS/IP. If you don’t have these middleware components, remove the
respective files from your project.
Add RTOS layer
Additionally add the RTOS interface layer to your project. Choose a file from the
folder Sample/USBH/OS that matches your RTOS. For embOS use USBH_OS_embOS.c.
Configuring the include path
The include path is the path in which the compiler looks for include files. In cases
where the included files (typically header files, .h) do not reside in the same folder
as the C file to compile, an include path needs to be set. In order to build the project
with all added files, you will need to add the following directories to your include
path:
Configuring debugging output
While developing and testing emUSB-Host, we recommend to use the DEBUG configuration of
emUSB-Host. This is enabled by setting the preprocessor symbol DEBUG to 1 (or USBH_DEBUG to 2).
The DEBUG configuration contains many additional run-time checks and generate debug output messages
which are very useful to identify problems that may occur during development.
In case of a fatal problem (e.g. an invalid configuration)
the program will end up in the function USBH_Panic() with a
appropriate error message that describes the cause of the problem.
Add the file USBH_ConfigIO.c found in the folder Config to your project
and configure it to match the message output method used by your debugging tools.
If possible use RTT.
To later compile a release configuration, which has a significant smaller code footprint,
simply set the preprocessor symbol DEBUG (or USBH_DEBUG) to 0.
Add hardware dependent configuration
To perform target hardware dependent runtime configuration, the emUSB-Host stack calls
a function named USBH_X_Config. Typical tasks that may be done inside this function are:
- Assign memory to be used by the emUSB-Host stack.
- Select an appropriate driver for the USB host controller.
- Configure I/O pins of the MCU for USB.
- Configure PLL and clock divider necessary for USB operation.
- Install an interrupt service routine for USB and set interrupt priority.
Details can be found in Runtime configuration.
Sample configurations for popular evaluation boards are supplied
with the driver shipment. They can be found in files called
USBH_Config_<TargetName>.c in the folders BSP/<BoardName>/Setup.
Add the appropriate configuration file to your project.
If there is no configuration file for your target hardware, take a file for a
similar hardware and modify it if necessary.
If the file needs modifications, we recommend to copy it into the directory Config
for easy updates to later versions of emUSB-Host.
Add BSP file
Some targets require CPU specific functions for initialization, mainly for installing
an interrupt service routine. They are contained in the file BSP_USB.c.
USB interrupt priority can also be configured in BSP_USB.c.
Sample BSP_USB.c files for popular evaluation boards are supplied
with the driver shipment. They can be found in the folders BSP/<BoardName>/Setup.
Add the appropriate BSP_USB.c file to your project.
If there is no BSP file for your target hardware, take a file for a
similar hardware and modify it if necessary.
If the file needs modifications, we recommend to copy it into the directory Config
for easy updates to later versions of emUSB-Host.
Note that a BSP_USB.c file is not always required, because for some target hardware
all runtime configuration is done in USBH_X_Config.
Prepare and run the application
Choose a sample application from the folder Application and add it to your project.
Sample applications are described in Example applications.
Compile and run the application on the target hardware.
Write your own application
Take one of the sample applications as a starting point to write your own application.
In order to use emUSB-Host, the application has to:
- Initialize the USB core stack by calling USBH_Init().
- Create two separate tasks that call the functions USBH_Task() and USBH_ISRTask(), respectively.
Task priority requirements described in Tasks and interrupt usage must be considered.
- Initialize the USB class drivers needed by calling the USBH_<class>_Init() function(s).
Updating emUSB-Host
If an existing project should be updated to a later emUSB-Host version, only files have to be replaced.
You should have received the emUSB-Host update as a zip file. Unzip this file to the location
of your choice and replace all emUSB-Host files in your project with the newer files from the
emUSB-Host update shipment.
In general, all files from the following directories have to be updated:
- USBH
- Inc
- SEGGER
- Doc
- Sample/USBH/OS
Some files may contain modification required for project specific customization.
These files should reside in the folder Config and must not be overwritten.
This includes:
- USBH_Conf.h
- USBH_ConfigIO.c
- BSP_USB.c
- USBH_Config_<TargetName>.c
Example applications
In this chapter, you will find a description of each emUSB-Host example application.
Overview
File | Description |
USBH_HID_Start.c | Demonstrates the handling of mouse and keyboard events. |
USBH_MSD_Start.c | Demonstrates how to handle mass storage devices. |
USBH_Printer_Start.c | Shows how to interact with a printer. |
USBH_CDC_Start.c | Demonstrates communication with CDC devices. |
USBH_MTP_Start.c | Shows how to interact with smart phones and other MTP-enabled devices. |
USBH_FT232_Start.c | Demonstrates communication with FTDI serial adapters. |
The example applications for the target-side are supplied in source code in the
Application folder of your shipment.
Mouse and keyboard events (USBH_HID_Start.c)
This example application displays in the terminal I/O of the debugger the events generated by a mouse and a keyboard connected over USB.
A message in the form:
6:972 MainTask - Mouse: xRel: 0, yRel: 0, WheelRel: 0, ButtonState: 1
is generated each time the mouse generates an event. An event is generated when
the mouse is moved, a button is pressed or the scroll-wheel is rolled. The message
indicates the change in position over the vertical and horizontal axis, the scroll-wheel
displacement and the status of all buttons.
In case of a keyboard these two messages are generated when a key is pressed and
then released:
386:203 MainTask - Keyboard: Key e/E - pressed
386:287 MainTask - Keyboard: Key e/E - released
The keycode is displayed followed by its status.
Mass storage handling (USBH_MSD_Start.c)
This demonstrates the handling of mass storage devices. A small test is run as soon
as a mass storage device is connected to host. The results of the test are displayed in
the terminal I/O window of the debugger. If the medium is not formatted only the
message “Medium is not formatted.” is shown and the application waits for a new
device to be connected. In case the medium is formatted the file system is mounted
and the total disk space is displayed. The test goes on and creates a file named
TestFile.txt in the root directory of the disk followed by a listing of the files in the
root directory. The value returned by OS_GetTime() is stored in the created file. At
the end of test the file system is unmounted and information about the mass storage
device is displayed like Vendor ID and name.
Information similar to the following is shown when a memory stick is connected:
<...>
**** Device added
Running sample on "msd:0:"
Reading volume information...
**** Volume information for msd:0:
125105536 KBytes total disk space
125105536 KBytes available free space
32768 bytes per cluster
3909548 clusters available on volume
3909548 free cluster available on volume
Creating file msd:0:\TestFile.txt...Ok
Contents of msd:0:
TESTFILE.TXT Attributes: A--- Size: 21
**** Unmount ****
Test with the following device was successful:
VendorId: 0x1234
ProductId: 0x5678
VendorName: XXXXXXX
ProductName: XXXXXXXXXXXXXX
Revision: 1.00
NumSectors: 250272768
BytesPerSector: 512
TotalSize: 122203 MByte
HighspeedCapable: No
ConnectedToRootHub: Yes
SelfPowered: No
Reported Imax: 500 mA
Connected to Port: 1
PortSpeed: FullSpeed
Printer interaction (USBH_Printer_Start.c)
This example shows how to communicate with a printer connected over USB. As soon
as a printer connects over USB the message “**** Device added” is displayed on
the terminal I/O window of the debugger followed by the device ID of the printer and
the port status. After that the ASCII text “Hello World” and a form feed is sent to the printer.
Terminal output:
**** Device added
Device Id = MFG:Hewlett-Packard;CMD:PJL,PML,POSTSCRIPT,PCLXL,PCL;MDL:HP
LaserJet P2015 Series;CLS:PRINTER;DES:Hewlett-Packard LaserJet P2015
Series;MEM:MEM=23MB;COMMENT:RES=1200x1;
PortStatus = 0x18 ->NoError=1, Select/OnLine=1, PaperEmpty=0
Printing Hello World to printer
Printing completed
**** Device removed
Serial communication (USBH_CDC_Start.c)
This example shows how to communicate with a CDC-enabled device.
Since CDC is just a transport protocol it is not possible to write a generic sample which will work with all devices.
This sample is designed to be used with a emUSB-Device CDC counterpart, the “USB_CDC_Echo.c” sample.
It can also be used with any other device, but it may not be able to demonstrate continuous communication.
The sample works as follows:
- When a CDC is connected the sample prints generic information about the device.
- After that the sample writes data onto the device.
- The sample reads data from the device and in case it has received any - sends it back.
With the emUSB-Device “USB_CDC_Echo.c” sample this causes a simple, continuous ping-pong of messages.
Terminal output:
**** Device added
<...>
0:663 USBH_isr - INIT: USBH_ISRTask started
**** Device added
Vendor Id = 0x1234
Product Id = 0x5678
Serial no. = 123456789
Speed = HighSpeed
Started communication...
<...>
**** Device removed
This example shows how to communicate with a MTP-enabled device.
The sample demonstrates most of the emUSB-Host MTP API. When a MTP device is connected the sample prints generic information about the device.
If the device is locked (e.g. pin code on a smart phone) the sample will wait for the user to unlock it.
The sample will then iterate over the storages made available by the device, print information about it,
print the file and folder list in the root directory and create a new file under it called “SEGGER_Test.txt”.
Terminal output:
<...>
**** Device added
Vendor Id = 0x1234
Product Id = 0x1234
Serial no. = 1
Speed = FullSpeed
Manufacturer : XXXXXX
Model : XXXXXXXXXXXXXXXXXXXXXX
DeviceVersion : 8.10.12397.0
MTP SerialNumber : 844848fb44583cbaa1ecae45545b3
USBH_MTP_CheckLock returns USBH_STATUS_ERROR
Please unlock the device to proceed.
<...>
_cbOnUserEvent: MTP Event received! EventCode: 0x4004, Para1: 0x00010001
, Para2: 0x00000000, Para3: 0x00000000.
<...>
USBH_MTP_CheckLock returns USBH_STATUS_SUCCESS
Found storage with ID: 0
StorageType = 0x0003
FilesystemType = 0x0002
AccessCapability = 0x0000
MaxCapacity = 3959422976 bytes
FreeSpaceInBytes = 1033814016 bytes
FreeSpaceInImages = 0x00000000
StorageDescription : Phone
VolumeLabel : MTP Volume - 65537
Found 9 objects in directory 0xFFFFFFFF
Processing object 0x00000001 in directory 0xFFFFFFFF...
StorageID = 0x00010001
ObjectFormat = 0x3001
ParentObject = 0xFFFFFFFF
ProtectionStatus = 0x0001
Filename : Documents
CaptureDate : 20140522T0
ModificationDate : 20160707T1
Processing object 0x00000002 in directory 0xFFFFFFFF...
StorageID = 0x00010001
ObjectFormat = 0x3001
ParentObject = 0xFFFFFFFF
ProtectionStatus = 0x0001
Filename : Downloads
CaptureDate : 20140522T0
ModificationDate : 20160707T1
<...>
Creating new object with 135 bytes in folder 0xFFFFFFFF
with name SEGGER_Test.txt.
Created new object in folder 0xFFFFFFFF, ID: 0x000013F9.
Connection to MTP device closed.
<...>
**** Device removed
FTDI devices (USBH_FT232_Start.c)
This example shows how to communicate with a FTDI FT232 adapters.
When a FT232 is connected the sample prints generic information about the device. After that it receives data from the connected FT232 adapter and sends it back.
The sample is easily tested by using two identical FT232 adapters connected to each other via a null modem cable. One of the devices should be connected to emUSB-Host.
The other to a PC. You can use any PC terminal emulator to send data from one adapter to the other, which will be then received by emUSB-Host and sent back.
Baudrate and other serial setting should match between the sample and the PC for this to work.
Terminal output:
**** Device added
<...>
3:213 MainTask - Vendor Id = 0x0403
3:213 MainTask - Product Id = 0x6001
3:213 MainTask - bcdDevice = 0x0600
<...>
**** Device removed
USB Host Core
In this chapter, you will find a description of all API functions as well as all required
data and function types.
Target API
This section describes the functions that can be used by the target application.
USBH_AssignMemory()
Description
Assigns a memory area that will be used by the memory management
functions for allocating memory.
This function must be called in the initialization phase.
Prototype
void USBH_AssignMemory(void * pMem,
U32 NumBytes);
Parameters
Parameter | Description |
pMem | Pointer to the memory area. |
NumBytes | Size of the memory area in bytes. |
Additional information
emUSB-Host comes with its own dynamic memory allocator optimized for its needs.
This function is used to set up up a memory area for the heap. The best place to
call it is in the USBH_X_Config() function.
For some USB host controllers additionally a separate memory heap for DMA memory
must be provided by calling USBH_AssignTransferMemory().
USBH_AssignTransferMemory()
Description
Assigns a memory area for a heap that will be used for allocating DMA memory.
This function must be called in the initialization phase.
The memory area provided to this function must fulfill the following requirements:
- Not cachable/bufferable.
- Fast access to avoid timeouts.
- USB-Host controller must have full read/write access.
- Cache aligned
If the physical address is not equal to the virtual address of the memory area
(address translation by an MMU), additionally a mapping function must be
installed using USBH_Config_SetV2PHandler().
Prototype
void USBH_AssignTransferMemory(void * pMem,
U32 NumBytes);
Parameters
Parameter | Description |
pMem | Pointer to the memory area (virtual address). |
NumBytes | Size of the memory area in bytes. |
Additional information
Use of this function is required only in systems in which “normal” default memory
does not fulfill all of these criteria.
In simple microcontroller systems without cache, MMU and external RAM, use of this
function is not required. If no transfer memory is assigned, memory assigned with
USBH_AssignMemory() is used instead.
USBH_CloseInterface()
Description
Close an interface handle that was opened with USBH_OpenInterface().
Prototype
void USBH_CloseInterface(USBH_INTERFACE_HANDLE hInterface);
Parameters
Additional information
Each handle must be closed one time. Calling this function with an invalid handle
leads to undefined behavior.
USBH_Config_SetV2PHandler()
Description
Sets a virtual address to physical address translator.
Is required, if the physical address is not equal to the virtual address
of the memory used for DMA access (address translation by an MMU).
See USBH_AssignTransferMemory.
Prototype
void USBH_Config_SetV2PHandler(USBH_V2P_FUNC * pfV2PHandler);
Parameters
Parameter | Description |
pfV2PHandler | Handler to be called to convert virtual address. |
USBH_ConfigPowerOnGoodTime()
Description
Configures the power on time that the host waits after connecting a device
before starting to communicate with the device. The default value is 300 ms.
Prototype
void USBH_ConfigPowerOnGoodTime(unsigned PowerGoodTime);
Parameters
Parameter | Description |
PowerGoodTime | Time the stack should wait before doing any other operation (im ms). |
Additional information
If you are dealing with problematic devices which have long initialization sequences it
is advisable to increase this timeout.
USBH_ConfigSupportExternalHubs()
Description
Enable support for external USB hubs.
Prototype
void USBH_ConfigSupportExternalHubs(U8 OnOff);
Parameters
Parameter | Description |
OnOff | 1 - Enable support for external hubs 0 - Disable support for external hubs. |
Additional information
This function should not be called if no external hub support is required to avoid
the code for external hubs to be linked into the application.
USBH_ConfigTransferBufferSize()
Description
Configures the size of a copy buffer that can be used if
the USB controller has limited access to the system memory
or the system is using cached (data) memory. Transfer buffers
of this size are allocated for each used endpoint.
If this functions is not called, a driver specific default size
is used.
Prototype
void USBH_ConfigTransferBufferSize(U32 HCIndex,
U32 Size);
Parameters
Parameter | Description |
HCIndex | Index of the host controller. |
Size | Size of the buffer in bytes. Must be a multiple of the maximum packet size (512 for high speed, 64 for full speed). |
USBH_CreateInterfaceList()
Description
Generates a list of available interfaces matching a given criteria.
Prototype
USBH_INTERFACE_LIST_HANDLE USBH_CreateInterfaceList
(const USBH_INTERFACE_MASK * pInterfaceMask,
unsigned int * pInterfaceCount);
Parameters
Parameter | Description |
pInterfaceMask | Pointer to a caller provided structure, that allows to select interfaces to be included in the list. If this pointer is NULL all available interfaces are returned. |
pInterfaceCount | Pointer to a variable that receives the number of interfaces in the list created. |
Return value
On success it returns a handle to the interface list.
In case of an error it returns NULL.
Additional information
The generated interface list is stored in the emUSB-Host and must be deleted by a
call to USBH_DestroyInterfaceList(). The list contains a snapshot of interfaces
available at the point of time where the function is called. This enables the application
to have a fixed relation between the index and a USB interface in a list. The list
is not updated if a device is removed or connected. A new list must be created to
capture the current available interfaces. Hub devices are not added to the list!
Example
/*********************************************************************
*
* _ListJLinkDevices
*
* Function description
* Generates a list of JLink devices connected to host.
*/
static void _ListJLinkDevices(void) {
USBH_INTERFACE_MASK IfaceMask;
unsigned int IfaceCount;
USBH_INTERFACE_LIST_HANDLE hIfaceList;
memset(&IfaceMask, 0, sizeof(IfaceMask));
//
// We want a list of all SEGGER J-Link devices connected to our host.
// The devices are selected by their Vendor and Product ID.
// Other identification information is not taken into account.
//
IfaceMask.Mask = USBH_INFO_MASK_VID | USBH_INFO_MASK_PID;
IfaceMask.VendorId = 0x1366;
IfaceMask.ProductId = 0x0101;
hIfaceList = USBH_CreateInterfaceList(&IfaceMask, &IfaceCount);
if (hIfaceList == NULL) {
USBH_Warnf_Application("Cannot create the interface list!");
} else {
if (IfaceCount == 0) {
USBH_Logf_Application("No devices found.");
} else {
unsigned int i;
USBH_INTERFACE_ID IfaceId;
//
// Traverse the list of devices and display information about each of them
//
for (i = 0; i < IfaceCount; ++i) {
//
// An interface is addressed by its ID
//
IfaceId = USBH_GetInterfaceId(hIfaceList, i);
_ShowIfaceInfo(IfaceId);
}
}
//
// Ensure the list is properly cleaned up
//
USBH_DestroyInterfaceList(hIfaceList);
}
}
USBH_DestroyInterfaceList()
Description
Destroy a device list created by USBH_CreateInterfaceList() and free the related resources.
Prototype
void USBH_DestroyInterfaceList(USBH_INTERFACE_LIST_HANDLE hInterfaceList);
Parameters
USBH_Exit()
Description
Shuts down and de-initializes the emUSB-Host stack. All resources will be
freed within this function. This includes also the removing and deleting of all host controllers.
Before this function can be used, the exit functions of all initialized USB classes
(e.g. USBH_CDC_Exit(), USBH_MSD_Exit(), …) must be called.
Calling USBH_Exit() will cause the functions USBH_Task() and USBH_ISRTask() to return.
Prototype
void USBH_Exit(void);
Additional information
After this function call, no other function of the USB stack should be called.
USBH_GetCurrentConfigurationDescriptor()
Description
Retrieves the current configuration descriptor of the device containing the given interface.
Prototype
USBH_STATUS USBH_GetCurrentConfigurationDescriptor
(USBH_INTERFACE_HANDLE hInterface,
U8 * pDescriptor,
unsigned * pBufferSize);
Parameters
Parameter | Description |
hInterface | Valid handle to an interface, returned by USBH_OpenInterface(). |
pDescriptor | Pointer to a buffer where the descriptor is stored. |
pBufferSize | in Size of the buffer pointed to by pDescriptor. out Number of bytes copied into the buffer. |
Return value
USBH_STATUS_SUCCESS on success. Other values indicate an error.
Additional information
The function returns a copy of the current configuration descriptor, that
was stored during the device enumeration. If the given buffer size is too small
the configuration descriptor returned is truncated.
USBH_GetDeviceDescriptor()
Description
Obsolete function, use USBH_GetDeviceDescriptorPtr().
Retrieves the current device descriptor of the device containing the given interface.
Prototype
USBH_STATUS USBH_GetDeviceDescriptor(USBH_INTERFACE_HANDLE hInterface,
U8 * pDescriptor,
unsigned * pBufferSize);
Parameters
Parameter | Description |
hInterface | Valid handle to an interface, returned by USBH_OpenInterface(). |
pDescriptor | Pointer to a buffer where the descriptor is stored. |
pBufferSize | in Size of the buffer pointed to by pDescriptor. out Number of bytes copied into the buffer. |
Return value
USBH_STATUS_SUCCESS on success. Other values indicate an error.
Additional information
The function returns a copy of the current device descriptor, that
was stored during the device enumeration. If the given buffer size is too small
the device descriptor returned is truncated.
USBH_GetDeviceDescriptorPtr()
Description
Returns a pointer to the device descriptor structure of the device containing the given interface.
Prototype
USBH_DEVICE_DESCRIPTOR *USBH_GetDeviceDescriptorPtr
(USBH_INTERFACE_HANDLE hInterface);
Parameters
Return value
Pointer to the current device descriptor information (read only), that
was stored during the device enumeration. The pointer gets invalid, when the
interface is closed using USBH_CloseInterface().
USBH_GetEndpointDescriptor()
Description
Retrieves an endpoint descriptor of the device containing the given interface.
Prototype
USBH_STATUS USBH_GetEndpointDescriptor
( USBH_INTERFACE_HANDLE hInterface,
U8 AlternateSetting,
const USBH_EP_MASK * pMask,
U8 * pBuffer,
unsigned * pBufferSize);
Parameters
Parameter | Description |
hInterface | Valid handle to an interface, returned by USBH_OpenInterface(). |
AlternateSetting | Specifies the alternate setting for the interface. The function returns endpoint descriptors that are inside the specified alternate setting. |
pMask | Pointer to a caller allocated structure of type USBH_EP_MASK, that specifies the endpoint selection pattern. |
pBuffer | Pointer to a buffer where the descriptor is stored. |
pBufferSize | in Size of the buffer pointed to by pBuffer. out Number of bytes copied into the buffer. |
Return value
USBH_STATUS_SUCCESS on success. Other values indicate an error.
Additional information
The endpoint descriptor is extracted from the current configuration descriptor, that
was stored during the device enumeration. If the given buffer size is too small
the endpoint descriptor returned is truncated.
Description
Retrieves the current frame number.
Prototype
USBH_STATUS USBH_GetFrameNumber(USBH_INTERFACE_HANDLE hInterface,
U32 * pFrameNumber);
Parameters
Parameter | Description |
hInterface | Valid handle to an interface, returned by USBH_OpenInterface(). |
pFrameNumber | Pointer to a variable that receives the frame number. |
Return value
USBH_STATUS_SUCCESS on success. Other values indicate an error.
Additional information
The frame number is transferred on the bus with 11 bits. This frame number is
returned as a 16 or 32 bit number related to the implementation of the host controller.
The last 11 bits are equal to the current frame. The frame number is increased
each millisecond if the host controller is running in full-speed mode,
or each 125 microsecond if the host controller is running in high-speed mode,
The returned frame number is related to the bus where the device is connected.
The frame numbers between different host controllers can be different.
CAUTION: The functionality is not implemented for all host drivers. For some host
controllers the function may always return a frame number of 0.
USBH_GetInterfaceDescriptor()
Description
Retrieves the interface descriptor of the given interface.
Prototype
USBH_STATUS USBH_GetInterfaceDescriptor(USBH_INTERFACE_HANDLE hInterface,
U8 AlternateSetting,
U8 * pBuffer,
unsigned * pBufferSize);
Parameters
Parameter | Description |
hInterface | Valid handle to an interface, returned by USBH_OpenInterface(). |
AlternateSetting | Specifies the alternate setting for this interface. |
pBuffer | Pointer to a buffer where the descriptor is stored. |
pBufferSize | in Size of the buffer pointed to by pBuffer. out Number of bytes copied into the buffer. |
Return value
USBH_STATUS_SUCCESS on success. Other values indicate an error.
Additional information
The interface descriptor is extracted from the current configuration descriptor, that
was stored during the device enumeration.
The interface descriptor belongs to the
interface that is identified by hInterface. If the interface has different
alternate settings the interface descriptors of each alternate setting can be
requested.
If the given buffer size is too small
the interface descriptor returned is truncated.
USBH_GetInterfaceId()
Description
Returns the interface id for a specified interface.
Prototype
USBH_INTERFACE_ID USBH_GetInterfaceId(USBH_INTERFACE_LIST_HANDLE hInterfaceList,
unsigned int Index);
Parameters
Parameter | Description |
hInterfaceList | Valid handle to a interface list, returned by USBH_CreateInterfaceList(). |
Index | Specifies the zero based index for an interface in the list. |
Return value
On success the interface Id for the interface specified by Index is returned. If the
interface index does not exist the function returns 0.
Additional information
The interface ID identifies a USB interface as long as the device is connected to the
host. If the device is removed and re-connected a new interface ID is assigned. The
interface ID is even valid if the interface list is deleted. The function can return an
interface ID even if the device is removed between the call to the function
USBH_CreateInterfaceList() and the call to this function. If this is the case, the
function USBH_OpenInterface() fails.
Example
See USBH_CreateInterfaceList.
USBH_GetInterfaceIdByHandle()
Description
Get the interface ID for a given index. A returned value of zero indicates an error.
Prototype
USBH_STATUS USBH_GetInterfaceIdByHandle(USBH_INTERFACE_HANDLE hInterface,
USBH_INTERFACE_ID * pInterfaceId);
Parameters
Parameter | Description |
hInterface | Handle to a valid interface, returned by USBH_OpenInterface(). |
pInterfaceId | Pointer to a variable that will receive the interface id. |
Return value
USBH_STATUS_SUCCESS on success.
Any other value means error.
Additional information
Returns the interface ID if the handle to the interface is available. This may be useful
if a Plug and Play notification is received and the application checks if it is related to
a given handle. The application can avoid calls to this function if the interface ID is
stored in the device context of the application.
USBH_GetInterfaceInfo()
Description
Obtain information about a specified interface.
Prototype
USBH_STATUS USBH_GetInterfaceInfo(USBH_INTERFACE_ID InterfaceID,
USBH_INTERFACE_INFO * pInterfaceInfo);
Parameters
Parameter | Description |
InterfaceID | ID of the interface to query. |
pInterfaceInfo | Pointer to a caller allocated structure that will receive the interface information on success. |
Return value
USBH_STATUS_SUCCESS on success.
Any other value means error.
Additional information
Can be used to identify a USB interface without having to open it. More detailed
information can be requested after the USB interface is opened.
If the interface belongs to a device
which is no longer connected to the host USBH_STATUS_DEVICE_REMOVED is
returned and pInterfaceInfo is not filled.
USBH_GetInterfaceSerial()
Description
Retrieves the serial number of the device containing the given interface.
Prototype
USBH_STATUS USBH_GetInterfaceSerial(USBH_INTERFACE_ID InterfaceID,
U32 BuffSize,
U8 * pSerialNumber,
U32 * pSerialNumberSize);
Parameters
Parameter | Description |
InterfaceID | ID of the interface to query. |
BuffSize | Size of the buffer pointed to by pSerialNumber. |
pSerialNumber | Pointer to a buffer where the serial number is stored. |
pSerialNumberSize | out Number of bytes copied into the buffer. |
Return value
USBH_STATUS_SUCCESS on success. Other values indicate an error.
Additional information
The serial number is returned as a UNICODE string in USB little endian format.
The number of valid bytes is returned in pSerialNumberSize. The string is not zero terminated.
The returned data does not contain a USB descriptor header and is encoded in the
first language Id. This string is a copy of the serial number string that was requested
during the enumeration.
If the device does not support a USB serial number string the function returns USBH_STATUS_SUCCESS
and a length of 0.
If the given buffer size is too small the serial number returned is truncated.
USBH_GetIADInfo()
Description
Obtains information about the corresponding Interface Association Descriptor
for an interface ID (if one is available).
Prototype
USBH_STATUS USBH_GetIADInfo(USBH_INTERFACE_ID InterfaceID,
USBH_IAD_INFO * pIADInfo);
Parameters
Parameter | Description |
InterfaceID | ID of an interface of the device to query. |
pIADInfo | Pointer to a caller allocated structure that will receive the IAD information on success. |
Return value
USBH_STATUS_SUCCESS on success.
Any other value means error.
USBH_GetPortInfo()
Description
Obtains information about a connected USB device.
Prototype
USBH_STATUS USBH_GetPortInfo(USBH_INTERFACE_ID InterfaceID,
USBH_PORT_INFO * pPortInfo);
Parameters
Parameter | Description |
InterfaceID | ID of an interface of the device to query. |
pPortInfo | Pointer to a caller allocated structure that will receive the port information on success. |
Return value
USBH_STATUS_SUCCESS on success.
Any other value means error.
USBH_GetSerialNumber()
Description
Retrieves the serial number of the device containing the given interface.
The serial number is returned as a UNICODE string in little endian format.
The number of valid bytes is returned in pBufferSize. The string is not zero terminated.
The returned data does not contain a USB descriptor header and is encoded in the
first language Id. This string is a copy of the serial number string that was requested
during the enumeration.
If the device does not support a USB serial number string the function returns USBH_STATUS_SUCCESS
and a length of 0.
If the given buffer size is too small the serial number returned is truncated.
Prototype
USBH_STATUS USBH_GetSerialNumber(USBH_INTERFACE_HANDLE hInterface,
U8 * pBuffer,
unsigned * pBufferSize);
Parameters
Parameter | Description |
hInterface | Valid handle to an interface, returned by USBH_OpenInterface(). |
pBuffer | Pointer to a buffer where the serial number is stored. |
pBufferSize | in Size of the buffer pointed to by pBuffer. out Number of bytes copied into the buffer. |
Return value
USBH_STATUS_SUCCESS on success. Other values indicate an error.
USBH_GetSerialNumberASCII()
Description
Retrieves the serial number of the device containing the given interface.
The serial number is returned as 0 terminated string.
The returned data does not contain a USB descriptor header and is encoded in the
first language Id. This string is a copy of the serial number string that was requested
during the enumeration. Non-ASCII characters are replaced by ’@’.
If the device does not support a USB serial number string the function returns USBH_STATUS_SUCCESS
and a zero length string.
If the given buffer size is too small the serial number returned is truncated.
The maximum string length returned is BuffSize - 1.
Prototype
USBH_STATUS USBH_GetSerialNumberASCII(USBH_INTERFACE_HANDLE hInterface,
char * pBuffer,
unsigned BufferSize);
Parameters
Parameter | Description |
hInterface | Valid handle to an interface, returned by USBH_OpenInterface(). |
pBuffer | Pointer to a buffer where the serial number is stored. |
BufferSize | Size of the buffer pointed to by pBuffer. |
Return value
USBH_STATUS_SUCCESS on success. Other values indicate an error.
USBH_GetStringDescriptorASCII()
Description
Retrieves a string from a string descriptor from the device containing the given interface.
The string returned is 0-terminated.
The returned data does not contain a USB descriptor header and is encoded in the
first language Id. Non-ASCII characters are replaced by ’@’.
If the given buffer size is too small the string is truncated.
The maximum string length returned is BufferSize - 1.
Prototype
USBH_STATUS USBH_GetStringDescriptorASCII(USBH_INTERFACE_HANDLE hInterface,
U8 StringIndex,
char * pBuffer,
unsigned BufferSize);
Parameters
Parameter | Description |
hInterface | Valid handle to an interface, returned by USBH_OpenInterface(). |
StringIndex | Index of the string. |
pBuffer | Pointer to a buffer where the string is stored. |
BufferSize | Size of the buffer pointed to by pBuffer. |
Return value
USBH_STATUS_SUCCESS on success. Other values indicate an error.
USBH_GetStringDescriptor()
Description
Retrieves the raw string descriptor from the device containing the given interface.
First two bytes of descriptor are type (always USB_STRING_DESCRIPTOR_TYPE) and length.
The rest contains a UTF-16 LE string.
If the given buffer size is too small the string is truncated.
Prototype
USBH_STATUS USBH_GetStringDescriptor(USBH_INTERFACE_HANDLE hInterface,
U8 StringIndex,
U16 LangID,
U8 * pBuffer,
unsigned * pNumBytes);
Parameters
Parameter | Description |
hInterface | Valid handle to an interface, returned by USBH_OpenInterface(). |
StringIndex | Index of the string. |
LangID | Language index. The default language of a device has the ID 0. See “Universal Serial Bus Language Identifiers (LANGIDs) version 1.0” for more details. This document is available on usb.org. |
pBuffer | Pointer to a buffer where the string is stored. |
pNumBytes | in Size of the buffer pointed to by pBuffer. out Number of bytes copied into the buffer. |
Return value
USBH_STATUS_SUCCESS on success. Other values indicate an error.
USBH_GetSpeed()
Description
Returns the operating speed of the device.
Prototype
USBH_STATUS USBH_GetSpeed(USBH_INTERFACE_HANDLE hInterface,
USBH_SPEED * pSpeed);
Parameters
Parameter | Description |
hInterface | Valid handle to an interface, returned by USBH_OpenInterface(). |
pSpeed | Pointer to a variable that will receive the speed information. |
Return value
USBH_STATUS_SUCCESS on success. Other values indicate an error.
Additional information
A high speed device can operate in full or high speed mode.
USBH_GetStatusStr()
Description
Converts the result status into a string.
Prototype
char *USBH_GetStatusStr(USBH_STATUS x);
Parameters
Parameter | Description |
x | Result status to convert. |
Return value
Pointer to a string which contains the result status in text form.
USBH_ISRTask()
Description
Processes the events triggered from the interrupt handler.
This function must run as a separate task in order to use the emUSBH stack.
The functions only returns, if the USBH stack is shut down (if USBH_Exit() was called).
In order for the emUSB-Host to work reliably, the task should have the highest
priority of all tasks dealing with USB.
Prototype
void USBH_ISRTask(void);
Additional information
This function waits for events from the interrupt
handler of the host controller and processes them.
When USBH_Exit() is used in the application this function should
not be directly started as a task, as it returns when USBH_Exit()
is called. A wrapper function can be used in this case,
see USBH_IsRunning() for a sample.
Note
Task priority requirements described in Tasks and interrupt usage must be considered.
USBH_Init()
Description
Initializes the emUSB-Host stack.
Prototype
void USBH_Init(void);
Additional information
Has to be called one time during startup before any other
function. The library initializes or allocates global resources
within this function.
USBH_MEM_GetMaxUsed()
Description
Returns the maximum used memory since initialization of the memory pool.
Prototype
U32 USBH_MEM_GetMaxUsed(int Idx);
Parameters
Parameter | Description |
Idx | Index of memory pool. 0 - normal memory 1 - transfer memory. |
Return value
Maximum used memory in bytes.
Additional information
This function only works in a debug configuration of emUSB-Host.
If compiled as release configuration, this function always returns 0.
USBH_SetRootPortPower()
Description
Set port of the root hub to a given power state.
The application must ensure that no transaction is pending on the port
before setting it into suspend state.
Prototype
void USBH_SetRootPortPower(U32 HCIndex,
U8 Port,
USBH_POWER_STATE State);
Parameters
Parameter | Description |
HCIndex | Index of the host controller. |
Port | Port number of the roothub. Ports are counted starting with 1. if set to 0, the new state is set to all ports of the root hub. |
State | New power state of the port. |
USBH_SetHubPortPower()
Description
Set port of an external hub to a given power state.
Prototype
USBH_STATUS USBH_SetHubPortPower(USBH_INTERFACE_ID InterfaceID,
U8 Port,
USBH_POWER_STATE State);
Parameters
Parameter | Description |
InterfaceID | Interface ID of the external hub. May be retrieved using USBH_GetPortInfo(). |
Port | Port number of the hub. Ports are counted starting with 1. |
State | New power state of the port (USBH_NORMAL_POWER, USBH_POWER_OFF or USBH_SUSPEND). |
Return value
USBH_STATUS_SUCCESS on success.
Any other value means error.
USBH_HUB_SuspendResume()
Description
Prepares hubs for suspend (stops the interrupt endpoint)
or re-starts the interrupt endpoint functionality after a resume.
This function may be used, if a port of a host controller is set to
suspend mode via the function USBH_SetRootPortPower().
The application must make sure that no transactions are running
on that port while it is suspended.
If there may be any external hubs connected to that port, then
polling of the interrupt endpoints of these hubs must be stopped while suspending.
To achieve this, USBH_HUB_SuspendResume() should be called with State = 0 before
USBH_SetRootPortPower(x, y, USBH_SUSPEND) and with State = 1 after resume with
USBH_SetRootPortPower(x, y, USBH_NORMAL_POWER).
All hubs connected to the given port of a host controller (directly or indirectly)
are handled by the function.
Prototype
void USBH_HUB_SuspendResume(U32 HCIndex,
U8 Port,
U8 State);
Parameters
Parameter | Description |
HCIndex | Index of the host controller. |
Port | Port number of the roothub. Ports are counted starting with 1. if set to 0, the function applies to all ports of the root hub. |
State | 0 - Prepare for suspend. 1 - Return from resume. |
USBH_GetNumRootPortConnections()
Description
Determine how many devices are directly connected to the host controllers
root hub ports. All physically connected devices are counted,
irrespective of the identification or enumeration of these devices.
Devices connected via a hub are not counted.
Prototype
unsigned USBH_GetNumRootPortConnections(U32 HCIndex);
Parameters
Parameter | Description |
HCIndex | Index of the host controller. |
Return value
Number of devices physically connected to the host controllers
root hub ports.
USBH_OpenInterface()
Description
Opens the specified interface.
Prototype
USBH_STATUS USBH_OpenInterface(USBH_INTERFACE_ID InterfaceID,
U8 Exclusive,
USBH_INTERFACE_HANDLE * pInterfaceHandle);
Parameters
Parameter | Description |
InterfaceID | Specifies the interface to open by its interface Id. The interface ID can be obtained by a call to USBH_GetInterfaceId(). |
Exclusive | Specifies if the interface should be opened exclusive or not. If the value is nonzero the function succeeds only if no other application has an open handle to this interface. |
pInterfaceHandle | Pointer where the handle to the opened interface is stored. |
Return value
USBH_STATUS_SUCCESS on success.
Any other value means error.
Additional information
The handle returned by this function via the pInterfaceHandle parameter is used by the
functions that perform data transfers. The returned handle must be closed with
USBH_CloseInterface() when it is no longer required.
If the interface is allocated exclusive no other
application can open it.
USBH_RegisterEnumErrorNotification()
Description
Registers a notification for a port enumeration error.
Prototype
USBH_ENUM_ERROR_HANDLE USBH_RegisterEnumErrorNotification
(void * pContext,
USBH_ON_ENUM_ERROR_FUNC * pfEnumErrorCallback);
Parameters
Parameter | Description |
pContext | A user defined pointer that is passed unchanged to the notification callback function. |
pfEnumErrorCallback | A pointer to a notification function of type USBH_ON_ENUM_ERROR_FUNC that is called if a port enumeration error occurs. |
Return value
On success a valid handle to the added notification is returned. A NULL is returned in
case of an error.
Additional information
To remove the notification USBH_UnregisterEnumErrorNotification() must be called. The
pfOnEnumError callback routine is called in the context of the process where the
interrupt status of a host controller is processed. The callback routine must not block.
USBH_RegisterPnPNotification()
Description
Registers a notification function for PnP events.
Prototype
USBH_NOTIFICATION_HANDLE USBH_RegisterPnPNotification
(const USBH_PNP_NOTIFICATION * pPnPNotification);
Parameters
Parameter | Description |
pPnPNotification | Pointer to a caller provided structure. |
Return value
On success a valid handle to the added notification is returned. A NULL is returned in
case of an error.
Additional information
An application can register any number of
notifications. The user notification routine is called in the context of a notify timer
that is global for all USB bus PnP notifications. If this function is called while the bus
driver has already enumerated devices that match the USBH_INTERFACE_MASK the
callback function passed in the USBH_PNP_NOTIFICATION structure is called for each
matching interface.
USBH_RestartEnumError()
Description
Restarts the enumeration process for all devices that have failed to enumerate.
Prototype
void USBH_RestartEnumError(void);
Additional information
If any problem occur during enumeration of a device, the device is reset and enumeration is retried.
To avoid an endless enumeration loop on broken devices there is a maximum retry count of 5 (USBH_RESET_RETRY_COUNTER).
After the retry count is expired, the port where the device is connected to is finally disabled.
Calling USBH_RestartEnumError() resets the retry counts and restarts enumeration on disabled ports.
USBH_SetCacheConfig()
Description
Configures cache related functionality that might be required by
the stack for several purposes such as cache handling in drivers.
Prototype
void USBH_SetCacheConfig(const SEGGER_CACHE_CONFIG * pConfig,
unsigned ConfSize);
Parameters
Parameter | Description |
pConfig | Pointer to an element of SEGGER_CACHE_CONFIG . |
ConfSize | Size of the passed structure in case library and header size of the structure differs. |
Additional information
This function has to called in USBH_X_Config().
USBH_SetOnSetPortPower()
Description
Sets a callback for the set-port-power driver function.
The user callback is called when the ports are added to the host driver instance, this
occurs during initialization, or when the ports are removed (during de-initialization).
Using this function is necessary if the port power is not controlled directly
through the USB controller but is provided from an external source.
Prototype
void USBH_SetOnSetPortPower(USBH_ON_SETPORTPOWER_FUNC * pfOnSetPortPower);
Parameters
Additional information
The callback function should not block.
USBH_ConfigPortPowerPinEx()
Description
Setups how the port-power pin should be set in order to
enable port for this port.
In normal case low means power enable. This feature must be
supported by the USBH driver.
Prototype
USBH_STATUS USBH_ConfigPortPowerPinEx(U32 HCIndex,
U8 SetHighIsPowerOn);
Parameters
Parameter | Description |
HCIndex | Index of the host controller. |
SetHighIsPowerOn | Select which logical voltage level enables the port. 1 - To enable port power, set the pin high. 0 - To enable port power, set the pin low. |
Return value
USBH_STATUS_SUCCESS | Configuration set. |
USBH_STATUS_ERROR | Invalid HCIndex. |
USBH_SetOnPortEvent()
Description
Sets a callback to report port events to the application.
Prototype
void USBH_SetOnPortEvent(USBH_ON_PORT_EVENT_FUNC * pfOnPortEvent);
Parameters
Additional information
The callback function should not block.
USBH_SubmitUrb()
Description
Submits an URB. Interface function for all asynchronous requests.
Prototype
USBH_STATUS USBH_SubmitUrb(USBH_INTERFACE_HANDLE hInterface,
USBH_URB * pUrb);
Parameters
Parameter | Description |
hInterface | Handle to a interface. |
pUrb | Pointer to a caller allocated structure. in The URB which should be submitted. out Submitted URB with the appropriate status and the received data if any. The storage for the URB must be permanent as long as the request is pending. The host controller can define special alignment requirements for the URB or the data transfer buffer. |
Return value
The request can fail for different reasons. In that case the return value is different
from USBH_STATUS_PENDING or USBH_STATUS_SUCCESS. If the function returns
USBH_STATUS_PENDING the completion function is called later. In all other cases the
completion routine is not called. If the function returns USBH_STATUS_SUCCESS, the
request was processed immediately. On error the request cannot be processed.
Additional information
If the status USBH_STATUS_PENDING is returned the ownership of the URB is passed to
the driver. The storage of the URB must not be freed nor modified as long as the
ownership is assigned to the driver. The driver passes the URB back to the
application by calling the completion routine. An URB that transfers data can be
pending for a long time.
Please make sure that the URB is not located in the stack. Otherwise the structure
may be corrupted in memory. Either use USBH_Malloc() or use global/static memory.
Notes
A pending URB transactions may be aborted with an abort request by using
USBH_SubmitUrb with a new URB where
Urb->Header.Function = USBH_FUNCTION_ABORT_ENDPOINT
and
Urb->Request.EndpointRequest.Endpoint = EndpointAddressToAbort.
Otherwise this operation will last until the device has responded to the request or the
device has been disconnected.
Example (asynchronous operation)
static U8 _Buffer[512];
static USBH_URB _Urb;
static void _OnUrbCompletion(USBH_URB * pUrb) {
if (pUrb->Header.Status == USBH_SUCCESS) {
ProcessData(pUrb->BulkIntRequest.pBuffer, pUrb->BulkIntRequest.Length);
} else {
// error handling ...
}
}
//
// Start IN transfer on interface 'hInterface' for endpoint 'Ep'
//
_Urb.Header.Function = USBH_FUNCTION_BULK_REQUEST;
_Urb.Header.pfOnCompletion = _OnUrbCompletion;
_Urb.Header.pContext = NULL;
_Urb.BulkIntRequest.pBuffer = &_Buffer[0];
_Urb.BulkIntRequest.Length = sizeof(_Buffer);
_Urb.BulkIntRequest.Endpoint = Ep;
Status = USBH_SubmitUrb(hInterface, pUrb);
if (Status != USBH_STATUS_PENDING) {
// error handling ...
}
Example (synchronous operation)
static U8 _Buffer[512];
static USBH_URB _Urb;
static void _OnUrbCompletion(USBH_URB * pUrb) {
USBH_OS_EVENT_OBJ *pEvent;
pEvent = (USBH_OS_EVENT_OBJ *)pUrb->Header.pContext;
USBH_OS_SetEvent(pEvent);
}
USBH_OS_EVENT_OBJ *pEvent;
//
// Start IN transfer on interface 'hInterface' for endpoint 'Ep'
//
pEvent = USBH_OS_AllocEvent();
_Urb.Header.Function = USBH_FUNCTION_BULK_REQUEST;
_Urb.Header.pfOnCompletion = _OnUrbCompletion;
_Urb.Header.pContext = pEvent;
_Urb.BulkIntRequest.pBuffer = &_Buffer[0];
_Urb.BulkIntRequest.Length = sizeof(_Buffer);
_Urb.BulkIntRequest.Endpoint = Ep;
Status = USBH_SubmitUrb(hInterface, pUrb);
if (Status != USBH_STATUS_PENDING) {
// error handling ...
} else {
USBH_OS_WaitEvent(pEvent);
if (_Urb.Header.Status == USBH_SUCCESS) {
ProcessData(_Urb.BulkIntRequest.pBuffer, _Urb.BulkIntRequest.Length);
} else {
// error handling ...
}
}
USBH_OS_FreeEvent(pEvent);
USBH_IsoDataCtrl()
Description
Acknowledge ISO data received from an IN EP or provide data for OUT EPs.
On order to start ISO OUT transfers after calling USBH_SubmitUrb(), initially
the output packet queue must be filled. For that purpose this function
must be called repeatedly until is does not return USBH_STATUS_NEED_MORE_DATA any more.
Prototype
USBH_STATUS USBH_IsoDataCtrl(const USBH_URB * pUrb,
USBH_ISO_DATA_CTRL * pIsoData);
Parameters
Parameter | Description |
pUrb | Pointer to the an active URB running ISO transfers. |
pIsoData | ISO data structure. |
Return value
USBH_STATUS_SUCCESS or USBH_STATUS_NEED_MORE_DATA on success or error code on failure.
USBH_Task()
Description
Manages the internal software timers.
This function must run as a separate task in order to use the emUSBH stack.
The functions only returns, if the USBH stack is shut down (if USBH_Exit() was called).
Prototype
void USBH_Task(void);
Additional information
The function iterates over the list of active timers
and invokes the registered callback functions in case the timer expired.
When USBH_Exit() is used in the application this function should
not be directly started as a task, as it returns when USBH_Exit()
is called. A wrapper function can be used in this case,
see USBH_IsRunning() for a sample.
Note
Task priority requirements described in Tasks and interrupt usage must be considered.
USBH_IsRunning()
Description
Returns whether the stack is running or not.
Prototype
int USBH_IsRunning(void);
Return value
0 | USBH is not running |
1 | USBH is running |
Example
/*********************************************************************
*
* _USBH_Task
*
* Function description
* Wrapper task for emUSBH USBH_Task.
* Before the function is called, the task stays in a loop to
* check whether the emUSBH stack is running.
*/
static void _USBH_Task(void) {
while (1) {
//
// Wait until USBH is Ready
//
while (USBH_IsRunning() == 0) {
OS_Delay(10);
}
USBH_Task();
}
}
/*********************************************************************
*
* _USBH_ISRTask
*
* Function description
* Wrapper task for emUSBH USBH_ISRTask.
* Before the function is called, the task stays in a loop to
* check whether the emUSBH stack is running.
*/
static void _USBH_ISRTask(void) {
while (1) {
//
// Wait until USBH is Ready
//
while (USBH_IsRunning() == 0) {
OS_Delay(10);
}
USBH_ISRTask();
}
}
USBH_UnregisterEnumErrorNotification()
Description
Removes a registered notification for a port enumeration error.
Prototype
void USBH_UnregisterEnumErrorNotification(USBH_ENUM_ERROR_HANDLE hEnumError);
Parameters
Additional information
Must be called for a port enumeration error notification that was successfully
registered by a call to USBH_RegisterEnumErrorNotification().
USBH_UnregisterPnPNotification()
Description
Removes a previously registered notification for PnP events.
Prototype
void USBH_UnregisterPnPNotification(USBH_NOTIFICATION_HANDLE hNotification);
Parameters
Additional information
Must be called for to unregister a PnP notification that was successfully registered by a call to
USBH_RegisterPnPNotification().
Data structures
The table below lists the available data structures.
USBH_BULK_INT_REQUEST
Description
Defines parameters for a BULK or INT transfer request.
Used with USBH_FUNCTION_BULK_REQUEST and USBH_FUNCTION_INT_REQUEST.
Type definition
typedef struct {
U8 Endpoint;
void * pBuffer;
U32 Length;
} USBH_BULK_INT_REQUEST;
Structure members
Member | Description |
Endpoint | Specifies the endpoint address with direction bit. |
pBuffer | Pointer to a caller provided buffer. |
Length | in length of data / size of buffer (in bytes). out Bytes transferred. |
USBH_CONTROL_REQUEST
Description
Defines parameters for a CONTROL transfer request.
Used with USBH_FUNCTION_CONTROL_REQUEST.
Type definition
typedef struct {
USBH_SETUP_PACKET Setup;
void * pBuffer;
U32 Length;
} USBH_CONTROL_REQUEST;
Structure members
Member | Description |
Setup | The setup packet, direction of data phase, the length field must be valid! |
pBuffer | Pointer to the caller provided storage, can be NULL. This buffer is used in the data phase to transfer the data. The direction of the data transfer depends from the Type field in the Setup. See the USB specification for details. |
Length | Returns the number of bytes transferred in the data phase. Output value only: Set by the driver. |
Additional information
A control request consists of a setup phase, an
optional data phase, and a handshake phase. The data phase is limited to a length of
4096 bytes. The Setup data structure must be filled in properly. The length field in
the Setup must contain the size of the Buffer. The caller must provide the storage
for the Buffer.
With this request any setup packet can be submitted. Some standard requests, like
SetAddress can be sent but would lead to a breakdown of the communication. It is not
allowed to set the following standard requests:
SetAddress:
It is assigned by the USB stack during enumeration or USB reset.
Clear Feature Endpoint Halt:
Use USBH_FUNCTION_RESET_ENDPOINT instead. The function
USBH_FUNCTION_RESET_ENDPOINT resets the data toggle bit in the host controller
structures.
SetConfiguration
USBH_ISO_REQUEST
Description
Defines parameters for a ISO transfer request.
Used with USBH_FUNCTION_ISO_REQUEST.
Only Endpoint must be set to submit an ISO URB.
All other members are set by the driver, before the completion routine
is called.
For every packet send or received, the members of this structure are filled,
Header.Status is set to USBH_STATUS_SUCCESS and the callback function is called.
This is repeated until the URB is explicitly canceled.
The URB is finally terminated, if Header.Status ≠ USBH_STATUS_SUCCESS.
Type definition
typedef struct {
U8 Endpoint;
U8 NBuffers;
U16 Length;
const void * pData;
USBH_STATUS Status;
} USBH_ISO_REQUEST;
Structure members
Member | Description |
Endpoint | in Specifies the endpoint address with direction bit. |
NBuffers | out Number of buffers used by the driver. |
Length | out Length of the data packet received (IN EPs only). |
pData | out Pointer to the data packet received (IN EPs only). |
Status | out Status of the transaction. |
USBH_ENDPOINT_REQUEST
Description
Defines parameter for an endpoint operation.
Used with USBH_FUNCTION_ABORT_ENDPOINT and USBH_FUNCTION_RESET_ENDPOINT.
Type definition
typedef struct {
U8 Endpoint;
} USBH_ENDPOINT_REQUEST;
Structure members
Member | Description |
Endpoint | Specifies the endpoint address with direction bit. |
USBH_ENUM_ERROR
Description
Is used as a notification parameter for the USBH_ON_ENUM_ERROR_FUNC callback function.
This data structure does not contain detailed information about the device that
fails at enumeration because this information is not available in all phases of the enumeration.
Type definition
typedef struct {
unsigned Flags;
int PortNumber;
USBH_STATUS Status;
int ExtendedErrorInformation;
} USBH_ENUM_ERROR;
Structure members
Member | Description |
Flags | Additional flags to determine the location and the type of the error. USBH_ENUM_ERROR_EXTHUBPORT_FLAG means the device is connected to an external hub. USBH_ENUM_ERROR_RETRY_FLAG the bus driver retries the enumeration of this device automatically. USBH_ENUM_ERROR_STOP_ENUM_FLAG the bus driver does not restart the enumeration for this device because all retries have failed. The application can force the bus driver to restart the enumeration by calling the function USBH_RestartEnumError. USBH_ENUM_ERROR_DISCONNECT_FLAG means the device has been disconnected during the enumeration. If the hub port reports a disconnect state the device cannot be re-enumerated by the bus driver automatically. Also the function USBH_RestartEnumError cannot re-enumerate the device. USBH_ENUM_ERROR_ROOT_PORT_RESET means an error during the USB reset of a root hub port occurs. USBH_ENUM_ERROR_HUB_PORT_RESET means an error during a reset of an external hub port occurs. |
PortNumber | Port number of the parent port where the USB device is connected. A flag in the PortFlags field determines if this is an external hub port. |
Status | Status of the failed operation. |
ExtendedErrorInformation | Internal information used for debugging. |
USBH_EP_MASK
Description
Is used as an input parameter to get an endpoint descriptor. The comparison with the
mask is true if each member that is marked as valid by a flag in the mask member is
equal to the value stored in the endpoint. E.g. if the mask is 0 the first endpoint is
returned. If Mask is set to USBH_EP_MASK_INDEX the zero based index can be used to
address all endpoints.
Type definition
typedef struct {
U32 Mask;
U8 Index;
U8 Address;
U8 Type;
U8 Direction;
} USBH_EP_MASK;
Structure members
Member | Description |
Mask | This member contains the information which fields are valid. It is an OR combination of the following flags: USBH_EP_MASK_INDEX The Index is used for comparison. USBH_EP_MASK_ADDRESS The Address field is used for comparison. USBH_EP_MASK_TYPE The Type field is used for comparison. USBH_EP_MASK_DIRECTION The Direction field is used for comparison. |
Index | If valid, this member contains the zero based index of the endpoint in the interface. |
Address | If valid, this member contains an endpoint address with direction bit. |
Type | If valid, this member contains the type of the endpoint: USB_EP_TYPE_CONTROL USB_EP_TYPE_BULK USB_EP_TYPE_ISO USB_EP_TYPE_INT |
Direction | If valid, this member specifies a direction. It is one of the following values: USB_IN_DIRECTION From device to host USB_OUT_DIRECTION From host to device |
Description
Common parameters for all URB based requests.
Type definition
typedef struct {
USBH_FUNCTION Function;
USBH_STATUS Status;
USBH_ON_COMPLETION_FUNC * pfOnCompletion;
void * pContext;
USBH_ON_COMPLETION_FUNC * pfOnInternalCompletion;
void * pInternalContext;
U32 HcFlags;
USBH_ON_COMPLETION_USER_FUNC * pfOnUserCompletion;
void * pUserContext;
USB_DEVICE * pDevice;
} USBH_HEADER;
Structure members
Member | Description |
Function | Function code defines the operation of the URB. |
Status | After completion this member contains the status for the request. |
pfOnCompletion | Caller provided pointer to the completion function. This completion function is called if the function USBH_SubmitUrb() returns USBH_STATUS_PENDING. If a different status code is returned the completion function is never called. |
pContext | This member can be used by the caller to store a context passed to the completion routine. |
pfOnInternalCompletion | Internal use. |
pInternalContext | Internal use. |
HcFlags | Internal use. |
pfOnUserCompletion | Internal use. |
pUserContext | Internal use. |
pDevice | Internal use. |
USBH_INTERFACE_INFO
Description
This structure contains information about a USB interface and the related device
and is returned by the function USBH_GetInterfaceInfo().
Type definition
typedef struct {
USBH_INTERFACE_ID InterfaceId;
USBH_DEVICE_ID DeviceId;
U16 VendorId;
U16 ProductId;
U16 bcdDevice;
U8 Interface;
U8 Class;
U8 SubClass;
U8 Protocol;
unsigned int OpenCount;
U8 ExclusiveUsed;
USBH_SPEED Speed;
U8 SerialNumberSize;
U8 NumConfigurations;
U8 CurrentConfiguration;
U8 HCIndex;
U8 AlternateSetting;
} USBH_INTERFACE_INFO;
Structure members
Member | Description |
InterfaceId | The unique interface Id. This ID is assigned if the USB device was successful enumerated. It is valid until the device is removed for the host. If the device is reconnected a different interface ID is assigned to each interface. |
DeviceId | The unique device Id. This ID is assigned if the USB device was successfully enumerated. It is valid until the device is removed from the host. If the device is reconnected a different device ID is assigned. The relation between the device ID and the interface ID can be used by an application to detect which USB interfaces belong to a device. |
VendorId | The Vendor ID of the device. |
ProductId | The Product ID of the device. |
bcdDevice | The BCD coded device version. |
Interface | The USB interface number. |
Class | The interface class. |
SubClass | The interface sub class. |
Protocol | The interface protocol. |
OpenCount | Number of open handles for this interface. |
ExclusiveUsed | If not 0, this interface is used exclusively. |
Speed | Operation speed of the device. |
SerialNumberSize | The size of the serial number in bytes, 0 means not available or error during request. The serial number itself can be retrieved using USBH_GetInterfaceSerial(). |
NumConfigurations | Number of different configuration of the device. |
CurrentConfiguration | Currently selected configuration, zero-based: 0…(NumConfigurations-1) |
HCIndex | Index of the host controller the device is connected to. |
AlternateSetting | The current alternate setting for this interface. |
USBH_INTERFACE_MASK
Description
Data structure that defines conditions to select USB interfaces.
Can be used to register notifications. Members that are not selected
with Mask need not be initialized.
Type definition
typedef struct {
U16 Mask;
U16 VendorId;
U16 ProductId;
U16 bcdDevice;
U8 Interface;
U8 Class;
U8 SubClass;
U8 Protocol;
const U16 * pVendorIds;
const U16 * pProductIds;
U16 NumIds;
} USBH_INTERFACE_MASK;
Structure members
Member | Description |
Mask | Contains an OR combination of the following flags. If the flag is set the related member of this structure is compared to the properties of the USB interface. USBH_INFO_MASK_VID Compare the Vendor ID (VID) of the device. USBH_INFO_MASK_PID Compare the Product ID (PID) of the device. USBH_INFO_MASK_DEVICE Compare the bcdDevice value of the device. USBH_INFO_MASK_INTERFACE Compare the interface number. USBH_INFO_MASK_CLASS Compare the class of the interface. USBH_INFO_MASK_SUBCLASS Compare the sub class of the interface. USBH_INFO_MASK_PROTOCOL Compare the protocol of the interface. USBH_INFO_MASK_VID_ARRAY Compare the Vendor ID (VID) of the device to a list if ids. USBH_INFO_MASK_PID_ARRAY Compare the Product ID (PID) of the device to a list if ids. If both USBH_INFO_MASK_VID_ARRAY and USBH_INFO_MASK_PID_ARRAY are selected, then the VendorId/ProductId of the device is compared to pairs pVendorIds[i]/pProductIds[i]. |
VendorId | Vendor ID to compare with. |
ProductId | Product ID to compare with. |
bcdDevice | BCD coded device version to compare with. |
Interface | Interface number to compare with. |
Class | Class code to compare with. |
SubClass | Sub class code to compare with. |
Protocol | Protocol stored in the interface to compare with. |
pVendorIds | Points to an array of Vendor IDs. |
pProductIds | Points to an array of Product IDs. |
NumIds | Number of ids in *pVendorIds and *pProductIds. When only USBH_INFO_MASK_VID_ARRAY is set this is the size of the pVendorIds array. When only USBH_INFO_MASK_PID_ARRAY is set this is the size of the pProductIds array. When both are set this is the size for both arrays (the arrays have to be the same size when both flags are set). |
USBH_PNP_NOTIFICATION
Description
Is used as an input parameter for the USBH_RegisterEnumErrorNotification()
function.
Type definition
typedef struct {
USBH_ON_PNP_EVENT_FUNC * pfPnpNotification;
void * pContext;
USBH_INTERFACE_MASK InterfaceMask;
} USBH_PNP_NOTIFICATION;
Structure members
Member | Description |
pfPnpNotification | The notification function that is called from the USB stack if a PnP event occurs. |
pContext | Pointer to a context, that is passed to the notification function. |
InterfaceMask | Mask for the interfaces for which the PnP notifiation should be called. |
USBH_PORT_INFO
Description
Information about a connected USB device returned by USBH_GetPortInfo().
Type definition
typedef struct {
U8 IsHighSpeedCapable;
U8 IsRootHub;
U8 IsSelfPowered;
U8 HCIndex;
U16 MaxPower;
U16 PortNumber;
USBH_SPEED PortSpeed;
USBH_DEVICE_ID DeviceId;
USBH_DEVICE_ID HubDeviceId;
USBH_INTERFACE_ID HubInterfaceId;
U32 PortStatus;
} USBH_PORT_INFO;
Structure members
Member | Description |
IsHighSpeedCapable | 1: Port supports high-speed, full-speed and low-speed communication. 0: Port supports only full-speed and low-speed communication. |
IsRootHub | 1: RootHub, device is directly connected to the host. 0: Device is connected via an external hub to the host. |
IsSelfPowered | 1: Device is externally powered 0: Device is powered by USB host controller. |
HCIndex | Index of the host controller the device is connected to. |
MaxPower | Max power the USB device consumes from USB host controller / USB hub in mA. |
PortNumber | Port number of the hub or roothub. Ports are counted starting with 1. |
PortSpeed | The port speed is the speed with which the device is connected. Can be either USBH_LOW_SPEED or USBH_FULL_SPEED or USBH_HIGH_SPEED. |
DeviceId | The unique device Id. This ID is assigned if the USB device was successfully enumerated. It is valid until the device is removed from the host. If the device is reconnected a different device ID is assigned. The relation between the device ID and the interface ID can be used by an application to detect which USB interfaces belong to a device. |
HubDeviceId | The unique device ID of the hub, if the device is connected via an external hub. If IsRootHub = 1, then HubDeviceId is zero. |
HubInterfaceId | Interface ID of the hub, if the device is connected via an external hub. If IsRootHub = 1, then HubInterfaceId is zero. |
PortStatus | Contents of the port status register of the hub. |
USBH_PORT_EVENT
Description
Information about an event occurred on a port of a root hub or external hub.
Type definition
typedef struct {
USBH_PORT_EVENT_TYPE Event;
U8 HCIndex;
U8 PortNumber;
USBH_INTERFACE_ID HubInterfaceId;
} USBH_PORT_EVENT;
Structure members
Member | Description |
Event | Event detected on the port. |
HCIndex | Index of the host controller the port is connected to. |
PortNumber | Port number of the hub or root hub. Ports are counted starting with 1. |
HubInterfaceId | Interface ID of the hub, if the device is connected via an external hub. If the port belongs to a root hub, then HubInterfaceId is zero. |
USBH_SET_INTERFACE
Description
Defines parameters for a control request to set an alternate interface setting.
Used with USBH_FUNCTION_SET_INTERFACE.
Type definition
typedef struct {
U8 AlternateSetting;
} USBH_SET_INTERFACE;
Structure members
Member | Description |
AlternateSetting | Number of alternate interface setting (zero based). |
USBH_SET_POWER_STATE
Description
Defines parameters to set or reset suspend mode for a device.
Used with USBH_FUNCTION_SET_POWER_STATE.
Type definition
typedef struct {
USBH_POWER_STATE PowerState;
} USBH_SET_POWER_STATE;
Structure members
Member | Description |
PowerState | New power state of the device. |
Additional information
If the device is switched to suspend, there must be no pending requests on the device.
USBH_URB
Description
This data structure is used to submit an URB.
The URB is the basic structure for all asynchronous operations on the USB stack. All
requests that exchange data with the device are using this data structure. The caller
has to provide the memory for this structure. The memory must be permanent until
the completion function is called.
Prototype
struct _USBH_URB {
USBH_HEADER Header;
union {
USBH_CONTROL_REQUEST ControlRequest;
USBH_BULK_INT_REQUEST BulkIntRequest;
USBH_ISO_REQUEST IsoRequest;
USBH_ENDPOINT_REQUEST EndpointRequest;
USBH_SET_INTERFACE SetInterface;
USBH_SET_POWER_STATE SetPowerState;
} Request;
};
Member | Description |
Header | Contains the URB header of type USBH_HEADER. The most important
parameters are the function code and the callback function. |
Request | A union that contains information depending on the specific
request of the USBH_HEADER. See description of the individual sub structures. |
SEGGER_CACHE_CONFIG
Description
Used to pass cache configuration and callback function pointers to the stack.
Prototype
typedef struct {
int CacheLineSize;
void (*pfDMB) (void);
void (*pfClean) (void *p, unsigned long NumBytes);
void (*pfInvalidate)(void *p, unsigned long NumBytes);
} SEGGER_CACHE_CONFIG;
Member | Description |
CacheLineSize | Cache line size of the CPU in bytes. Most Systems such as ARM9 use a 32 bytes cache line size. |
pfDMB | Unused. |
pfClean | Pointer to a callback function that executes a clean operation on cached memory.
The parameter ’p’ is always cache aligned. ’NumBytes’ must be rounded up by the function
to the next multiple of the cache line size, if necessary. |
pfInvalidate | Pointer to a callback function that executes an invalidate operation on cached memory.
The parameter ’p’ is always cache aligned. ’NumBytes’ must be rounded up by the function
to the next multiple of the cache line size, if necessary. |
Additional information
For further information about how this structure is used please refer to
USBH_SetCacheConfig.
USBH_ISO_DATA_CTRL
Description
This data structure is used to provide or acknowledge ISO data.
Used with function USBH_IsoDataCtrl().
Type definition
typedef struct {
U32 Length;
const U8 * pData;
U32 Length2;
const U8 * pData2;
const U8 * pBuffer;
} USBH_ISO_DATA_CTRL;
Structure members
Member | Description |
Length | in Length of the first data part to be transferred via ISO OUT EP in bytes. The ISO packet send has size ’Length’ + ’Length2’. |
pData | in Pointer to the first data part to be transferred via ISO OUT EP. The ISO packet send is constructed by concatenating both data parts ’pData’ and ’pData2’. |
Length2 | in Length of the second data part to be transferred via ISO OUT EP in bytes (optional). |
pData2 | in Pointer to the second data part to be transferred via ISO OUT EP. |
pBuffer | out Buffer used by the driver. |
USBH_IAD_INFO
Description
Information about an Interface Association Descriptor returned by USBH_GetIADInfo().
Type definition
typedef struct {
USBH_INTERFACE_ID aInterfaceIDs[];
U8 NumIDs;
U8 FunctionClass;
U8 FunctionSubClass;
U8 FunctionProtocol;
U8 iFunction;
} USBH_IAD_INFO;
Structure members
Member | Description |
aInterfaceIDs | Interface IDs which are combined by the IAD |
NumIDs | Number of valid interface IDs inside aInterfaceIDs. |
FunctionClass | Class code. |
FunctionSubClass | Subclass code. |
FunctionProtocol | Protocol code. |
iFunction | Index of string descriptor describing this function. |
Enumerations
The table below lists the available enumerations.
USBH_DEVICE_EVENT
Description
Enum containing the device events.
Enumerates the types of device events. It is used by the
USBH_NOTIFICATION_FUNC callback to indicate which type of event occurred.
Type definition
typedef enum {
USBH_DEVICE_EVENT_ADD,
USBH_DEVICE_EVENT_REMOVE
} USBH_DEVICE_EVENT;
Enumeration constants
Constant | Description |
USBH_DEVICE_EVENT_ADD | Indicates that a device was connected to the host and new interface is available. |
USBH_DEVICE_EVENT_REMOVE | Indicates that a device has been removed. |
USBH_FUNCTION
Description
Is used as a member for the USBH_HEADER data structure.
All function codes use the API function USBH_SubmitUrb() and are handled asynchronously.
Type definition
typedef enum {
USBH_FUNCTION_CONTROL_REQUEST,
USBH_FUNCTION_BULK_REQUEST,
USBH_FUNCTION_INT_REQUEST,
USBH_FUNCTION_ISO_REQUEST,
USBH_FUNCTION_RESET_DEVICE,
USBH_FUNCTION_RESET_ENDPOINT,
USBH_FUNCTION_ABORT_ENDPOINT,
USBH_FUNCTION_SET_INTERFACE,
USBH_FUNCTION_SET_POWER_STATE,
USBH_FUNCTION_CONFIGURE_EPS
} USBH_FUNCTION;
Enumeration constants
Constant | Description |
USBH_FUNCTION_CONTROL_REQUEST | Is used to send an URB with a control request. It uses the data structure USBH_CONTROL_REQUEST. A control request includes standard, class and vendor defines requests. The standard requests SetAddress, SetConfiguration and SetInterface can not be submitted by this request. These requests require a special handling in the driver. See USBH_FUNCTION_SET_INTERFACE for details. |
USBH_FUNCTION_BULK_REQUEST | Is used to transfer data to or from a bulk endpoint. It uses the data structure USBH_BULK_INT_REQUEST. |
USBH_FUNCTION_INT_REQUEST | Is used to transfer data to or from an interrupt endpoint. It uses the data structure USBH_BULK_INT_REQUEST. The interval is defined by the endpoint descriptor. |
USBH_FUNCTION_ISO_REQUEST | Is used to transfer data to or from an ISO endpoint. It uses the data structure USBH_ISO_REQUEST. ISO transfer may not be supported by all host controllers. |
USBH_FUNCTION_RESET_DEVICE | Sends a USB reset to the device. This removes the device and all its interfaces from the USB stack. The application should abort all pending requests and close all handles to this device. All handles become invalid. The USB stack then starts a new enumeration of the device. All interfaces will get new interface Ids. This request can be part of an error recovery or part of special class protocols like DFU. This function uses only the URB header. |
USBH_FUNCTION_RESET_ENDPOINT | Clears an error condition on a special endpoint. If a data transfer error occurs that cannot be handled in hardware the driver stops the endpoint and does not allow further data transfers before the endpoint is reset with this function. On a bulk or interrupt endpoint the host driver sends a Clear Feature Endpoint Halt request. This informs the device about the hardware error. The driver resets the data toggle bit for this endpoint. This request expects that no pending URBs are scheduled on this endpoint. Pending URBs must be aborted with the URB based function USBH_FUNCTION_ABORT_ENDPOINT. This function uses the data structure USBH_ENDPOINT_REQUEST. |
USBH_FUNCTION_ABORT_ENDPOINT | Aborts all pending requests on an endpoint. The host controller calls the completion function with a status code USBH_STATUS_CANCELED. The completion of the URBs may be delayed. The application should wait until all pending requests have been returned by the driver before the handle is closed or USBH_FUNCTION_RESET_ENDPOINT is called. |
USBH_FUNCTION_SET_INTERFACE | Selects a new alternate setting for the interface. There must be no pending requests on any endpoint to this interface. The interface handle does not become invalid during this operation. The number of endpoints may be changed. This request uses the data structure USBH_SET_INTERFACE. |
USBH_FUNCTION_SET_POWER_STATE | Is used to set the power state for a device. There must be no pending requests for this device if the device is set to the suspend state. The request uses the data structure USBH_SET_POWER_STATE. After the enumeration the device is in normal power state. |
USBH_FUNCTION_CONFIGURE_EPS | Internal use. |
USBH_PNP_EVENT
Description
Is used as a parameter for the PnP notification.
Type definition
typedef enum {
USBH_ADD_DEVICE,
USBH_REMOVE_DEVICE
} USBH_PNP_EVENT;
Enumeration constants
Constant | Description |
USBH_ADD_DEVICE | Indicates that a device was connected to the host and a new interface is available. |
USBH_REMOVE_DEVICE | Indicates that a device has been removed. |
USBH_POWER_STATE
Description
Enumerates the power states of a device.
Is used as a member in the USBH_SET_POWER_STATE data structure.
Type definition
typedef enum {
USBH_NORMAL_POWER,
USBH_SUSPEND,
USBH_POWER_OFF
} USBH_POWER_STATE;
Enumeration constants
Constant | Description |
USBH_NORMAL_POWER | The device is switched to normal operation. |
USBH_SUSPEND | The device is switched to USB suspend mode. |
USBH_POWER_OFF | The device is powered off. |
USBH_SPEED
Description
Enum containing operation speed values of a device.
Is used as a member in the USBH_INTERFACE_INFO data structure
and to get the operation speed of a device.
Type definition
typedef enum {
USBH_SPEED_UNKNOWN,
USBH_LOW_SPEED,
USBH_FULL_SPEED,
USBH_HIGH_SPEED,
USBH_SUPER_SPEED
} USBH_SPEED;
Enumeration constants
Constant | Description |
USBH_SPEED_UNKNOWN | The speed is unknown. |
USBH_LOW_SPEED | The device operates in low-speed mode. |
USBH_FULL_SPEED | The device operates in full-speed mode. |
USBH_HIGH_SPEED | The device operates in high-speed mode. |
USBH_SUPER_SPEED | The device operates in SuperSpeed mode. |
USBH_PORT_EVENT_TYPE
Description
Defines an event type for USB ports.
Currently only one event type is defined. May be extended in the future.
Type definition
typedef enum {
USBH_PORT_EVENT_OVER_CURRENT
} USBH_PORT_EVENT_TYPE;
Enumeration constants
Constant | Description |
USBH_PORT_EVENT_OVER_CURRENT | An over current condition has been detected on the hub port. |
Function Types
The table below lists the available function types.
USBH_NOTIFICATION_FUNC
Description
Type of user callback set in USBH_PRINTER_RegisterNotification(),
USBH_HID_RegisterNotification(), USBH_CDC_AddNotification(),
USBH_FT232_RegisterNotification() and USBH_MTP_RegisterNotification().
Type definition
typedef void (USBH_NOTIFICATION_FUNC)(void * pContext,
U8 DevIndex,
USBH_DEVICE_EVENT Event);
Parameters
Parameter | Description |
pContext | Pointer to a context passed by the user in the call to one of the register functions. |
DevIndex | Zero based index of the device that was added or removed. First device has index 0, second one has index 1, etc |
Event | Enum USBH_DEVICE_EVENT which gives information about the event that occurred. |
USBH_ON_COMPLETION_FUNC
Description
Is called by the library when an URB request completes.
Type definition
typedef void (USBH_ON_COMPLETION_FUNC)(USBH_URB * pUrb);
Parameters
Parameter | Description |
pUrb | Contains the URB that was completed. |
Additional information
Is called in the context of the USBH_Task() or USBH_ISRTask().
USBH_ON_ENUM_ERROR_FUNC
Description
Is called by the library if an error occurs at enumeration stage.
Type definition
typedef void (USBH_ON_ENUM_ERROR_FUNC)( void * pContext,
const USBH_ENUM_ERROR * pEnumError);
Parameters
Parameter | Description |
pContext | Is a user defined pointer that was passed to USBH_RegisterEnumErrorNotification(). |
pEnumError | Pointer to a structure containing information about the error occurred. This structure is temporary and must not be accessed after the functions returns. |
Additional information
Is called in the context of USBH_Task() function or of a ProcessInterrupt function of a
host controller. Before this function is called it must be registered with
USBH_RegisterEnumErrorNotification(). If a device is not successfully enumerated
the function USBH_RestartEnumError() can be called to re-start a new enumeration
in the context of this function. This callback mechanism is part of the enhanced
error recovery.
USBH_ON_PNP_EVENT_FUNC
Description
Is called by the library if a PnP event occurs and if a PnP notification was registered.
Type definition
typedef void (USBH_ON_PNP_EVENT_FUNC)(void * pContext,
USBH_PNP_EVENT Event,
USBH_INTERFACE_ID InterfaceId);
Parameters
Parameter | Description |
pContext | Is the user defined pointer that was passed to USBH_RegisterEnumErrorNotification(). The library does not dereference this pointer. |
Event | Enum USBH_DEVICE_EVENT specifies the PnP event. |
InterfaceId | Contains the interface ID of the removed or added interface. |
Additional information
Is called in the context of USBH_Task() function. In the context of this function all
other API functions of the USB host stack can be called. The removed or added interface
can be identified by the interface Id. The client can use this information to find the
related USB Interface and close all handles if it was in use, to open it or to collect
information about the interface.
USBH_ON_SETPORTPOWER_FUNC
Description
Callback set by USBH_SetOnSetPortPower(). Is called when port power should be changed.
Type definition
typedef void (USBH_ON_SETPORTPOWER_FUNC)(U32 HostControllerIndex,
U8 Port,
U8 PowerOn);
Parameters
Parameter | Description |
HostControllerIndex | Index of the host controller. This corresponds to the return value of the respective USBH_<DriverName>_Add call. |
Port | 1-based port index. |
PowerOn | 0 - power off 1 - power on |
USBH_CHECK_ADDRESS_FUNC
Description
Checks if an address can be used for transfers.
The function must return 0, if access is allowed for the given address,
1 otherwise.
Type definition
typedef int USBH_CHECK_ADDRESS_FUNC(const void * pMem);
Parameters
Parameter | Description |
pMem | Pointer to the memory. |
Return value
- 0 - Memory can be used for access.
- 1 - Access not allowed for the given address.
USBH_ON_PORT_EVENT_FUNC
Description
Callback set by USBH_SetOnPortEvent(). Is called when an event occurs on a port.
Type definition
typedef void (USBH_ON_PORT_EVENT_FUNC)(const USBH_PORT_EVENT * pPortEvent);
Parameters
Parameter | Description |
pPortEvent | Pointer to information about the port even. |
USBH_STATUS
Description
Status codes returned by most of the API functions.
Type definition
typedef enum {
USBH_STATUS_SUCCESS,
USBH_STATUS_CRC,
USBH_STATUS_BITSTUFFING,
USBH_STATUS_DATATOGGLE,
USBH_STATUS_STALL,
USBH_STATUS_NOTRESPONDING,
USBH_STATUS_PID_CHECK,
USBH_STATUS_UNEXPECTED_PID,
USBH_STATUS_DATA_OVERRUN,
USBH_STATUS_DATA_UNDERRUN,
USBH_STATUS_XFER_SIZE,
USBH_STATUS_DMA_ERROR,
USBH_STATUS_BUFFER_OVERRUN,
USBH_STATUS_BUFFER_UNDERRUN,
USBH_STATUS_OHCI_NOT_ACCESSED1,
USBH_STATUS_OHCI_NOT_ACCESSED2,
USBH_STATUS_HC_ERROR,
USBH_STATUS_FRAME_ERROR,
USBH_STATUS_SPLIT_ERROR,
USBH_STATUS_NEED_MORE_DATA,
USBH_STATUS_CHANNEL_NAK,
USBH_STATUS_ERROR,
USBH_STATUS_INVALID_PARAM,
USBH_STATUS_PENDING,
USBH_STATUS_DEVICE_REMOVED,
USBH_STATUS_CANCELED,
USBH_STATUS_HC_STOPPED,
USBH_STATUS_BUSY,
USBH_STATUS_NO_CHANNEL,
USBH_STATUS_INVALID_DESCRIPTOR,
USBH_STATUS_ENDPOINT_HALTED,
USBH_STATUS_TIMEOUT,
USBH_STATUS_PORT,
USBH_STATUS_INVALID_HANDLE,
USBH_STATUS_NOT_OPENED,
USBH_STATUS_ALREADY_ADDED,
USBH_STATUS_ENDPOINT_INVALID,
USBH_STATUS_NOT_FOUND,
USBH_STATUS_NOT_SUPPORTED,
USBH_STATUS_ISO_DISABLED,
USBH_STATUS_LENGTH,
USBH_STATUS_COMMAND_FAILED,
USBH_STATUS_INTERFACE_PROTOCOL,
USBH_STATUS_INTERFACE_SUB_CLASS,
USBH_STATUS_WRITE_PROTECT,
USBH_STATUS_INTERNAL_BUFFER_NOT_EMPTY,
USBH_STATUS_BAD_RESPONSE,
USBH_STATUS_DEVICE_ERROR,
USBH_STATUS_MTP_OPERATION_NOT_SUPPORTED,
USBH_STATUS_MEMORY,
USBH_STATUS_RESOURCES
} USBH_STATUS;
Enumeration constants
Constant | Description |
USBH_STATUS_SUCCESS | Operation successfully completed. |
USBH_STATUS_CRC | Data packet received from device contained a CRC error. |
USBH_STATUS_BITSTUFFING | Data packet received from device contained a bit stuffing violation. |
USBH_STATUS_DATATOGGLE | Data packet received from device had data toggle PID that did not match the expected value. |
USBH_STATUS_STALL | Endpoint was stalled by the device. |
USBH_STATUS_NOTRESPONDING | USB device did not respond to the request (did not respond to IN token or did not provide a handshake to the OUT token. |
USBH_STATUS_PID_CHECK | Check bits on PID from endpoint failed on data PID (IN) or handshake (OUT). |
USBH_STATUS_UNEXPECTED_PID | Receive PID was not valid when encountered or PID value is not defined. |
USBH_STATUS_DATA_OVERRUN | The amount of data returned by the device exceeded either the size of the maximum data packet allowed from the endpoint or the remaining buffer size (Babble error). |
USBH_STATUS_DATA_UNDERRUN | The endpoint returned less than maximum packet size and that amount was not sufficient to fill the specified buffer. |
USBH_STATUS_XFER_SIZE | Size exceeded the maximum transfer size supported by the driver. |
USBH_STATUS_DMA_ERROR | Direct memory access error. |
USBH_STATUS_BUFFER_OVERRUN | During an IN transfer, the host controller received data from the device faster than it could be written to system memory. |
USBH_STATUS_BUFFER_UNDERRUN | During an OUT transfer, the host controller could not retrieve data from system memory fast enough to keep up with data USB data rate. |
USBH_STATUS_OHCI_NOT_ACCESSED1 | Exclusive to OHCI. This code is set before the TD is placed on a list to be processed by the HC. (Binary for this code is 111x (1111 or 1110 depending on implementation)) |
USBH_STATUS_OHCI_NOT_ACCESSED2 | Exclusive to OHCI. This code is set before the TD is placed on a list to be processed by the HC. |
USBH_STATUS_HC_ERROR | Error reported by the host controller. |
USBH_STATUS_FRAME_ERROR | An interrupt transfer could not be scheduled within a micro frame. |
USBH_STATUS_SPLIT_ERROR | Error while using split transactions. |
USBH_STATUS_NEED_MORE_DATA | The transfer could not be started yet. More data is required. |
USBH_STATUS_CHANNEL_NAK | Internal use. |
USBH_STATUS_ERROR | Unspecified error occurred. |
USBH_STATUS_INVALID_PARAM | An invalid parameter was provided. |
USBH_STATUS_PENDING | The operation was started asynchronously. |
USBH_STATUS_DEVICE_REMOVED | The device was detached from the host. |
USBH_STATUS_CANCELED | The operation was canceled by user request. |
USBH_STATUS_HC_STOPPED | Host controller stopped. |
USBH_STATUS_BUSY | The endpoint, interface or device has pending requests and therefore the operation can not be executed. |
USBH_STATUS_NO_CHANNEL | Transfer request can’t be processed, because there is no free channel in the USB controller. |
USBH_STATUS_INVALID_DESCRIPTOR | A device provided an invalid descriptor. |
USBH_STATUS_ENDPOINT_HALTED | The endpoint has been halted. A pipe will be halted when a data transmission error (CRC, bit stuff, DATA toggle) occurs. |
USBH_STATUS_TIMEOUT | The operation was aborted due to a timeout. |
USBH_STATUS_PORT | Operation on a USB port failed. |
USBH_STATUS_INVALID_HANDLE | An invalid handle was provided to the function. |
USBH_STATUS_NOT_OPENED | The device or interface was not opened. |
USBH_STATUS_ALREADY_ADDED | Item has already been added. |
USBH_STATUS_ENDPOINT_INVALID | Invalid endpoint for the requested operation. |
USBH_STATUS_NOT_FOUND | Requested information not available. |
USBH_STATUS_NOT_SUPPORTED | The operation is not supported by the connected device. |
USBH_STATUS_ISO_DISABLED | The support for isochronous transfers is disabled in the USB stack, see USBH_SUPPORT_ISO_TRANSFER. |
USBH_STATUS_LENGTH | The operation detected a length error. |
USBH_STATUS_COMMAND_FAILED | This error is reported if the MSD command code was sent successfully but the status returned from the device indicates a command error. |
USBH_STATUS_INTERFACE_PROTOCOL | The used MSD interface protocol is not supported. The interface protocol is defined by the interface descriptor. |
USBH_STATUS_INTERFACE_SUB_CLASS | The used MSD interface sub class is not supported. The interface sub class is defined by the interface descriptor. |
USBH_STATUS_WRITE_PROTECT | The MSD medium is write protected. |
USBH_STATUS_INTERNAL_BUFFER_NOT_EMPTY | Internal use. |
USBH_STATUS_BAD_RESPONSE | Device responded unexpectedly. |
USBH_STATUS_DEVICE_ERROR | Device indicated a failure. |
USBH_STATUS_MTP_OPERATION_NOT_SUPPORTED | The requested MTP operation is not supported by the connected device. |
USBH_STATUS_MEMORY | Memory could not been allocated. |
USBH_STATUS_RESOURCES | Not enough resources (e.g endpoints, events, handles, …) |
Human Interface Device (HID) class
This chapter describes the emUSB-Host Human interface device class driver and its usage.
The HID class is part of the BASE package.
The HID-class code is linked in only if registered by the application program.
Introduction
The emUSB-Host HID class software allows accessing USB Human Interface Devices.
It implements the USB Human interface Device class protocols specified by the USB
Implementers Forum. The entire API of this class driver is prefixed with the
“USBH_HID_” text.
This chapter describes the architecture, the features and the programming interface
of this software component.
Overview
Two types of HIDs are currently supported: Keyboard and Mouse. For both, the application
can set a callback routine which is invoked whenever a message from either
one is received.
Types of HIDs:
- “True” HIDs: Mouse & Keyboard
- Devices using the HID protocol for data transfer
Example code
Example code which is provided in the USBH_HID_Start.c file. It outputs mouse and
keyboard events to the terminal I/O of debugger.
API Functions
This chapter describes the emUSB-Host HID API functions.
USBH_HID_CancelIo()
Description
Cancels any pending read/write operation.
Prototype
USBH_STATUS USBH_HID_CancelIo(USBH_HID_HANDLE hDevice);
Parameters
Parameter | Description |
hDevice | Handle to the HID device. |
Return value
USBH_STATUS_SUCCESS : Operation successfully canceled.
Any other value means error.
USBH_HID_Close()
Description
Closes a handle to opened HID device.
Prototype
USBH_STATUS USBH_HID_Close(USBH_HID_HANDLE hDevice);
Parameters
Parameter | Description |
hDevice | Handle to the opened device. |
Return value
USBH_STATUS_SUCCESS on success or error code on failure.
USBH_HID_Exit()
Description
Releases all resources, closes all handles to the USB stack and unregisters all
notification functions.
Prototype
void USBH_HID_Exit(void);
USBH_HID_GetDeviceInfo()
Description
Retrieves information about an opened HID device.
Prototype
USBH_STATUS USBH_HID_GetDeviceInfo(USBH_HID_HANDLE hDevice,
USBH_HID_DEVICE_INFO * pDevInfo);
Parameters
Parameter | Description |
hDevice | Handle to an opened HID device. |
pDevInfo | Pointer to a USBH_HID_DEVICE_INFO buffer. |
Return value
USBH_STATUS_SUCCESS on success or error code on failure.
USBH_HID_GetNumDevices()
Description
Returns the number of available devices. It also retrieves
the information about a device.
Prototype
int USBH_HID_GetNumDevices(USBH_HID_DEVICE_INFO * pDevInfo,
U32 NumItems);
Parameters
Parameter | Description |
pDevInfo | Pointer to an array of USBH_HID_DEVICE_INFO structures. |
NumItems | Number of items that pDevInfo can hold. |
Return value
Number of devices available.
USBH_HID_GetReport()
Description
Reads a report from a HID device.
Prototype
USBH_STATUS USBH_HID_GetReport(USBH_HID_HANDLE hDevice,
U8 * pBuffer,
U32 BufferSize,
USBH_HID_USER_FUNC * pfFunc,
USBH_HID_RW_CONTEXT * pRWContext);
Parameters
Parameter | Description |
hDevice | Handle to an opened HID device. |
pBuffer | Pointer to a buffer to read. |
BufferSize | Size of the buffer. |
pfFunc | [Optional] Callback function of type USBH_HID_USER_FUNC invoked when the read operation finishes (asynchronous operation). It can be the NULL pointer, the function is executed synchronously. |
pRWContext | [Optional] Pointer to a USBH_HID_RW_CONTEXT structure which will be filled with data after the transfer has been completed and passed as a parameter to the callback function (pfFunc). If pfFunc ≠ NULL, this parameter is required. If pfFunc = NULL, only the member pRWContext->NumBytesTransferred is set by the function. |
Return value
USBH_STATUS_SUCCESS | Success on synchronous operation (pfFunc = NULL). |
USBH_STATUS_PENDING | Request was submitted successfully and the application is informed via callback (pfFunc ≠ NULL). Any other value means error. |
USBH_HID_GetReportDesc()
Description
Returns the data of a report descriptor in raw form.
Prototype
USBH_STATUS USBH_HID_GetReportDesc( USBH_HID_HANDLE hDevice,
const U8 ** ppReportDescriptor,
unsigned * pNumBytes);
Parameters
Parameter | Description |
hDevice | Handle to an opened device. |
ppReportDescriptor | Returns a pointer to the report descriptor which is stored in an internal data structure of the USB stack. The report descriptor must not be changed. The pointer becomes invalid after the device is closed. |
pNumBytes | Returns the size of the report descriptor in bytes. |
Return value
USBH_STATUS_SUCCESS on success or error code on failure.
USBH_HID_Init()
Description
Initializes and registers the HID device driver with emUSB-Host.
Prototype
U8 USBH_HID_Init(void);
Return value
1 | Success. |
0 | Could not register HID device driver. |
Additional information
This function can be called multiple times, but only the first
call initializes the module. Any further calls only increase
the initialization counter. This is useful for cases where
the module is initialized from different places which
do not interact with each other, To de-initialize
the module USBH_HID_Exit has to be called
the same number of times as this function was called.
USBH_HID_Open()
Description
Opens a device given by an index.
Prototype
USBH_HID_HANDLE USBH_HID_Open(unsigned Index);
Parameters
Parameter | Description |
Index | Device index. |
Return value
≠ USBH_HID_INVALID_HANDLE | Handle to a HID device. |
= USBH_HID_INVALID_HANDLE | Device not available. |
Additional information
The index of a new connected device is provided to the callback function
registered with USBH_HID_AddNotification().
USBH_HID_AddNotification()
Description
Adds a callback in order to be notified when a device is added or removed.
Prototype
USBH_STATUS USBH_HID_AddNotification(USBH_NOTIFICATION_HOOK * pHook,
USBH_NOTIFICATION_FUNC * pfNotification,
void * pContext);
Parameters
Parameter | Description |
pHook | Pointer to a user provided USBH_NOTIFICATION_HOOK structure, which is initialized and used by this function. The memory area must be valid, until the notification is removed. |
pfNotification | Pointer to a function the stack should call when a device is connected or disconnected. |
pContext | Pointer to a user context that is passed to the callback function. |
Return value
USBH_STATUS_SUCCESS on success or error code on failure.
USBH_HID_RemoveNotification()
Description
Removes a callback added via USBH_HID_AddNotification.
Prototype
USBH_STATUS USBH_HID_RemoveNotification(const USBH_NOTIFICATION_HOOK * pHook);
Parameters
Return value
USBH_STATUS_SUCCESS on success or error code on failure.
USBH_HID_RegisterNotification()
Description
Obsolete function, use USBH_HID_AddNotification().
Registers a notification callback in order to inform user about
adding or removing a device.
Prototype
void USBH_HID_RegisterNotification(USBH_NOTIFICATION_FUNC * pfNotification,
void * pContext);
Parameters
Parameter | Description |
pfNotification | Pointer to a callback function of type USBH_NOTIFICATION_FUNC the emUSB-Host calls when a HID device is attached/removed. |
pContext | Application specific pointer. The pointer is not dereferenced by the emUSB-Host. It is passed to the callback function. Any value the application chooses is permitted, including NULL. |
USBH_HID_SetOnKeyboardStateChange()
Description
Sets a callback to be called in case of keyboard events.
Handles all keyboards that do not use report ids. These are all
keyboards that can be used in boot mode (with a PC BIOS).
Prototype
void USBH_HID_SetOnKeyboardStateChange(USBH_HID_ON_KEYBOARD_FUNC * pfOnChange);
Parameters
Parameter | Description |
pfOnChange | Callback that shall be called when a keyboard change notification is available. |
USBH_HID_SetOnExKeyboardStateChange()
Description
Sets a callback to be called in case of keyboard events.
Handles also keyboards that use report ids.
In contrast to the function USBH_HID_SetOnKeyboardStateChange(), some
unusual Apple keyboards are supported, too.
Prototype
void USBH_HID_SetOnExKeyboardStateChange(USBH_HID_ON_KEYBOARD_FUNC * pfOnChange);
Parameters
Parameter | Description |
pfOnChange | Callback that shall be called when a keyboard change notification is available. |
USBH_HID_SetOnMouseStateChange()
Description
Sets a callback to be called in case of mouse events.
Prototype
void USBH_HID_SetOnMouseStateChange(USBH_HID_ON_MOUSE_FUNC * pfOnChange);
Parameters
Parameter | Description |
pfOnChange | Callback that shall be called when a mouse change notification is available. |
USBH_HID_SetOnRCStateChange()
Description
Sets a callback to be called in case of remote control events.
Remote control interfaces are often a part of an USB audio device,
the HID interface is used to tell the host about changes in volume,
mute, for music track control and similar.
Prototype
void USBH_HID_SetOnRCStateChange(USBH_HID_ON_RC_FUNC * pfOnChange);
Parameters
Parameter | Description |
pfOnChange | Callback that shall be called when a remote control change notification is available. |
USBH_HID_SetOnGenericEvent()
Description
Sets a callback to be called in case of generic HID events.
Prototype
void USBH_HID_SetOnGenericEvent( U32 NumUsages,
const U32 * pUsages,
USBH_HID_ON_GENERIC_FUNC * pfOnEvent);
Parameters
Parameter | Description |
NumUsages | Number of usage codes provided by the caller. |
pUsages | List of usage codes of fields from the report to be monitored. Each usage code must contain the Usage Page in the high order 16 bits and the Usage ID in the the low order 16 bits. pUsages must point to a static memory area that remains valid until the USBH_HID module is shut down. |
pfOnEvent | Callback that shall be called when a report is received that contains at least one field with usage code from the list. |
USBH_HID_SetReport()
Description
Sends an output report to a HID device. This function assumes report IDs
are not used.
Prototype
USBH_STATUS USBH_HID_SetReport( USBH_HID_HANDLE hDevice,
const U8 * pBuffer,
U32 BufferSize,
USBH_HID_USER_FUNC * pfFunc,
USBH_HID_RW_CONTEXT * pRWContext);
Parameters
Parameter | Description |
hDevice | Handle to an opened HID device. |
pBuffer | Pointer to a buffer containing the data to be sent. In case the device has more than one report descriptor the first byte inside the buffer must contain a valid ID matching one of the report descriptors. |
BufferSize | Size of the buffer. |
pfFunc | [Optional] Callback function of type USBH_HID_USER_FUNC invoked when the send operation finishes. It can be the NULL pointer. |
pRWContext | [Optional] Pointer to a USBH_HID_RW_CONTEXT structure which will be filled with data after the transfer has been completed and passed as a parameter to the pfFunc function. |
Return value
USBH_STATUS_SUCCESS | Success. |
USBH_STATUS_PENDING | Request was submitted and application is informed via callback. Any other value means error. |
USBH_HID_SetReportEx()
Description
Sends an output or feature report to a HID device. Optionally sends out a report ID.
Output reports are send via the OUT endpoint of the device if present,
or using a control request otherwise.
Prototype
USBH_STATUS USBH_HID_SetReportEx( USBH_HID_HANDLE hDevice,
const U8 * pBuffer,
U32 BufferSize,
USBH_HID_USER_FUNC * pfFunc,
USBH_HID_RW_CONTEXT * pRWContext,
unsigned Flags);
Parameters
Parameter | Description |
hDevice | Handle to an opened HID device. |
pBuffer | Pointer to a buffer containing the data to be sent. In case the device has more than one report descriptor the first byte inside the buffer must contain a valid ID matching one of the report descriptors. |
BufferSize | Size of the buffer. |
pfFunc | [Optional] Callback function of type USBH_HID_USER_FUNC invoked when the send operation finishes. It can be the NULL pointer. |
pRWContext | [Optional] Pointer to a USBH_HID_RW_CONTEXT structure which will be filled with data after the transfer has been completed and passed as a parameter to the pfOnComplete function. |
Flags | A bitwise OR-combination of flags USBH_HID_USE_REPORT_ID: Enables report ID usage. The first byte in the buffer pointed to by pBuffer is used as report ID. USBH_HID_OUTPUT_REPORT: Send an output report (default). USBH_HID_FEATURE_REPORT: Send a feature report. |
Return value
USBH_STATUS_SUCCESS | Success. |
USBH_STATUS_PENDING | Request was submitted and application is informed via callback. Any other value means error. |
USBH_HID_GetReportEP0()
Description
Reads a report from a HID device via control request.
Prototype
USBH_STATUS USBH_HID_GetReportEP0(USBH_HID_HANDLE hDevice,
U8 ReportID,
unsigned Flags,
U8 * pBuffer,
U32 Length,
U32 * pNumBytesRead);
Parameters
Parameter | Description |
hDevice | Handle to an opened HID device. |
ReportID | ID of the report requested from the device. |
Flags | USBH_HID_INPUT_REPORT: Request for an input report (default). USBH_HID_FEATURE_REPORT: Request for a feature report. |
pBuffer | Pointer to a buffer to read. |
Length | Requested length of the report. |
pNumBytesRead | [O] Actual length of the report read. |
Return value
USBH_STATUS_SUCCESS | Success. Any other value means error. |
USBH_HID_SetIndicators()
Description
Sets the indicators (usually LEDs) on a keyboard.
Prototype
USBH_STATUS USBH_HID_SetIndicators(USBH_HID_HANDLE hDevice,
U8 IndicatorMask);
Parameters
Parameter | Description |
hDevice | Handle to the opened device. |
IndicatorMask | Binary mask of the following items USBH_HID_IND_NUM_LOCK USBH_HID_IND_CAPS_LOCK USBH_HID_IND_SCROLL_LOCK USBH_HID_IND_COMPOSE USBH_HID_IND_KANA USBH_HID_IND_SHIFT |
Return value
USBH_STATUS_SUCCESS on success or error code on failure.
USBH_HID_GetIndicators()
Description
Retrieves the indicator (LED) status.
Prototype
USBH_STATUS USBH_HID_GetIndicators(USBH_HID_HANDLE hDevice,
U8 * pIndicatorMask);
Parameters
Parameter | Description |
hDevice | Handle to the opened device. |
pIndicatorMask | Binary mask of the following items USBH_HID_IND_NUM_LOCK USBH_HID_IND_CAPS_LOCK USBH_HID_IND_SCROLL_LOCK USBH_HID_IND_COMPOSE USBH_HID_IND_KANA USBH_HID_IND_SHIFT |
Return value
USBH_STATUS_SUCCESS on success or error code on failure.
Description
Sets whether the keyboard LED should be updated or not.
(Default is disabled).
Prototype
void USBH_HID_ConfigureAllowLEDUpdate(unsigned AllowLEDUpdate);
Parameters
Parameter | Description |
AllowLEDUpdate | 0 - Disable LED Update. 1 - Allow LED Update. |
USBH_HID_GetInterfaceHandle()
Description
Return the handle to the (open) USB interface. Can be used to
call USBH core functions like USBH_GetStringDescriptor().
Prototype
USBH_INTERFACE_HANDLE USBH_HID_GetInterfaceHandle(USBH_HID_HANDLE hDevice);
Parameters
Parameter | Description |
hDevice | Handle to an open device returned by USBH_HID_Open(). |
Return value
Handle to an open interface.
Data structures
This chapter describes the emUSB-Host HID API structures.
USBH_HID_DEVICE_INFO
Description
Structure containing information about a HID device.
Type definition
typedef struct {
U16 InputReportSize;
U16 OutputReportSize;
U16 ProductId;
U16 VendorId;
unsigned DevIndex;
USBH_INTERFACE_ID InterfaceID;
unsigned NumReportInfos;
USBH_HID_REPORT_INFO ReportInfo[];
U8 DeviceType;
U8 InterfaceNo;
} USBH_HID_DEVICE_INFO;
Structure members
Member | Description |
InputReportSize | Deprecated. = ReportInfo[0].InputReportSize for compatibility. |
OutputReportSize | Deprecated. = ReportInfo[0].OutputReportSize for compatibility. |
ProductId | The Product ID of the device. |
VendorId | The Vendor ID of the device. |
DevIndex | Device index. |
InterfaceID | Interface ID of the HID device. |
NumReportInfos | Number of entries in ReportInfo. |
ReportInfo | Size and Report Ids of all reports of the interface. |
DeviceType | Device type. USBH_HID_VENDOR - Vendor device USBH_HID_MOUSE - Mouse device USBH_HID_KEYBOARD - Keyboard device |
InterfaceNo | Index of the interface (from USB descriptor). |
USBH_HID_KEYBOARD_DATA
Description
Structure containing information about a keyboard event.
Type definition
typedef struct {
unsigned Code;
unsigned Value;
USBH_INTERFACE_ID InterfaceID;
} USBH_HID_KEYBOARD_DATA;
Structure members
Member | Description |
Code | Contains the keycode. |
Value | Keyboard state info. Refer to sample code for more information. |
InterfaceID | ID of the interface that caused the event. |
USBH_HID_MOUSE_DATA
Description
Structure containing information about a mouse event.
Type definition
typedef struct {
int xChange;
int yChange;
int WheelChange;
int ButtonState;
USBH_INTERFACE_ID InterfaceID;
} USBH_HID_MOUSE_DATA;
Structure members
Member | Description |
xChange | Change of x-position since last event. |
yChange | Change of y-position since last event. |
WheelChange | Change of wheel-position since last event (if wheel is present). |
ButtonState | Each bit corresponds to one button on the mouse. If the bit is set, the corresponding button is pressed. Typically, bit 0 corresponds to the left mouse button bit 1 corresponds to the right mouse button bit 2 corresponds to the middle mouse button. |
InterfaceID | ID of the interface that caused the event. |
USBH_HID_RC_DATA
Description
Structure containing information about a remote control event.
Type definition
typedef struct {
U8 VolumeIncrement;
U8 VolumeDecrement;
I8 Mute;
U8 PlayPause;
U8 ScanNextTrack;
U8 ScanPreviousTrack;
U8 Repeat;
U8 RandomPlay;
USBH_INTERFACE_ID InterfaceID;
} USBH_HID_RC_DATA;
Structure members
Member | Description |
VolumeIncrement | Indicates that the volume increment button was pressed (1 - pressed, 0 - unpressed). |
VolumeDecrement | Indicates that the volume decrement button was pressed (1 - pressed, 0 - unpressed). |
Mute | Indicates that the mute button was pressed (1 - pressed, 0 - unpressed OR -1 for “off”, 0 for “no change” and 1 for “on”, which selection variant is used depends on the device, but the second variant is rarely used). |
PlayPause | Indicates that the play/pause button was pressed (1 - pressed, 0 - unpressed). |
ScanNextTrack | Indicates that the scan next track button was pressed (1 - pressed, 0 - unpressed). |
ScanPreviousTrack | Indicates that the scan previous track button was pressed (1 - pressed, 0 - unpressed). |
Repeat | Indicates that the repeat button was pressed (1 - pressed, 0 - unpressed). |
RandomPlay | Indicates that the random play button was pressed (1 - pressed, 0 - unpressed). |
InterfaceID | ID of the interface that caused the event. |
USBH_HID_GENERIC_DATA
Description
Structure containing information from a HID report event.
Type definition
typedef struct {
U32 Usage;
USBH_ANY_SIGNED Value;
U8 Valid;
U8 Signed;
U8 ReportID;
USBH_ANY_SIGNED LogicalMin;
USBH_ANY_SIGNED LogicalMax;
USBH_ANY_SIGNED PhysicalMin;
USBH_ANY_SIGNED PhysicalMax;
U8 PhySigned;
U8 NumBits;
U16 BitPosStart;
} USBH_HID_GENERIC_DATA;
Structure members
Member | Description |
Usage | HID usage code. Copied from the array given to USBH_HID_SetOnGenericEvent(). Set to 0, if the usage code was not found in any report descriptor. |
Value | Value of the field extracted from the report. |
Valid | = 1 if Value field contains valid value. |
Signed | = 1 if Value is signed, = 0 if unsigned. |
ReportID | ID of the report containing the field. |
LogicalMin | Logical minimum from report descriptor. Contains signed value, if Signed = 1, unsigned value otherwise. |
LogicalMax | Logical maximum from report descriptor. Contains signed value, if Signed = 1, unsigned value otherwise. |
PhysicalMin | Physical minimum from report descriptor. Contains signed value, if PhySigned = 1, unsigned value otherwise. |
PhysicalMax | Physical maximum from report descriptor. Contains signed value, if PhySigned = 1, unsigned value otherwise. |
PhySigned | = 1 if PhysicalMin / PhysicalMax are signed, = 0 if unsigned. |
NumBits | Internal use. |
BitPosStart | Internal use. |
USBH_HID_REPORT_INFO
Description
Structure containing information about a HID report.
Type definition
typedef struct {
U8 ReportId;
U16 InputReportSize;
U16 OutputReportSize;
} USBH_HID_REPORT_INFO;
Structure members
Member | Description |
ReportId | Report Id |
InputReportSize | Size of input report in bytes. |
OutputReportSize | Size of output report in bytes. |
USBH_HID_RW_CONTEXT
Description
Contains information about a completed, asynchronous transfers.
Is passed to the USBH_HID_ON_COMPLETE_FUNC user
callback when using asynchronous write and read.
When this structure is passed to USBH_HID_GetReport() or USBH_HID_SetReport()
its member need not to be initialized.
Type definition
typedef struct {
void * pUserContext;
USBH_STATUS Status;
U32 NumBytesTransferred;
void * pUserBuffer;
U32 UserBufferSize;
} USBH_HID_RW_CONTEXT;
Structure members
Function Types
This chapter describes the emUSB-Host HID API function types.
USBH_HID_ON_KEYBOARD_FUNC
Description
Function called on every keyboard event.
Type definition
typedef void (USBH_HID_ON_KEYBOARD_FUNC)(USBH_HID_KEYBOARD_DATA * pKeyData);
Parameters
USBH_HID_ON_MOUSE_FUNC
Description
Function called on every mouse event.
Type definition
typedef void (USBH_HID_ON_MOUSE_FUNC)(USBH_HID_MOUSE_DATA * pMouseData);
Parameters
USBH_HID_ON_RC_FUNC
Description
Function called on every remote control event.
Type definition
typedef void (USBH_HID_ON_RC_FUNC)(USBH_HID_RC_DATA * pMouseData);
Parameters
USBH_HID_ON_GENERIC_FUNC
Description
Function called on every generic HID event.
Type definition
typedef void (USBH_HID_ON_GENERIC_FUNC)
( USBH_INTERFACE_ID InterfaceID,
unsigned NumGenericInfos,
const USBH_HID_GENERIC_DATA * pGenericData);
Parameters
Parameter | Description |
InterfaceID | Interface ID of the HID device that generated the event. |
NumGenericInfos | Number of USBH_HID_GENERIC_DATA structures provided. |
pGenericData | Pointer to an array of USBH_HID_GENERIC_DATA structures. |
USBH_HID_USER_FUNC
Description
Function called on completion of USBH_HID_GetReport() or USBH_HID_SetReport().
Type definition
typedef void (USBH_HID_USER_FUNC)(USBH_HID_RW_CONTEXT * pContext);
Parameters
Printer class (Add-On)
This chapter describes the emUSB-Host printer class software component and how to
use it.
The printer class is an optional extension to emUSB-Host.
Introduction
The printer class software component of emUSB-Host allows the communication to
USB printing devices. It implements the USB printer class protocol specified by the
USB Implementers Forum.
This chapter describes the architecture, the features and the programming interface
of this software component. To improve the readability of application code, all the
functions and data types of this API are prefixed with the “USBH_PRINTER_” text.
In the following text the word “printer” is used to refer to any USB device that
produces a hard copy of data sent to it.
Overview
A printer connected to the emUSB-Host is automatically configured and added to an
internal list. The application receives a notification each time a printer is added or
removed over a callback. In order to communicate to a printer the application should
open a handle to it. The printers are identified by an index. The first connected
printer gets assigned the index 0, the second index 1, and so on. You can use this
index to identify a printer in a call to USBH_PRINTER_OpenByIndex() function.
Features
The following features are provided:
- Handling of multiple printers at the same time.
- Notifications about printer connection status.
- Ability to query the printer operating status and its device ID.
Example code
An example application which uses the API is provided in the USBH_Printer_Start.c file
of your shipment. This example displays information about the printer and its
connection status in the I/O terminal of the debugger. In addition the text “Hello World”
is printed out at the top of the current page when the first printer connects.
API Functions
This chapter describes the emUSB-Host Printer API functions.
USBH_PRINTER_Close()
Description
Closes a handle to an opened printer.
Prototype
USBH_STATUS USBH_PRINTER_Close(USBH_PRINTER_HANDLE hDevice);
Parameters
Parameter | Description |
hDevice | Handle to the opened device. |
Return value
= USBH_STATUS_SUCCESS | Successful. |
≠ USBH_STATUS_SUCCESS | An error occurred. |
Description
Sets up the default timeout the host waits until the
data transfer will be aborted.
Prototype
void USBH_PRINTER_ConfigureTimeout(U32 Timeout);
Parameters
Parameter | Description |
Timeout | Timeout given in ms. |
USBH_PRINTER_ExecSoftReset()
Description
Flushes all send and receive buffers.
Prototype
USBH_STATUS USBH_PRINTER_ExecSoftReset(USBH_PRINTER_HANDLE hDevice);
Parameters
Parameter | Description |
hDevice | Handle to the opened printer. |
Return value
USBH_STATUS_SUCCESS | Reset executed. |
USBH_STATUS_ERROR | An error occurred. |
USBH_PRINTER_Exit()
Description
Unregisters and de-initializes the PRINTER device driver from emUSB-Host.
Prototype
void USBH_PRINTER_Exit(void);
Additional information
Before this function is called any notifications added via
USBH_PRINTER_AddNotification() must be removed
via USBH_PRINTER_RemoveNotification().
This function will release resources that were used by this device
driver. It has to be called if the application is closed. This has
to be called before USBH_Exit() is called. No more functions of
this module may be called after calling USBH_PRINTER_Exit(). The
only exception is USBH_PRINTER_Init(), which would in turn
reinitialize the module and allows further calls.
USBH_PRINTER_GetDeviceId()
Description
Ask the USB printer to send the IEEE.1284 ID string.
Prototype
USBH_STATUS USBH_PRINTER_GetDeviceId(USBH_PRINTER_HANDLE hDevice,
U8 * pData,
unsigned NumBytes);
Parameters
Parameter | Description |
hDevice | Handle to the opened printer device. |
pData | Pointer to a caller allocated buffer. |
NumBytes | Number of bytes allocated for the read buffer. |
Return value
USBH_STATUS_SUCCESS : Device ID read.
Any other status : An error occurred.
USBH_PRINTER_GetNumDevices()
Description
Returns the number of available devices.
Prototype
int USBH_PRINTER_GetNumDevices(void);
Return value
Number of devices available
USBH_PRINTER_GetPortStatus()
Description
Returns the status of printer.
Prototype
USBH_STATUS USBH_PRINTER_GetPortStatus(USBH_PRINTER_HANDLE hDevice,
U8 * pStatus);
Parameters
Parameter | Description |
hDevice | Handle to the opened printer. |
pStatus | Pointer to a caller allocated variable. |
Return value
= USBH_STATUS_SUCCESS | Status retrieved successfully. |
≠ USBH_STATUS_SUCCESS | An error occurred. |
Additional information
The returned status is to be interpreted as follows:
Bit(s) | Fields | Explanations |
7 .. 6 | Reserved | Reserved for future use; device shall return these bits set to zero. |
5 | Paper Empty | 1 = Paper Empty, 0 = Paper Not Empty |
4 | Select | 1 = Selected, 0 = Not Selected |
3 | Not Error | 1 = No error, 0 = Error |
2 .. 0 | Reserved | Reserved for future use; device shall return these bits set to zero. |
USBH_PRINTER_Init()
Description
Initialize the Printer device class driver.
Prototype
U8 USBH_PRINTER_Init(void);
Return value
1 | Success |
0 | Could not register class device driver |
USBH_PRINTER_Open()
Description
Opens a handle to a printer. The printer is identified by its name.
Prototype
USBH_PRINTER_HANDLE USBH_PRINTER_Open(const char * sName);
Parameters
Parameter | Description |
sName | Pointer to a name of the device eg. prt001 for device 0. |
Return value
≠ 0 | Handle to a printing device |
= 0 | Device not available or error occurred. |
Additional information
It is recommended to use USBH_PRINTER_OpenByIndex().
It is slightly faster.
USBH_PRINTER_OpenByIndex()
Description
Opens a device given by an index.
Prototype
USBH_PRINTER_HANDLE USBH_PRINTER_OpenByIndex(unsigned Index);
Parameters
Parameter | Description |
Index | Index of the device that shall be opened. In general this means: the first connected device is 0, second device is 1 etc. |
Return value
≠ USBH_PRINTER_INVALID_HANDLE | Handle to the device. |
= USBH_PRINTER_INVALID_HANDLE | Device could not be opened (removed or not available). |
USBH_PRINTER_Receive()
Description
Reads one packet from the device. The size of the buffer provided by the caller must
be at least the maximum packet size of the IN endpoint.
The maximum packet size of the IN endpoint can be retrieved using USBH_PRINTER_GetDeviceInfo().
Prototype
USBH_STATUS USBH_PRINTER_Receive(USBH_PRINTER_HANDLE hDevice,
U8 * pData,
U32 * pNumBytesRead,
U32 Timeout);
Parameters
Parameter | Description |
hDevice | Handle to an open device returned by USBH_PRINTER_Open(). |
pData | Pointer to a buffer to store the data read. |
pNumBytesRead | Pointer to a variable which receives the number of bytes read from the device. |
Timeout | Timeout in ms. 0 means infinite timeout. |
Return value
USBH_STATUS_SUCCESS on success or error code on failure.
Additional information
This function does not access the buffer used by the function USBH_PRINTER_Read().
Data contained in this buffer are not returned by USBH_PRINTER_Receive().
Intermixing calls to USBH_PRINTER_Read() and USBH_PRINTER_Receive() for the same endpoint
should be avoided or used with care.
USBH_PRINTER_WriteEx()
Description
Writes data to the printer device. The function blocks until all data
has been written or until the timeout has been reached.
Prototype
USBH_STATUS USBH_PRINTER_WriteEx( USBH_PRINTER_HANDLE hDevice,
const U8 * pData,
U32 NumBytes,
U32 * pNumBytesWritten,
U32 Timeout);
Parameters
Parameter | Description |
hDevice | Handle to an open device returned by USBH_PRINTER_Open(). |
pData | Pointer to data to be sent. |
NumBytes | Number of bytes to send. |
pNumBytesWritten | Pointer to a variable which receives the number of bytes written to the device. Can be NULL. |
Timeout | Timeout in ms. 0 means infinite timeout. |
Return value
USBH_STATUS_SUCCESS on success or error code on failure.
Additional information
If the function returns an error code (including USBH_STATUS_TIMEOUT) it already may
have written part of the data. The number of bytes written successfully is always
stored in the variable pointed to by pNumBytesWritten.
USBH_PRINTER_RegisterNotification()
Description
This function is deprecated, please use function USBH_PRINTER_AddNotification!
Sets a callback in order to be notified when a device is added or removed.
Prototype
void USBH_PRINTER_RegisterNotification(USBH_NOTIFICATION_FUNC * pfNotification,
void * pContext);
Parameters
Parameter | Description |
pfNotification | Pointer to a function the stack should call when a device is connected or disconnected. |
pContext | Pointer to a user context that is passed to the callback function. |
Additional information
This function is deprecated, please use function USBH_PRINTER_AddNotification.
USBH_PRINTER_AddNotification()
Description
Adds a callback in order to be notified when a device is added or removed.
Prototype
USBH_STATUS USBH_PRINTER_AddNotification(USBH_NOTIFICATION_HOOK * pHook,
USBH_NOTIFICATION_FUNC * pfNotification,
void * pContext);
Parameters
Parameter | Description |
pHook | Pointer to a user provided USBH_NOTIFICATION_HOOK variable. |
pfNotification | Pointer to a function the stack should call when a device is connected or disconnected. |
pContext | Pointer to a user context that is passed to the callback function. |
Return value
USBH_STATUS_SUCCESS on success or error code on failure.
USBH_PRINTER_RemoveNotification()
Description
Removes a callback added via USBH_PRINTER_AddNotification.
Prototype
USBH_STATUS USBH_PRINTER_RemoveNotification(const USBH_NOTIFICATION_HOOK * pHook);
Parameters
Return value
USBH_STATUS_SUCCESS on success or error code on failure.
USBH_PRINTER_Write()
Description
Sends data to a printer.
Prototype
USBH_STATUS USBH_PRINTER_Write( USBH_PRINTER_HANDLE hDevice,
const U8 * pData,
unsigned NumBytes);
Parameters
Parameter | Description |
hDevice | Handle to the opened printer. |
pData | Pointer to data to be sent. |
NumBytes | Number of bytes to send. |
Return value
= USBH_STATUS_SUCCESS | Data sent. |
≠ USBH_STATUS_SUCCESS | An error occurred. |
Additional information
This functions does not alter the data it sends to printer.
Data in ASCII form is typically printed out correctly by the
majority of printers. For complex graphics the data passed to this
function must be properly formatted according to the protocol the
printer understands, like Hewlett Packard PLC, IEEE 1284.1,
Adobe Postscript or Microsoft Windows Printing System (WPS).
USBH_PRINTER_Read()
Description
Receives data from a printer.
Prototype
USBH_STATUS USBH_PRINTER_Read(USBH_PRINTER_HANDLE hDevice,
U8 * pData,
unsigned NumBytes);
Parameters
Parameter | Description |
hDevice | Handle to the opened printer. |
pData | Pointer to a caller allocated buffer. |
NumBytes | Size of the receive buffer in bytes. |
Return value
= USBH_STATUS_SUCCESS | Data received. |
≠ USBH_STATUS_SUCCESS | An error occurred. |
Additional information
Not all printers support read operation. For the normal usage of
a printer, reading from the printer is normally not required.
Some printers do not even provide an IN Endpoint for read operations.
Typically a read operation can be used to feedback status information
from the printer to the host. This type of feedback requires usually
a command to be sent to the printer first. Which type of information
can be read from the printer depends very much on the model.
USBH_PRINTER_SendVendorRequest()
Description
Sends custom vendor requests to the printer.
Prototype
USBH_STATUS USBH_PRINTER_SendVendorRequest(USBH_PRINTER_HANDLE hDevice,
U8 RequestType,
U8 Request,
U16 wValue,
void * pData,
U32 * pNumBytes,
U32 Timeout);
Parameters
Parameter | Description |
hDevice | Handle to the opened printer device. |
RequestType | This parameter is a bitmap containing the following values: bit 7 transfer direction: 0 = OUT (Host to Device) 1 = IN (Device to Host) bits 6..5 request type: 0 = Standard 1 = Class 2 = Vendor 3 = Reserved bits 4..0 recipient: 0 = Device 1 = Interface 2 = Endpoint 3 = Other |
Request | Request code in the setup request. |
wValue | wValue in the setup request. |
pData | Additional data for the setup request. |
pNumBytes | in Number of bytes to be received/sent in pData. out Number of bytes processed. |
Timeout | Timeout in ms. 0 means infinite timeout. |
Return value
= USBH_STATUS_SUCCESS | Successful. |
≠ USBH_STATUS_SUCCESS | An error occurred. |
Additional information
wLength which is normally part of the setup packet will be determined given by the pNumBytes and pData.
In case no pBuffer is given, wLength will be 0.
USBH_PRINTER_AddCustomDeviceMask()
Description
This function allows the PRINTER module to receive notifications
about devices which do not use the correct class and subclass IDs
for the printer class.
Prototype
USBH_STATUS USBH_PRINTER_AddCustomDeviceMask(const U16 * pVendorIds,
const U16 * pProductIds,
U16 NumIds);
Parameters
Parameter | Description |
pVendorIds | Array of vendor IDs. |
pProductIds | Array of product IDs. |
NumIds | Number of elements in both arrays, each index in both arrays is used as a pair to create a filter. |
Return value
USBH_STATUS_SUCCESS | Success. |
USBH_STATUS_ERROR | Notification could not be registered. |
Data structures
This chapter describes the emUSB-Host Printer class data structures.
USBH_PRINTER_DEVICE_INFO
Type definition
typedef struct {
U16 VendorId;
U16 ProductId;
U16 bcdDevice;
U16 MaxPacketSize_OUT;
U16 MaxPacketSize_IN;
U8 acSerialNo[];
} USBH_PRINTER_DEVICE_INFO;
Structure members
Member | Description |
VendorId | The printer’s vendor ID. |
ProductId | The printer’s product ID. |
bcdDevice | Binary Coded Decimal device version. |
MaxPacketSize_OUT | Maximum packet size of the bulk OUT EP. |
MaxPacketSize_IN | Maximum packet size of the bulk IN EP. If this value is zero it means that the printer does not have an IN endpoint. |
acSerialNo | The printer’s serial number. |
Mass Storage Device (MSD) class
This chapter describes the emUSB-Host Mass storage device class driver and its
usage.
The MSD class is part of the BASE package. The MSD class code is only linked in if
registered by the application program.
Introduction
The emUSB-Host MSD class software allows accessing USB Mass Storage Devices.
It implements the USB Mass Storage Device class protocols specified by the USB
Implementers Forum. The entire API of this class driver is prefixed “USBH_MSD_”.
This chapter describes the architecture, the features and the programming interface
of the class driver.
Overview
A mass storage device connected to the emUSB-Host is added to the file system as a
device. All operations on the device, such as formatting, reading / writing of files and
directories are performed through the API of the file system. With emFile, the device
name of the first MSD is “msd:0:”.
The structure of MSD component is shown in the following diagram:
Features
The following features are provided:
- The command block specification and protocol implementation used by the connected device will be automatically detected.
- It is independent of the file system. An interface to emFile is provided.
Requirements
To use the MSD class driver to perform file and directory operations, a file system
(typically emFile) is required.
Example code
Example code which is provided in the file USBH_MSD_Start.c.
The example shows the capacity of the connected device, shows files in the root
directory and creates and writes to a file.
Supported Protocols
The following table contains an overview about the implemented command protocols.
Command block specification | Implementation | Related documents |
SCSI transparent command set | All necessary commands for accessing flash devices. | Mass Storage Class Specification Overview Revision 1.2., SCSI-2 Specification September 1993 Rev.10 (X3T9.2 Project 275D) |
The following table contains an overview about the implemented transport protocols.
Protocol implementation | Implementation | Related documents |
Bulk-Only transport | All commands implemented | Universal Serial Bus Mass Storage Class Bulk-Only Transport Rev.1.0. |
API Functions
This chapter describes the emUSB-Host MSD API functions.
USBH_MSD_Exit()
Description
Releases all resources, closes all handles to the USB bus
driver and un-register all notification functions. Has to be called
if the application is closed before the USBH_Exit is called.
Prototype
void USBH_MSD_Exit(void);
USBH_MSD_GetStatus()
Description
Checks the Status of a device. Therefore it performs a “Test Unit Ready” command to
test if the device is still connected and if a logical unit is assigned.
Prototype
USBH_STATUS USBH_MSD_GetStatus(U8 Unit);
Parameters
Return value
= USBH_STATUS_SUCCESS | Device is ready for operation. |
≠ USBH_STATUS_SUCCESS | An error occurred. |
USBH_MSD_GetUnits()
Description
Returns available units for a device.
Prototype
USBH_STATUS USBH_MSD_GetUnits(U8 DevIndex,
U32 * pUnitMask);
Parameters
Parameter | Description |
DevIndex | Index of the MSD device returned by USBH_MSD_LUN_NOTIFICATION_FUNC. |
pUnitMask | out Pointer to a U32 variable which will receive the LUN mask. |
Return value
= USBH_STATUS_SUCCESS | Device is ready for operation. |
≠ USBH_STATUS_SUCCESS | An error occurred. |
Additional information
The mask corresponds to the unit IDs. The device has unit ID n, if bit n of the mask is set.
E.g. a mask of 0x0000000C means unit ID 2 and unit ID 3 are available for the device.
USBH_MSD_GetUnitInfo()
Description
Returns basic information about the logical unit (LUN).
Prototype
USBH_STATUS USBH_MSD_GetUnitInfo(U8 Unit,
USBH_MSD_UNIT_INFO * pInfo);
Parameters
Parameter | Description |
Unit | 0-based Unit Id. See USBH_MSD_GetUnits(). |
pInfo | out Pointer to a caller provided structure of type USBH_MSD_UNIT_INFO. It receives the information about the LUN in case of success. |
Return value
= USBH_STATUS_SUCCESS | Device is ready for operation. |
≠ USBH_STATUS_SUCCESS | An error occurred. |
USBH_MSD_GetPortInfo()
Description
Retrieves the port information about a USB MSC device using a unit ID.
Prototype
USBH_STATUS USBH_MSD_GetPortInfo(U8 Unit,
USBH_PORT_INFO * pPortInfo);
Parameters
Parameter | Description |
Unit | 0-based Unit Id. See USBH_MSD_GetUnits(). |
pPortInfo | out Pointer to a caller provided structure of type USBH_PORT_INFO. It receives the information about the LUN in case of success. |
Return value
= USBH_STATUS_SUCCESS | Success, pPortInfo contains valid port information. |
≠ USBH_STATUS_SUCCESS | An error occurred. |
USBH_MSD_Init()
Description
Initializes the USB Mass Storage Class Driver.
Prototype
int USBH_MSD_Init(USBH_MSD_LUN_NOTIFICATION_FUNC * pfLunNotification,
void * pContext);
Parameters
Parameter | Description |
pfLunNotification | Pointer to a function that shall be called when a new device notification is received. The function is called when a device is attached and ready or when it is removed. |
pContext | Pointer to a context that should be passed to pfLunNotification. |
Return value
1 | Success. |
0 | Initialization failed. |
Additional information
Performs basic initialization of the library. Has to be called
before any other library function is called.
Example:
/*********************************************************************
*
* _cbOnAddRemoveDevice
*
* Function description
* Callback, called when a device is added or removed.
* Call in the context of the USBH_Task.
* The functionality in this routine should not block!
*/
static void _cbOnAddRemoveDevice(void * pContext, U8 DevIndex, USBH_MSD_EVENT Event) {
switch (Event) {
case USBH_MSD_EVENT_ADD:
USBH_Logf_Application("**** Device added\n");
_MSDReady = 1;
_CurrentDevIndex = DevIndex;
break;
case USBH_MSD_EVENT_REMOVE:
USBH_Logf_Application("**** Device removed\n");
_MSDReady = 0;
_CurrentDevIndex = 0xff;
break;
default: /* USBH_MSD_EVENT_ERROR */
USBH_Logf_Application("**** Device error\n");
break;
}
}
<...>
USBH_MSD_Init(_cbOnAddRemoveDevice, NULL);
<...>
USBH_MSD_ReadSectors()
Description
Reads sectors from a USB Mass Storage device. To read file and
folders use the file system functions. This function allows to read
sectors raw.
Prototype
USBH_STATUS USBH_MSD_ReadSectors(U8 Unit,
U32 SectorAddress,
U32 NumSectors,
U8 * pBuffer);
Parameters
Parameter | Description |
Unit | 0-based Unit Id. See USBH_MSD_GetUnits(). |
SectorAddress | Index of the first sector to read. The first sector has the index 0. |
NumSectors | Number of sectors to read. |
pBuffer | Pointer to a caller allocated buffer. |
Return value
= USBH_STATUS_SUCCESS | Sectors successfully read. |
≠ USBH_STATUS_SUCCESS | An error occurred. |
USBH_MSD_WriteSectors()
Description
Writes sectors to a USB Mass Storage device. To write files and
folders use the file system functions. This function allows to write
sectors raw.
Prototype
USBH_STATUS USBH_MSD_WriteSectors( U8 Unit,
U32 SectorAddress,
U32 NumSectors,
const U8 * pBuffer);
Parameters
Parameter | Description |
Unit | 0-based Unit Id. See USBH_MSD_GetUnits(). |
SectorAddress | Index of the first sector to write. The first sector has the index 0. |
NumSectors | Number of sectors to write. |
pBuffer | Pointer to the data. |
Return value
= USBH_STATUS_SUCCESS | Sectors successfully written. |
≠ USBH_STATUS_SUCCESS | An error occurred. |
USBH_MSD_UseAheadCache()
Description
Enables the read-ahead-cache functionality.
Prototype
void USBH_MSD_UseAheadCache(int OnOff);
Parameters
Parameter | Description |
OnOff | 1 : on, 0 - off. |
Additional information
The read-ahead-cache is a functionality which makes sure that read
accesses to an MSD will always read a minimal amount of sectors
(normally at least four). The rest of the sectors which have not
been requested directly will be stored in a cache and subsequent
reads will be supplied with data from the cache instead of the
actual device.
This functionality is mainly used as a workaround for certain MSD
devices which crash when single sectors are being read directly
from the device too often. Enabling the cache will cause a slight
drop in performance, but will make sure that all MSD devices which
are affected by the aforementioned issue do not crash. Unless
USBH_MSD_SetAheadBuffer() was used before calling this function
with a “1” as parameter the function will try to allocate a buffer
for eight sectors (4096 bytes) from the emUSB-Host memory pool.
USBH_MSD_SetAheadBuffer()
Description
Sets a user provided buffer for the read-ahead-cache functionality.
Prototype
void USBH_MSD_SetAheadBuffer(const USBH_MSD_AHEAD_BUFFER * pAheadBuf);
Parameters
Parameter | Description |
pAheadBuf | Pointer to a USBH_MSD_AHEAD_BUFFER structure which holds the buffer information. |
Additional information
This function has to be called before enabling the read-ahead-cache
with USBH_MSD_UseAheadCache(). The buffer should have space for
at least four sectors (2048 bytes), but eight sectors (4096 bytes)
are suggested for better performance. The buffer size must be a
multiple of 512.
Data Structures
This chapter describes the used emUSB-Host MSD API structures.
USBH_MSD_UNIT_INFO
Description
Contains logical unit information.
Type definition
typedef struct {
U32 TotalSectors;
U16 BytesPerSector;
int WriteProtectFlag;
U16 VendorId;
U16 ProductId;
char acVendorName[];
char acProductName[];
char acRevision[];
} USBH_MSD_UNIT_INFO;
Structure members
Member | Description |
TotalSectors | Contains the number of total sectors available on the LUN. |
BytesPerSector | Contains the number of bytes per sector. |
WriteProtectFlag | Nonzero if the device is write protected. |
VendorId | USB Vendor ID. |
ProductId | USB Product ID. |
acVendorName | Vendor identification string. |
acProductName | Product identification string. |
acRevision | Revision string. |
USBH_MSD_AHEAD_BUFFER
Description
Structure describing the read-ahead-cache buffer.
Type definition
typedef struct {
U8 * pBuffer;
U32 Size;
} USBH_MSD_AHEAD_BUFFER;
Structure members
Member | Description |
pBuffer | Pointer to a buffer. |
Size | Size of the buffer in bytes. |
Function Types
This chapter describes the used emUSB-Host MSD API function types.
USBH_MSD_LUN_NOTIFICATION_FUNC
Description
This callback function is called when a logical unit is either
added or removed. To get detailed information USBH_MSD_GetStatus()
has to be called. The LUN indexes must be used to get access to
a specified unit of the device.
Type definition
typedef void USBH_MSD_LUN_NOTIFICATION_FUNC(void * pContext,
U8 DevIndex,
USBH_MSD_EVENT Event);
Parameters
Parameter | Description |
pContext | Pointer to a context that was set by the user when the USBH_MSD_Init() was called. |
DevIndex | Zero based index of the device that was attached or removed. |
Event | Gives information about the event that has occurred. The following events are currently available: USBH_MSD_EVENT_ADD A device was attached. USBH_MSD_EVENT_REMOVE A device was removed. USBH_MSD_EVENT_ERROR A new device could not be added because of errors. |
MTP Device Driver (Add-On)
This chapter describes the optional emUSB-Host add-on “MTP device driver”.
It allows communication with MTP USB devices.
Introduction
The MTP driver software component of emUSB-Host allows communication with MTP
devices such as Android or Windows smartphones, media players, cameras and so
on.
A file system is not required to use emUSB-Host MTP.
This chapter provides an explanation of the functions available to application developers
via the MTP driver software. All the functions and data types of this add-on are
prefixed with the “USBH_MTP_” text.
Overview
An MTP device connected to the emUSB-Host is automatically configured and added
to an internal list. If the MTP module has been registered, it is notified via a callback
when an MTP device has been added or removed. The driver then can notify the
application program when a callback function has been registered via
USBH_MTP_RegisterNotification(). In order to communicate with such a device,
the application has to call USBH_MTP_Open(), passing the device index. MTP devices
are identified by an index. The first connected device gets assigned the index 0, the
second index 1, and so on.
Features
The following features are provided:
- Compatibility with different MTP devices.
Example code
An example application which demonstrates the API is provided in the USBH_MTP_Start.c file.
API Functions
This chapter describes the emUSB-Host MTP driver API functions.
USBH_MTP_Init()
Description
Initializes and registers the MTP device driver with emUSB-Host.
Prototype
USBH_STATUS USBH_MTP_Init(void);
Return value
USBH_STATUS_SUCCESS | Success. |
USBH_STATUS_MEMORY | Can not init MTP module, out of memory. |
USBH_MTP_Exit()
Description
Unregisters and de-initializes the MTP device driver from emUSB-Host.
Prototype
void USBH_MTP_Exit(void);
Additional information
This function will release resources that were used by this device driver.
It has to be called if the application is closed. This has to be
called before USBH_Exit() is called. No more functions of this
module may be called after calling USBH_MTP_Exit(). The only
exception is USBH_MTP_Init(), which would in turn re-init
the module and allow further calls.
USBH_MTP_RegisterNotification()
Description
Sets a callback in order to be notified when a device is added
or removed.
Prototype
void USBH_MTP_RegisterNotification(USBH_NOTIFICATION_FUNC * pfNotification,
void * pContext);
Parameters
Parameter | Description |
pfNotification | Pointer to a function the stack should call when a device is connected or disconnected. |
pContext | Pointer to a user context that should be passed to the callback function |
Additional information
Only one notification function can be set for all devices.
To unregister, call this function with the pfNotification
parameter set to NULL.
USBH_MTP_Open()
Description
Opens a device using the given index.
Prototype
USBH_MTP_DEVICE_HANDLE USBH_MTP_Open(U8 Index);
Parameters
Parameter | Description |
Index | Index of the device that should be opened. In general this means: the first connected device is 0, second device is 1 etc. |
Return value
≠ 0 | Handle to the device |
= 0 | Device not available or removed. |
USBH_MTP_Close()
Description
Closes a handle to an opened device.
Prototype
USBH_STATUS USBH_MTP_Close(USBH_MTP_DEVICE_HANDLE hDevice);
Parameters
Parameter | Description |
hDevice | Handle to the opened device. |
Return value
= USBH_STATUS_SUCCESS | Successful. |
≠ USBH_STATUS_SUCCESS | An error occurred. |
USBH_MTP_GetDeviceInfo()
Description
Retrieves basic information about the MTP device.
Prototype
USBH_STATUS USBH_MTP_GetDeviceInfo(USBH_MTP_DEVICE_HANDLE hDevice,
USBH_MTP_DEVICE_INFO * pDevInfo);
Parameters
Parameter | Description |
hDevice | Handle to the opened device. |
pDevInfo | out Pointer to a USBH_MTP_DEVICE_INFO structure where the information related to the device will be stored. |
Return value
= USBH_STATUS_SUCCESS | Successful. |
≠ USBH_STATUS_SUCCESS | An error occurred. |
USBH_MTP_GetNumStorages()
Description
Retrieves the number of storages the device has.
Prototype
USBH_STATUS USBH_MTP_GetNumStorages(USBH_MTP_DEVICE_HANDLE hDevice,
U8 * pNumStorages);
Parameters
Parameter | Description |
hDevice | Handle to the opened device. |
pNumStorages | out Pointer to a variable where the number of storages reported by the device will be stored. |
Return value
= USBH_STATUS_SUCCESS | Successful. |
≠ USBH_STATUS_SUCCESS | An error occurred. |
Additional information
This function may return zero storages when the device is locked.
Unfortunately this is not always the case and can not be used as
a criteria to check whether a device is locked (e.g. Windows
Phones will return the correct number of storages even if they
are locked.)
See USBH_MTP_CheckLock() for further information.
USBH_MTP_Reset()
Description
Executes the MTP reset command on the device. This command sets
the device in the default state. “Default state” can mean different
things for different manufacturers. This MTP command is rarely
supported by devices. This command will close all sessions on
the device side. Therefore the host application should call
USBH_MTP_Close() after a successful call to this function.
Prototype
USBH_STATUS USBH_MTP_Reset(USBH_MTP_DEVICE_HANDLE hDevice);
Parameters
Parameter | Description |
hDevice | Handle to the opened device. |
Return value
= USBH_STATUS_SUCCESS | Successful. |
≠ USBH_STATUS_SUCCESS | An error occurred. |
USBH_MTP_SetTimeouts()
Description
Sets timeouts for read and write transactions for a device.
The timeouts are valid for single transactions, not for whole API calls.
Prototype
USBH_STATUS USBH_MTP_SetTimeouts(USBH_MTP_DEVICE_HANDLE hDevice,
U32 ReadTimeout,
U32 WriteTimeout);
Parameters
Parameter | Description |
hDevice | Handle to the opened device. |
ReadTimeout | Timeout for all transactions which read from the device. |
WriteTimeout | Timeout for all transactions which write to the device. |
Return value
= USBH_STATUS_SUCCESS | Successful. |
≠ USBH_STATUS_SUCCESS | An error occurred. |
Additional information
It is advised to set the timeouts to at least 10 seconds, as this
is the time many Android devices may require to respond to certain commands.
USBH_MTP_GetLastErrorCode()
Description
Returns the error code for the last executed operation.
Prototype
U16 USBH_MTP_GetLastErrorCode(USBH_MTP_DEVICE_HANDLE hDevice);
Parameters
Parameter | Description |
hDevice | Handle to the opened device. |
Return value
= 0 | Last operation completed without an error code. |
≠ 0 | Error code. See USBH_MTP_RESPONSE_CODES for a list of MTP error codes. |
USBH_MTP_GetStorageInfo()
Description
Retrieves information about a storage on the device.
Prototype
USBH_STATUS USBH_MTP_GetStorageInfo(USBH_MTP_DEVICE_HANDLE hDevice,
U8 StorageIndex,
USBH_MTP_STORAGE_INFO * pStorageInfo);
Parameters
Parameter | Description |
hDevice | Handle to the opened device. |
StorageIndex | Zero-based index of the storage, see USBH_MTP_GetNumStorages(). |
pStorageInfo | out Pointer to a USBH_MTP_STORAGE_INFO structure to store information related to the storage. |
Return value
= USBH_STATUS_SUCCESS | Successful. |
≠ USBH_STATUS_SUCCESS | An error occurred. |
Notes
This operation is always supported by MTP devices.
Description
Formats (deletes all data!) on a device storage.
Prototype
USBH_STATUS USBH_MTP_Format(USBH_MTP_DEVICE_HANDLE hDevice,
U8 StorageIndex);
Parameters
Parameter | Description |
hDevice | Handle to the opened device. |
StorageIndex | Zero-based index of the storage, see USBH_MTP_GetNumStorages(). |
Return value
= USBH_STATUS_SUCCESS | Successful. |
≠ USBH_STATUS_SUCCESS | An error occurred. |
USBH_MTP_GetNumObjects()
Description
Retrieves the number of objects inside a single directory.
Prototype
USBH_STATUS USBH_MTP_GetNumObjects(USBH_MTP_DEVICE_HANDLE hDevice,
U8 StorageIndex,
U32 DirObjectID,
U32 * pNumObjects);
Parameters
Parameter | Description |
hDevice | Handle to the opened device. |
StorageIndex | Zero-based index of the storage, see USBH_MTP_GetNumStorages(). |
DirObjectID | Object ID for the directory. |
pNumObjects | out Pointer to a variable where the number of objects inside the directory will be stored. |
Return value
= USBH_STATUS_SUCCESS | Successful. |
≠ USBH_STATUS_SUCCESS | An error occurred. |
USBH_MTP_GetObjectList()
Description
Retrieves a list of object IDs from a directory.
The number of objects inside a directory can be found out
beforehand by using USBH_MTP_GetNumObjects.
Prototype
USBH_STATUS USBH_MTP_GetObjectList(USBH_MTP_DEVICE_HANDLE hDevice,
U8 StorageIndex,
U32 DirObjectID,
USBH_MTP_OBJECT * pBuffer,
U32 * pNumObjects);
Parameters
Parameter | Description |
hDevice | Handle to the opened device. |
StorageIndex | Zero-based index of the storage, see USBH_MTP_GetNumStorages(). |
DirObjectID | Object ID for the directory. |
pBuffer | out Pointer to an array of USBH_MTP_OBJECT structures. |
pNumObjects | in/out The application should specify the size of the buffer in USBH_MTP_OBJECT units. The MTP module will read object IDs up to the specified value. If there are less objects in the folder the number of objects read will be stored in this variable. If there are more objects in the folder than specified the data for the surplus objects is discarded by the module. |
Return value
= USBH_STATUS_SUCCESS | Successful. |
≠ USBH_STATUS_SUCCESS | An error occurred. |
Example
static USBH_MTP_OBJECT _aObjBuffer[10];
<...>
Status = USBH_MTP_GetNumObjects(hDevice, StorageIndex, DirObjectID, &NumObjectsDir);
if (Status == USBH_STATUS_SUCCESS) {
USBH_Logf_Application("Found %d objects in directory 0x%0.8X \n",
NumObjectsDir, DirObjectID);
NumObjects = USBH_MIN(NumObjectsDir, NumObjectsFree);
//
// Retrieve a list of object IDs from the root directory.
//
Status = USBH_MTP_GetObjectList(hDevice,
StorageIndex,
DirObjectID,
_aObjBuffer,
&NumObjects);
if (Status == USBH_STATUS_SUCCESS) {
<...>
} else {
<...>
}
} else {
<...>
}
USBH_MTP_GetObjectInfo()
Description
Retrieves the ObjectInfo dataset for a specific object.
Prototype
USBH_STATUS USBH_MTP_GetObjectInfo(USBH_MTP_DEVICE_HANDLE hDevice,
U32 ObjectID,
USBH_MTP_OBJECT_INFO * pObjInfo);
Parameters
Parameter | Description |
hDevice | Handle to the opened device. |
ObjectID | Object ID to retrieve information for. |
pObjInfo | out Pointer to a USBH_MTP_OBJECT_INFO structure where the data will be stored. |
Return value
= USBH_STATUS_SUCCESS | Successful. |
≠ USBH_STATUS_SUCCESS | An error occurred. |
USBH_MTP_CreateObject()
Description
Writes a new object onto the device.
MTP does not allow files to be written in chunks, therefore a callback mechanism is
implemented to allow the embedded host to write files of any size onto the MTP
device. As soon as the contents of the first buffer have been written or the file has
been completely written onto the device - the registered callback is called. Inside the
callback the user can either put new data into the previously used buffer or change
the buffer by modifying the pNextBuffer parameter inside the USBH_SEND_DATA_FUNC
callback. Using two (or more) buffers and switching between them has the advantage
that the MTP module can write continuously to the device.
Prototype
USBH_STATUS USBH_MTP_CreateObject(USBH_MTP_DEVICE_HANDLE hDevice,
U8 StorageIndex,
USBH_MTP_CREATE_INFO * pInfo);
Parameters
Parameter | Description |
hDevice | Handle to the opened device. |
StorageIndex | Zero-based index of the storage, see USBH_MTP_GetNumStorages(). |
pInfo | in/out Pointer to a USBH_MTP_CREATE_INFO structure where parameters for the new object are stored. |
Return value
= USBH_STATUS_SUCCESS | Successful. On success the member ObjectID of the USBH_MTP_CREATE_INFO will contain the new object ID provided by the device. |
≠ USBH_STATUS_SUCCESS | An error occurred. |
Example
static U8 _acBufWrite[1024*64];
const U16 _sFileName[] = L"SEGGER.txt";
U32 FileSize = 1024 * 1024;
/*********************************************************************
*
* _SendData
*
* Function description
* In this sample application the file data is simply generated
* through a memset, in a real application data can for example
* be read from the host's file system.
*/
static void _SendData(void * pUserContext,
U32 NumBytesSentTotal,
U32 * pNumBytesToSend,
void ** pNextBuffer) {
U32 NumBytesToSend;
int r;
NumBytesToSend = *(U32*)&pUserContext - NumBytesSentTotal;
NumBytesToSend = USBH_MIN(sizeof(_acBufWrite), NumBytesToSend);
if (NumBytesToSend) {
USBH_MEMSET(_acBufWrite, 0xA5, NumBytesToSend);
}
}
<...>
USBH_MTP_CREATE_INFO CreateInfo;
CreateInfo.FileNameSize = strlen(_sFileName) + 1; // File name length
// + terminating character
CreateInfo.sFileName = _sFileName; // File name Unicode string
CreateInfo.ObjectSize = FileSize; // Size of the file in bytes
CreateInfo.ParentObjectID = ObjectID; // Object ID of the parent
// folder
CreateInfo.pfGetData = _SendData; // Callback function
CreateInfo.pUserBuf = _acBufWrite; // User buffer containing
// the data
CreateInfo.UserBufSize = sizeof(_acBufWrite); // Size of the user buffer
CreateInfo.isFolder = FALSE; // Not a folder
CreateInfo.pUserContext = (void*)FileSize; // User context is passed
// to the callback
Status = USBH_MTP_CreateObject(hDevice, StorageIndex, &CreateInfo);
<...>
USBH_MTP_DeleteObject()
Description
Deletes an object from the device.
Prototype
USBH_STATUS USBH_MTP_DeleteObject(USBH_MTP_DEVICE_HANDLE hDevice,
U32 ObjectID);
Parameters
Parameter | Description |
hDevice | Handle to the opened device. |
ObjectID | Object ID to be deleted. |
Return value
= USBH_STATUS_SUCCESS | Successful. |
≠ USBH_STATUS_SUCCESS | An error occurred. |
USBH_MTP_RenameObject()
Description
Changes the name of an object.
Prototype
USBH_STATUS USBH_MTP_RenameObject( USBH_MTP_DEVICE_HANDLE hDevice,
U32 ObjectID,
const U16 * sNewName,
U32 NumChars);
Parameters
Parameter | Description |
hDevice | Handle to the opened device. |
ObjectID | Object ID to retrieve the property from. |
sNewName | Pointer to a Unicode string containing the new file name. |
NumChars | Length of the new file name in U16 units. |
Return value
= USBH_STATUS_SUCCESS | Successful. |
≠ USBH_STATUS_SUCCESS | An error occurred. |
USBH_MTP_ReadFile()
Description
Reads a file from the device.
MTP does not allow files to be read in chunks, therefore a callback mechanism is
implemented to allow embedded devices with limited memory to be able to read files
of any size from an MTP device.
The callback is called as soon as the user provided buffer is full or the file has been
completely read. In the callback the user can either process the data in the user
buffer or change the user buffer by writing the pNextBuffer parameter inside the
USBH_RECEIVE_DATA_FUNC callback and process the data in the first buffer in another
task. The second method has the advantage that the callback can return immediately
and the MTP module can continue reading from the device.
Prototype
USBH_STATUS USBH_MTP_ReadFile(USBH_MTP_DEVICE_HANDLE hDevice,
U32 ObjectID,
USBH_RECEIVE_DATA_FUNC * pfReadData,
void * pUserContext,
U8 * pUserBuf,
U32 UserBufSize);
Parameters
Parameter | Description |
hDevice | Handle to the opened device. |
ObjectID | Object ID of the file to read. |
pfReadData | Pointer to a user-provided USBH_RECEIVE_DATA_FUNC callback function which will be called when the file is being received. |
pUserContext | Pointer to a user context which is passed to the callback function. |
pUserBuf | Pointer to a buffer where the data will be stored. This parameter can be NULL. In this case the callback is called directly and a buffer has to be set from there. |
UserBufSize | Size of the user buffer. |
Return value
= USBH_STATUS_SUCCESS | Successful. |
≠ USBH_STATUS_SUCCESS | An error occurred. |
Example
/*********************************************************************
*
* _ReceiveData
*
* Function description
* This function is responsible for receiving the data provided by
* the USBH_MTP_ReadFile function.
*/
static void _ReceiveData(void * pUserContext,
U32 NumBytesRemaining,
U32 NumBytesInBuffer,
void ** pNextBuffer,
U32 * pNextBufferSize) {
printf("Reading file 0x%8.8lX, reading chunk of %lu still have to "
"read %lu bytes for the current file.\n",
*(U32*)pUserContext,
NumBytesInBuffer,
NumBytesRemaining);
}
<...>
Status =