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.
USB Background information
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:
Config
Inc
SEGGER
USBH
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.
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().
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:
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:
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 addedRunning sample on "msd:0:"Reading volume information...****Volume information formsd:0:125105536KBytes total disk space125105536KBytes available free space32768bytes per cluster3909548clusters available on volume3909548free cluster available on volumeCreating file msd:0:\TestFile.txt...OkContents of msd:0:TESTFILE.TXT Attributes:A---Size:21****Unmount ****Test with the following device was successful:VendorId:0x1234ProductId:0x5678VendorName:XXXXXXXProductName:XXXXXXXXXXXXXXRevision:1.00NumSectors:250272768BytesPerSector:512TotalSize:122203MByteHighspeedCapable:NoConnectedToRootHub:YesSelfPowered:NoReported Imax:500mAConnected to Port:1PortSpeed: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 addedDevice Id =MFG:Hewlett-Packard;CMD:PJL,PML,POSTSCRIPT,PCLXL,PCL;MDL:HPLaserJet P2015 Series;CLS:PRINTER;DES:Hewlett-Packard LaserJet P2015Series;MEM:MEM=23MB;COMMENT:RES=1200x1;PortStatus =0x18->NoError=1,Select/OnLine=1,PaperEmpty=0Printing Hello World to printerPrinting 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:663USBH_isr -INIT:USBH_ISRTaskstarted****Device addedVendor Id =0x1234Product Id =0x5678Serial no.=123456789Speed =HighSpeedStarted communication...<...>****Device removed
Media Transfer Protocol (USBH_MTP_Start.c)
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 addedVendor Id =0x1234Product Id =0x1234Serial no.=1Speed =FullSpeedManufacturer :XXXXXXModel :XXXXXXXXXXXXXXXXXXXXXXDeviceVersion :8.10.12397.0MTP SerialNumber :844848fb44583cbaa1ecae45545b3USBH_MTP_CheckLockreturns USBH_STATUS_ERRORPlease unlock the device to proceed.<...>_cbOnUserEvent:MTP Event received!EventCode:0x4004,Para1:0x00010001,Para2:0x00000000,Para3:0x00000000.<...>USBH_MTP_CheckLockreturns USBH_STATUS_SUCCESSFound storage with ID:0StorageType =0x0003FilesystemType =0x0002AccessCapability =0x0000MaxCapacity =3959422976bytesFreeSpaceInBytes =1033814016bytesFreeSpaceInImages =0x00000000StorageDescription :PhoneVolumeLabel :MTP Volume -65537Found 9objects in directory 0xFFFFFFFFProcessing object 0x00000001in directory 0xFFFFFFFF...StorageID =0x00010001ObjectFormat =0x3001ParentObject =0xFFFFFFFFProtectionStatus =0x0001Filename :DocumentsCaptureDate :20140522T0ModificationDate :20160707T1Processing object 0x00000002in directory 0xFFFFFFFF...StorageID =0x00010001ObjectFormat =0x3001ParentObject =0xFFFFFFFFProtectionStatus =0x0001Filename :DownloadsCaptureDate :20140522T0ModificationDate :20160707T1<...>Creating newobject with 135bytes in folder 0xFFFFFFFFwith name SEGGER_Test.txt.Created newobject 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:213MainTask -Vendor Id =0x04033:213MainTask -Product Id =0x60013:213MainTask -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.
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.
Removes a previously registered notification for PnP events.
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.
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().
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.
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.
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.
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.
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.*/staticvoid_ListJLinkDevices(void){USBH_INTERFACE_MASKIfaceMask;unsignedintIfaceCount;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{unsignedinti;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);}}
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.
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.
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.
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.
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.
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.
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.
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.
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.
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).
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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)
staticU8 _Buffer[512];staticUSBH_URB _Urb;staticvoid_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)
staticU8 _Buffer[512];staticUSBH_URB _Urb;staticvoid_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.
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).
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.
/*********************************************************************** _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.*/staticvoid_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.*/staticvoid_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.
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.
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.
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.
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.
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_CONTROLUSB_EP_TYPE_BULKUSB_EP_TYPE_ISOUSB_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
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.
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.
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.
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).
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.
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.
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().
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().
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.
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.
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.
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.
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.
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.
[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.
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.
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.
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.
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).
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.
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.
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.
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.
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.
Binary mask of the following items USBH_HID_IND_NUM_LOCKUSBH_HID_IND_CAPS_LOCKUSBH_HID_IND_SCROLL_LOCKUSBH_HID_IND_COMPOSEUSBH_HID_IND_KANAUSBH_HID_IND_SHIFT
Return value
USBH_STATUS_SUCCESS on success or error code on failure.
Binary mask of the following items USBH_HID_IND_NUM_LOCKUSBH_HID_IND_CAPS_LOCKUSBH_HID_IND_SCROLL_LOCKUSBH_HID_IND_COMPOSEUSBH_HID_IND_KANAUSBH_HID_IND_SHIFT
Return value
USBH_STATUS_SUCCESS on success or error code on failure.
USBH_HID_ConfigureAllowLEDUpdate()
Description
Sets whether the keyboard LED should be updated or not.
(Default is disabled).
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.
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.
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.
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.
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.
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.
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.
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().
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.
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).
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.
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.
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.
Sets a user provided buffer for the read-ahead-cache functionality.
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.
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.
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).
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!*/staticvoid_cbOnAddRemoveDevice(void*pContext,U8 DevIndex,USBH_MSD_EVENTEvent){switch(Event){caseUSBH_MSD_EVENT_ADD:USBH_Logf_Application("**** Device added\n");_MSDReady =1;_CurrentDevIndex =DevIndex;break;caseUSBH_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.
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.
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.
This callback function is called when a logical unit is either added or removed.
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.
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.
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.
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.)
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.
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
staticUSBH_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.
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.
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
staticU8 _acBufWrite[1024*64];constU16 _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.*/staticvoid_SendData(void*pUserContext,U32 NumBytesSentTotal,U32 *pNumBytesToSend,void**pNextBuffer){U32 NumBytesToSend;intr;NumBytesToSend =*(U32*)&pUserContext -NumBytesSentTotal;NumBytesToSend =USBH_MIN(sizeof(_acBufWrite),NumBytesToSend);if(NumBytesToSend){USBH_MEMSET(_acBufWrite,0xA5,NumBytesToSend);}}<...>USBH_MTP_CREATE_INFOCreateInfo;CreateInfo.FileNameSize =strlen(_sFileName)+1;// File name length// + terminating characterCreateInfo.sFileName =_sFileName;// File name Unicode stringCreateInfo.ObjectSize =FileSize;// Size of the file in bytesCreateInfo.ParentObjectID =ObjectID;// Object ID of the parent// folderCreateInfo.pfGetData =_SendData;// Callback functionCreateInfo.pUserBuf =_acBufWrite;// User buffer containing// the dataCreateInfo.UserBufSize =sizeof(_acBufWrite);// Size of the user bufferCreateInfo.isFolder =FALSE;// Not a folderCreateInfo.pUserContext =(void*)FileSize;// User context is passed// to the callbackStatus =USBH_MTP_CreateObject(hDevice,StorageIndex,&CreateInfo);<...>
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.
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.*/staticvoid_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 =USBH_MTP_ReadFile(hDevice,// Handle to the deviceObjectID,// Object ID to read&_ReceiveData,// Callback function&ObjectID,// User context passed to the callback_acReadBuf,// User buffer to usesizeof(_acReadBuf));// User buffer size
USBH_MTP_GetDevicePropDesc()
Description
Retrieves the description of a MTP property from the device.
The description includes the size of a property, which is highly
important as the same properties can have different sizes on
different devices.
Retrieves the value of a property of a specific Device.
The property description has to be retrieved
via USBH_MTP_GetDevicePropDesc prior to calling this function.
MTP Format Code ID for the MTP property which should be queried. (See USBH_MTP_OBJECT_FORMAT for a list of valid format codes).
pBuffer
out Pointer to an array of U16 values, this array will receive the list of property codes.
pNumProps
in/out The application should specify the size of the buffer in U16 values. The MTP module will read property codes up to the specified value. If there are less codes delivered by the device the number of codes read will be stored in this variable. If there are more codes delivered by device the surplus codes are discarded by the module.
Return value
= USBH_STATUS_SUCCESS
Successful.
≠ USBH_STATUS_SUCCESS
An error occurred.
Additional information
Unfortunately there is no way to ask the device how many properties
a format has before requesting the list or to request a partial list,
therefore the buffer should be big enough to contain all of them.
USBH_MTP_GetObjectPropDesc()
Description
Retrieves information about an MTP object property used by the device.
This is especially important because the application needs to know
the data type (the size) of the property before retrieving it.
MTP Format Code ID for the MTP property which should be queried. (See USBH_MTP_OBJECT_FORMAT for a list of valid format codes).
pDesc
in Pointer to a USBH_MTP_OBJECT_PROP_DESC structure where the MTP property descriptor will be stored.
Return value
= USBH_STATUS_SUCCESS
Successful.
≠ USBH_STATUS_SUCCESS
An error occurred.
Example
/*********************************************************************** _DataTypeToBytes** Function description* Returns the number of bytes required for the given data type.*/staticunsigned_DataTypeToBytes(U16 DataType){unsignedNumBytes;switch(DataType){caseUSBH_MTP_DATA_TYPE_INT8:caseUSBH_MTP_DATA_TYPE_UINT8:NumBytes =1;break;caseUSBH_MTP_DATA_TYPE_INT16:caseUSBH_MTP_DATA_TYPE_UINT16:NumBytes =2;break;caseUSBH_MTP_DATA_TYPE_INT32:caseUSBH_MTP_DATA_TYPE_UINT32:NumBytes =4;break;caseUSBH_MTP_DATA_TYPE_INT64:caseUSBH_MTP_DATA_TYPE_UINT64:NumBytes =8;break;caseUSBH_MTP_DATA_TYPE_STR:NumBytes =256;break;caseUSBH_MTP_DATA_TYPE_UINT128:NumBytes =16;break;default:NumBytes =0;// Error, invalid data type.break;}returnNumBytes;}USBH_MTP_OBJECT_PROP_DESCObjPropDesc;U8 *pPropertyBuffer;//// Check in which format the property// USBH_MTP_OBJECT_PROP_STORAGE_ID is stored.//Status =USBH_MTP_GetObjectPropDesc(hDevice,USBH_MTP_OBJECT_PROP_STORAGE_ID,USBH_MTP_OBJECT_FORMAT_UNDEFINED,&ObjPropDesc);if(Status ==USBH_STATUS_SUCCESS){//// Now that we know the format - memory can be allocated// and the property can be retrieved.//NumBytes =_DataTypeToBytes(ObjPropDesc.DataType);pPropertyBuffer =malloc(NumBytes);if(pPropertyBuffer){Status =USBH_MTP_GetObjectPropValue(hDevice,CreateInfo.ObjectID,&ObjPropDesc,pPropertyBuffer,NumBytes);if(Status ==USBH_STATUS_SUCCESS){<...dosomething with the value...>}else{<...>}free(pPropertyBuffer);}else{<...>}}else{<...>}
USBH_MTP_GetObjectPropValue()
Description
Retrieves the value of a property of a specific object.
The property description has to be retrieved
via USBH_MTP_GetObjectPropDesc prior to calling this function.
Any other value means the device is locked and reports the specific error through which it was determined.
Additional information
Some devices (mainly Windows Phone) may re-enumerate when they are unlocked
by the user, which will cause this function to correctly report
USBH_STATUS_DEVICE_REMOVED. The application should open a new handle to the
device and call this function again.
On some devices (mainly Android) the storage count of the device (the value which
you get from USBH_MTP_GetNumStorages()) will be updated automatically when this
function is called and the user has unlocked the device (normally from
zero to the real value).
USBH_MTP_SetEventCallback()
Description
Sets a callback for MTP events, e.g. StoreAdded, ObjectAdded, etc.
The callback should not block.
See the description of USBH_EVENT_CALLBACK for additional information.
USBH_MTP_ConfigEventSupport()
Description
Turns MTP event support on or off.
Should be called after USBH_MTP_Init()
When turning MTP support on or off only newly connected devices
will be affected.
Event support is off by default.
Calling this function will not affect devices which are already open.
To make sure open devices are affected you have to close them
(USBH_MTP_Close()) and open them again (USBH_MTP_Open()).
Some MTP devices do not behave as they should when re-opening
a session and refuse to communicate, in such a case it is
advised to re-enumerate them.
0x0000 Undefined 0x0001 Fixed ROM 0x0002 Removable ROM 0x0003 Fixed RAM 0x0004 Removable RAM Note: This value is often unreliable as many devices return 0x0003 for everything.
0x0000 Read-write 0x0001 Read-only without object deletion 0x0002 Read-only with object deletion
MaxCapacity
An U64 little-endian value which designates the maximum capacity of the storage in bytes. The value is declared as an array of U8, you will have to cast it into a U64 in your application. If the storage is read-only, this field is optional and may contain zero.
FreeSpaceInBytes
An U64 little-endian value which designates the free space on the storage in bytes. The value is declared as an array of U8, you will have to cast it into a U64 in your application. If the storage is read-only, this field is optional and may contain zero.
FreeSpaceInImages
Value describing the number of images which could still be fit into the storage. This is a PTP relevant value, for MTP it is normally zero or 0xFFFFFFFF.
Pointer to a user-provided callback which will provide the data. See USBH_SEND_DATA_FUNC.
FileNameSize
The length of the file-name string (including termination).
sFileName
Pointer to the Unicode file-name string (must include zero-termination).
isFolder
Flag indicating whether the new object should be a folder or not. When creating a folder pfGetData, pUserBuf, UserBufSize can be set to NULL.
pUserBuf
Pointer to a user buffer where the data is located. Can be NULL, in this case the callback is called immediately and the buffer has to be set inside the callback.
UserBufSize
Size of the user buffer in bytes.
pUserContext
User context which is passed to the callback.
USBH_MTP_OBJECT_PROP_DESC
Description
Contains information about the data-type and accessibility of an object property.
This value contains the total number of bytes which have already been transferred
pNumBytesToSend
The user has to set this value to the number of bytes which are inside the buffer.
ppNextBuffer
The user can change this pointer to a different buffer. If this parameter remains NULL after the callback returns, the previous buffer is re-used (the application should put new data into the buffer first).
USBH_RECEIVE_DATA_FUNC
Description
Definition of the callback which has to be specified when using USBH_MTP_ReadFile().
This value contains the total number of bytes which still have to be read.
NumBytesInBuffer
The number of bytes which have been read in this transaction.
ppNextBuffer
The user can change this pointer to a different buffer. If this parameter remains NULL after the callback returns, the previous buffer is re-used (the application should copy the data out of the buffer first, as it will be overwritten on the next transaction).
pNextBufferSize
Size of the next buffer. This only needs to be changed when the pNextBuffer parameter is changed.
The events USBH_MTP_EVENT_STORE_ADDED and USBH_MTP_EVENT_STORE_REMOVED
are handled by the MTP module before being passed to the callback.
The storage information for the device is updated automatically
when one of these events is received. All events are passed to
the callback, this includes vendor specific events which are not
present in the USBH_MTP_EVENT_CODES enum. Parameters which are
not used with a specific event (e.g. USBH_MTP_EVENT_STORE_ADDED
has only one parameter) will be passed as zero.
The callback should not block.
Enums
This chapter describes the emUSB-Host MTP API enums.
This chapter describes the optional emUSB-Host add-on “CDC device driver”.
It allows communication with a CDC USB device.
Introduction
The CDC driver software component of emUSB-Host allows communication with CDC
devices. The Communication Device Class (CDC) is an abstract USB class protocol
defined by the USB Implementers Forum. The protocol allows emulation of serial
communication via USB.
This chapter provides an explanation of the functions available to application developers
via the CDC driver software. All the functions and data types of this add-on are
prefixed with ’USBH_CDC_’.
Overview
A CDC device connected to the emUSB-Host is automatically configured and added to
an internal list. If the CDC driver has been registered, it is notified via a callback
when a CDC device has been added or removed. The driver then can notify the application
program, when a callback function has been registered via
USBH_CDC_AddNotification(). In order to communicate with such a device,
the application has to call the USBH_CDC_Open(), passing the device index. CDC
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 CDC devices.
Ability to send and receive data.
Ability to set various parameters, such as baudrate, number of stop bits, parity.
Handling of multiple CDC devices at the same time.
Notifications about CDC connection status.
Ability to query the CDC line and modem status.
Example code
An example application which uses the API is provided in the USBH_CDC_Start.c file.
This example displays information about the CDC device in the I/O terminal of the
debugger. In addition the application then starts a simple echo server, sending back
the received data.
API Functions
This chapter describes the emUSB-Host CDC driver API functions.
These functions are defined in the header file USBH_CDC.h.
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_CDC_Exit has to be called
the same number of times as this function was called.
USBH_CDC_Exit()
Description
Unregisters and de-initializes the CDC device module from emUSB-Host.
Before this function is called any notifications added via
USBH_CDC_AddNotification() must be removed
via USBH_CDC_RemoveNotification().
Has to be called the same number of times USBH_CDC_Init was
called in order to de-initialize the module.
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_CDC_Exit(). The only exception is USBH_CDC_Init(),
which would in turn re-init the module and allow further calls.
USBH_CDC_AddNotification()
Description
Adds a callback in order to be notified when a device is added or removed.
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.
Example
staticUSBH_NOTIFICATION_HOOK_Hook;/*********************************************************************** _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*/staticvoid_cbOnAddRemoveDevice(void*pContext,U8 DevIndex,USBH_DEVICE_EVENTEvent){(void)pContext;switch(Event){caseUSBH_DEVICE_EVENT_ADD:USBH_Logf_Application("**** Device added\n");_DevIndex =DevIndex;_DevIsReady =1;break;caseUSBH_DEVICE_EVENT_REMOVE:USBH_Logf_Application("**** Device removed\n");_DevIsReady =0;_DevIndex =-1;break;default:;// Should never happen}}<...>USBH_CDC_Init();USBH_CDC_AddNotification(&_Hook,_cbOnAddRemoveDevice,NULL);<...>
USBH_CDC_RemoveNotification()
Description
Removes a callback added via USBH_CDC_AddNotification.
USBH_STATUS_SUCCESS on success or error code on failure.
USBH_CDC_AllowShortRead()
Description
Enables or disables short read mode.
If enabled, the function USBH_CDC_Read() returns as soon as data was
read from the device. This allows the application to read data where the number of
bytes to read is undefined.
USBH_STATUS_SUCCESS on success or error code on failure.
USBH_CDC_Read()
Description
Reads from the CDC device. Depending of the ShortRead mode (see USBH_CDC_AllowShortRead()),
this function will either return as soon as data are available or
all data have been read from the device.
This function will also return when a set timeout is expired,
whatever comes first. If a timeout
is not specified via USBH_CDC_SetTimeouts() the default timeout (USBH_CDC_DEFAULT_TIMEOUT) is used.
The USB stack can only read complete packets from the USB device.
If the size of a received packet exceeds NumBytes then all data that does not
fit into the callers buffer (pData) is stored in an internal buffer and
will be returned by the next call to USBH_CDC_Read(). See also USBH_CDC_GetQueueStatus().
To read a null packet, set pData = NULL and NumBytes = 0.
For this, the internal buffer must be empty.
Pointer to a variable which receives the number of bytes read from the device. Can be NULL.
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 read part of the data. The number of bytes read successfully is always
stored in the variable pointed to by pNumBytesRead.
USBH_CDC_Write()
Description
Writes data to the CDC device. The function blocks until all data
has been written or until the timeout has been reached. If a timeout
is not specified via USBH_CDC_SetTimeouts() the default timeout (USBH_CDC_DEFAULT_TIMEOUT) is used.
Pointer to a variable which receives the number of bytes written to the device. Can be NULL.
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_CDC_GetMaxTransferSize()
Description
Return the maximum transfer sizes allowed for the USBH_CDC_*Async functions.
Pointer to a variable which will receive the maximum transfer size for the Bulk OUT endpoint (for USBH_CDC_ReadAsync()).
pMaxInTransferSize
Pointer to a variable which will receive the maximum transfer size for the Bulk IN endpoint (for USBH_CDC_WriteAsync()).
Return value
USBH_STATUS_SUCCESS on success or error code on failure.
Additional information
Using this function is only necessary with the USBH_CDC_*Async functions,
other functions handle the limits internally.
These limits exist because certain USB controllers have hardware limitations.
Some USB controllers (OHCI, EHCI, …) do not have these limitations, therefore 0xFFFFFFFF will be returned.
USBH_CDC_ReadAsync()
Description
Triggers a read transfer to the CDC device. The result of
the transfer is received through the user callback.
This function will return immediately while the read transfer is
done asynchronously. The read operation terminates either, if ’BuffSize’
bytes have been read or if a short packet was received from the device.
Pointer to the buffer that receives the data from the device.
BufferSize
Size of the buffer in bytes. Must be a multiple of of the maximum packet size of the USB device. Use USBH_CDC_GetMaxTransferSize() to get the maximum allowed size.
pfOnComplete
Pointer to a user function of type USBH_CDC_ON_COMPLETE_FUNC which will be called after the transfer has been completed.
pRWContext
Pointer to a USBH_CDC_RW_CONTEXT structure which will be filled with data after the transfer has been completed and passed as a parameter to the pfOnComplete function. The member ’pUserContext’ may be set before calling USBH_CDC_ReadAsync(). Other members need not be initialized and are set by the function USBH_CDC_ReadAsync(). The memory used for this structure must be valid, until the transaction is completed.
Return value
= USBH_STATUS_PENDING
Success, the data transfer is queued, the user callback will be called after the transfer is finished.
≠ USBH_STATUS_PENDING
An error occurred, the transfer is not started and user callback will not be called.
Triggers a write transfer to the CDC device. The result of
the transfer is received through the user callback.
This function will return immediately while the write transfer is
done asynchronously.
Pointer to a user function of type USBH_CDC_ON_COMPLETE_FUNC which will be called after the transfer has been completed.
pRWContext
Pointer to a USBH_CDC_RW_CONTEXT structure which will be filled with data after the transfer has been completed and passed as a parameter to the pfOnComplete function. pfOnComplete function. The member ’pUserContext’ may be set before calling USBH_CDC_WriteAsync(). Other members need not be initialized and are set by the function USBH_CDC_WriteAsync(). The memory used for this structure must be valid, until the transaction is completed.
Return value
= USBH_STATUS_PENDING
Success, the data transfer is queued, the user callback will be called after the transfer is finished.
≠ USBH_STATUS_PENDING
An error occurred, the transfer is not started and user callback will not be called.
Example
staticUSBH_CDC_RW_CONTEXT_ReadWriteContext;<...>/*********************************************************************** _OnWriteComplete*/staticvoid_OnWriteComplete(USBH_CDC_RW_CONTEXT*pRWContext){if(pRWContext->Status ==USBH_STATUS_SUCCESS){printf("Successfully written data to the device \n");}else{printf("WriteAsync callback returned %s \n",USBH_GetStatusStr(pRWContext->Status));// Error handling}<...>}<...>Status =USBH_CDC_WriteAsync(_hDevice,_acBuffer,NumBytes,_OnWriteComplete,&_ReadWriteContext);if(Status !=USBH_STATUS_PENDING){// Error handling.}<...>
USBH_STATUS_SUCCESS on success or error code on failure.
Additional information
This function can be used to cancel a transfer which was initiated
by USBH_CDC_ReadAsync or USBH_CDC_Read. In the later case this
function has to be called from a different task.
USBH_STATUS_SUCCESS on success or error code on failure.
Additional information
This function can be used to cancel a transfer which was initiated
by USBH_CDC_WriteAsync or USBH_CDC_Write. In the later case this
function has to be called from a different task.
USBH_CDC_SetCommParas()
Description
Setups the serial communication with the given characteristics.
Number of bits per word. Must be between USBH_CDC_BITS_5 and USBH_CDC_BITS_8.
StopBits
Number of stop bits. Must be USBH_CDC_STOP_BITS_1 or USBH_CDC_STOP_BITS_2.
Parity
Parity - must be must be one of the following values: UBSH_CDC_PARITY_NONEUBSH_CDC_PARITY_ODDUBSH_CDC_PARITY_EVENUBSH_CDC_PARITY_MARKUSBH_CDC_PARITY_SPACE
Return value
USBH_STATUS_SUCCESS on success or error code on failure.
USBH_CDC_SetDtr()
Description
Sets the Data Terminal Ready (DTR) control signal.
USBH_STATUS_SUCCESS on success or error code on failure.
USBH_CDC_GetQueueStatus()
Description
Gets the number of bytes in the receive queue.
The USB stack can only read complete packets from the USB device.
If the size of a received packet exceeds the number of bytes requested
with USBH_CDC_Read(), than all data that is not returned by USBH_CDC_Read()
is stored in an internal buffer.
The number of bytes returned by USBH_CDC_GetQueueStatus() can be read
using USBH_CDC_Read() out of the buffer without a USB transaction
to the USB device being executed.
Pointer to a variable which receives the number of bytes in the receive queue.
Return value
USBH_STATUS_SUCCESS on success or error code on failure.
Example
//// Read only ONE byte to trigger the read transfer.// This means that the remaining bytes are in the internal packet buffer!//USBH_CDC_Read(hDevice,acData,1,&NumBytes);if(NumBytes){//// We do not know how big the packet was which we received from the device,// since we only read 1 byte from the packet.// Therefore we still might have some data in the internal buffer!// Using USBH_CDC_GetQueueStatus we can check how many bytes are still in the// internal buffer (if any) and read those as well.//if(USBH_CDC_GetQueueStatus(hDevice,&RxBytes)==USBH_STATUS_SUCCESS){//// Read the remaining bytes.//if(RxBytes >0){USBH_CDC_Read(hDevice,&acData[1],RxBytes,&NumBytes);}}}
USBH_CDC_SetBreak()
Description
Sets the BREAK condition for the device for a limited time.
Pointer to a structure of type USBH_CDC_SERIALSTATE which receives the serial status from the device.
Return value
USBH_STATUS_SUCCESS on success or error code on failure.
Additional information
The least significant byte of the pSerialState value holds the modem status.
The line status is held in the second least significant byte of the pSerialState value.
The status is bit-mapped as follows:
Data Carrier Detect (DCD) = 0x01
Data Set Ready (DSR) = 0x02
Break Interrupt (BI) = 0x04
Ring Indicator (RI) = 0x08
Framing Error (FE) = 0x10
Parity Error (PE) = 0x20
Overrun Error (OE) = 0x40
USBH_CDC_SetOnSerialStateChange()
Description
Sets a callback which informs the user about serial state changes.
USBH_STATUS_SUCCESS on success or error code on failure.
USBH_CDC_AddDevice()
Description
Register a device with a non-standard interface layout as a CDC device.
This function should not be used for CDC compliant devices!
After registering the device the application will receive ADD and REMOVE notifications
to the user callback which was set by USBH_CDC_AddNotification().
USBH_STATUS_SUCCESS on success or error code on failure.
Additional information
The numeric interface IDs can be retrieved by setting up a PnP notification via
USBH_RegisterPnPNotification(). Please note that the PnP notification callback
will be triggered for each interface, but you only have to add the device once.
Alternatively you can simply set the IDs if you know the interface layout.
A bitwise OR-combination of flags that shall be set for each device. At the moment the following are available: USBH_CDC_IGNORE_INT_EP: This flag prevents the interrupt endpoint of the CDC interface from being polled by the CDC module. The interrupt endpoint is normally used in the CDC protocol to communicate the changes of serial states, using this flag essentially prevents the callbacks set via USBH_CDC_SetOnIntStateChange() and USBH_CDC_SetOnSerialStateChange() from ever executing. USBH_CDC_DISABLE_INTERFACE_CHECK: According to the CDC specification CDC devices must contain two interfaces, the first being the control interface, containing an interrupt IN endpoint, the second being a data interface containing a bulk IN and a bulk OUT endpoint. Some manufacturers sometimes decide to put all 3 endpoints into one interface, despite the device otherwise being compatible to the CDC specification. This flag allows such devices to be added to the CDC module.
USBH_CDC_SuspendResume()
Description
Prepares a CDC device for suspend (stops the interrupt endpoint)
or re-starts the interrupt endpoint functionality after a resume.
USBH_STATUS_SUCCESS on success or error code on failure.
Additional information
The application must make sure that no transactions are running
when setting a device into suspend mode.
This function is used in combination with USBH_SetRootPortPower().
To suspend:
Call this function before USBH_SetRootPortPower(x, y, USBH_SUSPEND) with State = 0.
To resume:
Call this function after USBH_SetRootPortPower(x, y, USBH_NORMAL_POWER) with State = 1.
USBH_CDC_GetInterfaceHandle()
Description
Return the handle to the (open) USB interface. Can be used to
call USBH core functions like USBH_GetStringDescriptor().
State of receiver carrier detection mechanism of device. This signal corresponds to V.24 signal 109 and RS-232 signal DCD.
bTxCarrier
State of transmission carrier. This signal corresponds to V.24 signal 106 and RS-232 signal DSR.
bBreak
State of break detection mechanism of the device.
bRingSignal
State of ring signal detection of the device.
bFraming
A framing error has occurred.
bParity
A parity error has occurred.
bOverRun
Received data has been discarded due to overrun in the device.
USBH_CDC_RW_CONTEXT
Description
Contains information about a completed, asynchronous transfers.
Is passed to the USBH_CDC_ON_COMPLETE_FUNC user
callback when using asynchronous write and read.
When this structure is passed to USBH_CDC_ReadAsync() or USBH_CDC_WriteAsync()
its member need not to be initialized.
Pointer to a structure of type USBH_CDC_SERIALSTATE showing the serial status from the device.
FT232 Device Driver (Add-On)
This chapter describes the optional emUSB-Host add-on “FT232 device driver”.
It allows communication with an FTDI FT232 USB device, typically serving as
USB to RS232 converter.
Introduction
The FT232 driver software component of emUSB-Host allows the communication with
FTDI FT232 devices. It implements the FT232 protocol specified by FTDI which is a
vendor specific protocol. The protocol allows emulation of serial communication via
USB.
This chapter provides an explanation of the functions available to application developers via the FT232 driver software. All the functions and data types of this add-on
are prefixed with the “USBH_FT232_” text.
Features
The following features are provided:
Compatibility with different FT232 devices.
Ability to send and receive data.
Ability to set various parameters, such as baudrate, number of stop bits, parity.
Handling of multiple FT232 devices at the same time.
Notifications about FT232 connection status.
Ability to query the FT232 line and modem status.
Example code
An example application which uses the API is provided in the USBH_FT232_Start.c file.
This example displays information about the FT232 device in the I/O terminal of the
debugger. In addition the application then starts a simple echo server, sending back
the received data.
Compatibility
The following devices work with the current FT232 driver:
FT8U232AM
FT232B
FT232R
FT2232D
Further reading
For more information about the FTDI FT232 devices, please take a look at the hardware manual and D2XX Programmer’s Guide manual (Document Reference No.: FT_000071) available from www.ftdichip.com.
API Functions
This chapter describes the emUSB-Host FT232 driver API functions.
This function is deprecated, please use function USBH_FT232_AddNotification! Sets a callback in order to be notified when a device is added or removed.
Before this function is called any notifications added via
USBH_FT232_AddNotification() must be removed
via USBH_FT232_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_FT232_Exit(). The
only exception is USBH_FT232_Init(), which would in turn
reinitialize the module and allows further calls.
USBH_FT232_AddNotification()
Description
Adds a callback in order to be notified when a device is added or removed.
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.
Example
staticUSBH_NOTIFICATION_HOOK_Hook;/*********************************************************************** _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*/staticvoid_cbOnAddRemoveDevice(void*pContext,U8 DevIndex,USBH_DEVICE_EVENTEvent){(void)pContext;switch(Event){caseUSBH_DEVICE_EVENT_ADD:USBH_Logf_Application("**** Device added\n");_DevIndex =DevIndex;_DevIsReady =1;break;caseUSBH_DEVICE_EVENT_REMOVE:USBH_Logf_Application("**** Device removed\n");_DevIsReady =0;_DevIndex =-1;break;default:;// Should never happen}}<...>USBH_FT232_Init();USBH_FT232_AddNotification(&_Hook,_cbOnAddRemoveDevice,NULL);<...>
USBH_FT232_RemoveNotification()
Description
Removes a callback added via USBH_FT232_AddNotification.
USBH_STATUS_SUCCESS on success or error code on failure.
USBH_FT232_RegisterNotification()
Description
This function is deprecated, please use function USBH_FT232_AddNotification!
Sets a callback in order to be notified when a device is added or removed.
out Pointer to a variable which receives the number of bytes read from the device.
Return value
= USBH_STATUS_SUCCESS
Successful.
≠ USBH_STATUS_SUCCESS
An error occurred.
Additional information
USBH_FT232_Read() always returns the number of bytes read in
pNumBytesRead. This function does not return until NumBytes bytes
have been read into the buffer unless short read mode is enabled.
This allows USBH_FT232_Read() to return when either data have been
read from the queue or as soon as some data have been read from
the device. The number of bytes in the receive queue can be
determined by calling USBH_FT232_GetQueueStatus(), and passed to
USBH_FT232_Read() as NumBytes so that the function reads the data
and returns immediately. When a read timeout value has been
specified in a previous call to USBH_FT232_SetTimeouts(),
USBH_FT232_Read() returns when the timer expires or NumBytes have
been read, whichever occurs first. If the timeout occurs,
USBH_FT232_Read() reads available data into the buffer and
returns USBH_STATUS_TIMEOUT. An application should use
the function return value and pNumBytesRead when processing
the buffer. If the return value is USBH_STATUS_SUCCESS, and
pNumBytesRead is equal to NumBytes then USBH_FT232_Read has
completed normally. If the return value is USBH_STATUS_TIMEOUT,
pNumBytesRead may be less or even 0, in any case, pData will be
filled with pNumBytesRead. Any other return value suggests an
error in the parameters of the function, or a fatal error like a
USB disconnect.
Define whether short read mode shall be used or not. 1 - Allow short read. 0 - Short read mode disabled.
Return value
= USBH_STATUS_SUCCESS
Successful.
≠ USBH_STATUS_SUCCESS
An error occurred.
Additional information
USBH_FT232_AllowShortRead() sets the USBH_FT232_Read() into
a special mode - short read mode. When this mode is enabled,
the function returns as soon as any data has been read from
the device. This allows the application to read data where
the number of bytes to read is undefined. To disable this mode,
AllowShortRead should be set to 0.
Number of bits per word. Must be either USBH_FT232_BITS_8 or USBH_FT232_BITS_7.
StopBits
Number of stop bits. Must be USBH_FT232_STOP_BITS_1 or USBH_FT232_STOP_BITS_2.
Parity
Parity - must be one of the following values: USBH_FT232_PARITY_NONEUSBH_FT232_PARITY_ODDUSBH_FT232_PARITY_EVENUSBH_FT232_PARITY_MARKUSBH_FT232_PARITY_SPACE
Return value
= USBH_STATUS_SUCCESS
Successful.
≠ USBH_STATUS_SUCCESS
An error occurred.
USBH_FT232_SetFlowControl()
Description
This function sets the flow control for the device.
Pointer to a variable of type U32 which receives the modem status and line status from the device.
Return value
= USBH_STATUS_SUCCESS
Successful.
≠ USBH_STATUS_SUCCESS
An error occurred.
Additional information
The least significant byte of the pModemStatus value holds the modem status.
The line status is held in the second least significant byte of the pModemStatus value.
The modem status is bit-mapped as follows:
The latency timer controls the timeout for the FTDI device to transfer
data from the FT232 interface to the USB interface.
The FTDI device transfers data from the FT232 to the USB interface
when it receives 62 bytes over FT232 (one full packet with 2 status bytes)
or when the latency timeout elapses.
Required value, in milliseconds, of latency timer. Valid range is 2 - 255.
Return value
= USBH_STATUS_SUCCESS
Successful.
≠ USBH_STATUS_SUCCESS
An error occurred.
Additional information
In the FT8U232AM and FT8U245AM devices, the receive buffer timeout
that is used to flush remaining data from the receive buffer was
fixed at 16 ms. Therefore this function cannot be used with these
devices. In all other FTDI devices, this timeout is programmable
and can be set at 1 ms intervals between 2ms and 255 ms.
This allows the device to be better optimized for protocols
requiring faster response times from short data packets.
Required value for bit mode mask. This sets up which bits are inputs and outputs. A bit value of 0 sets the corresponding pin to an input. A bit value of 1 sets the corresponding pin to an output. In the case of CBUS Bit Bang, the upper nibble of this value controls which pins are inputs and outputs, while the lower nibble controls which of the outputs are high and low.
Enable
Mode value. Can be one of the following values: 0x00 = Reset 0x01 = Asynchronous Bit Bang 0x02 = MPSSE (FT2232, FT2232H, FT4232H and FT232H devices only) 0x04 = Synchronous Bit Bang (FT232R, FT245R, FT2232, FT2232H, FT4232H and FT232H devices only) 0x08 = MCU Host Bus Emulation Mode (FT2232, FT2232H, FT4232H and FT232H devices only) 0x10 = Fast Opto-Isolated Serial Mode (FT2232, FT2232H, FT4232H and FT232H devices only) 0x20 = CBUS Bit Bang Mode (FT232R and FT232H devices only) 0x40 = Single Channel Synchronous 245 FIFO Mode (FT2232H and FT232H devices only).
Return value
= USBH_STATUS_SUCCESS
Successful.
≠ USBH_STATUS_SUCCESS
An error occurred.
Additional information
For further information please refer to the HW-reference manuals
and application note on the FTDI website.
USBH_FT232_GetBitMode()
Description
Returns the current values on the data bus pins.
This function does NOT return the configured mode.
This chapter describes the optional emUSB-Host add-on “FT260 device driver”.
It allows communication with an FTDI FT260 USB device, typically serving as
USB to I2C converter.
Introduction
The FT260 driver software component of emUSB-Host allows the communication with
FTDI FT260 devices. It implements on HID based protocol specified by FTDI.
The protocol allows use the FT260 as I2C master to communicate with
different I2C slave devices. UART communication is also available.
This chapter provides an explanation of the functions available to application developers via the FT260 driver software. All the functions and data types of this add-on
are prefixed with the “USBH_FT260_” text.
Features
The following features are provided:
Compatibility with different FT260 devices.
Ability to use I2C or UART operation.
Ability to set up speed for the I2C bus.
Ability to set various parameters, such as baudrate, number of stop bits, parity for UART.
Handling of multiple FT260 devices at the same time.
Ability to query the FT260 UART line and modem status.
Example code
An example application which uses the API is provided in the USBH_FT260_Start.c file.
This example displays the dump of the EEPROM that is available on device address 0x50 on the UMFT260EV1A board.
Compatibility
The following devices work with the current FT260 driver:
FT260Q
FT260S
Further reading
For more information about the FTDI FT260 devices, please take a look at the hardware manual and AN_394 User Guide for FT260 (Document Reference No.: FT_001279) available from www.ftdichip.com.
API Functions
This chapter describes the emUSB-Host FT260 driver API functions.
staticUSBH_NOTIFICATION_HOOK_Hook;/*********************************************************************** _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*/staticvoid_cbOnAddRemoveDevice(void*pContext,U8 DevIndex,USBH_DEVICE_EVENTEvent){(void)pContext;switch(Event){caseUSBH_DEVICE_EVENT_ADD:USBH_Logf_Application("**** Device added\n");_DevIndex =DevIndex;_DevIsReady =1;break;caseUSBH_DEVICE_EVENT_REMOVE:USBH_Logf_Application("**** Device removed\n");_DevIsReady =0;_DevIndex =-1;break;default:;// Should never happen}}<...>USBH_FT260_Init();USBH_FT260_AddNotification(&_Hook,_cbOnAddRemoveDevice,NULL);<...>
USBH_FT260_RemoveNotification()
Description
Removes a callback added via USBH_HID_FT260_AddNotification.
Pointer to a U8 Variable to store the I2C status: : The status can be an or combination of the following: USBH_FT260_I2CM_STATUS_CONTROLLER_BUSY - Controller busy: all other status bits invalid USBH_FT260_I2CM_STATUS_ERROR_CONDITION - Error condition USBH_FT260_I2CM_STATUS_SLAVE_NACK - Slave address was not acknowledged during last operation USBH_FT260_I2CM_STATUS_DATA_NACK - Data not acknowledged during last operation USBH_FT260_I2CM_STATUS_ARBITRATION_LOST - Arbitration lost during last operation USBH_FT260_I2CM_STATUS_CONTROLLER_IDLE - Controller idle USBH_FT260_I2CM_STATUS_BUS_BUSY - Bus busy
The following flow controls are available: USBH_FT260_UART_OFF - Disables the UART module. USBH_FT260_UART_RTS_CTS_MODE - Use hardware flow control RTS, CTS mode. USBH_FT260_UART_DTR_DSR_MODE - Use hardware flow control DTR, DSR mode. USBH_FT260_UART_XON_XOFF_MODE, - Use software flow control mode. USBH_FT260_UART_NO_FLOW_CTRL_MODE - Do not use any flow control mode.
Return value
= USBH_STATUS_SUCCESS
Operation was successful.
≠ USBH_STATUS_SUCCESS
Operation was not successful.
USBH_FT260_UART_SetDataCharacteristics()
Description
Setups the UART based on the given data characteristics.
The following data bits are available: USBH_FT260_DATA_BIT_7 - Use 7 bit mode. USBH_FT260_DATA_BIT_8 - use 8 bit mode.
StopBits
The desired stop bits can be the following: USBH_FT260_STOP_BITS_1 - Use one stop bit. USBH_FT260_STOP_BITS_2 - Use two stop bits.
Parity
The following parity options are available: USBH_FT260_PARITY_NONE - Use no parity. USBH_FT260_PARITY_ODD, - Use odd parity. USBH_FT260_PARITY_EVEN - Use even parity. USBH_FT260_PARITY_MARK - Use mark parity. USBH_FT260_PARITY_SPACE - Use space parity.
This structure is used to retrieve or to set the status of the various GPIO pins of the FT260 chip.
USBH_FT260_VID_PID_PAIR
Description
This structure is used to add a FT260 device that has a
different Vendor and Product Id stored in EEPROM.
Only the VendorId and ProductId members needs to be filled.
Anything else is handled by the FT260 module.
Note: Do not modify these values after the
USBH_FT260_AddSupportedItem() was called.
Specifies the set flow mode control. The following modes are available: 0x00 : OFF, and switch UART pins to GPIO 0x01 : RTS_CTS mode(GPIOB = > RTSN, GPIOE = > CTSN) 0x02 : DTR_DSR mode(GPIOF = > DTRN, GPIOH = > DSRN) 0x03 : XON_XOFF(software flow control) 0x04 : No flow control mode
BaudRate
UART baud rate The FT260 supports baud rate range from 1200 to 12M.
DataBit
The current data bit mode: 0x07: 7 data bits 0x08: 8 data bits
Parity
The parity that is used by the UART module: 0x00: No parity 0x01: Odd parity. This means that the parity bit is set to either ’1’ or ’0’ so that an odd number of 1’s are sent. 0x02: Even parity.This means that the parity bit is set to either ’1’ or ’0’ so that an even number of 1’s are sent. 0x03: Mark parity.This simply means that the parity bit is always High. 0x04: Space parity.This simply means that the parity bit is always Low.
StopBit
The number of stop bits that are used: 0x00: one stop bit 0x02: two stop bits
Breaking
When active the TXD line goes into “spacing” state which causes a break in the receiving UART. 0x00 : no break 0x02 : break
USBH_FT260_GPIO_REPORT
Description
This structure is used to retrieve or to set the status of the
various GPIO pins of the FT260 chip.
Please refer to the data sheet of the FT260 to check the GPIO capability.
GPIO[0..5] Pin direction whereas: 1 : Output 0 : Input
GpioN_Value
GPIO[A..H] Pin state
GpioN_Dir
GPIO[A..H] Pin direction whereas: 1 : Output 0 : Input
BULK Device Driver (Add-On)
This chapter describes the optional emUSB-Host add-on “BULK device driver”.
It allows communication with a vendor specific USB devices.
Introduction
The BULK driver software component of emUSB-Host allows communication with vendor specific
devices using an arbitrary number of bulk or interrupt endpoints.
This chapter provides an explanation of the functions available to application developers
via the BULK driver software. All the functions and data types of this add-on are
prefixed with ’USBH_BULK_’.
Overview
A BULK device connected to the emUSB-Host is automatically configured and added to
an internal list. If the BULK driver has been registered, it is notified via a callback
when a BULK device has been added or removed. The driver then can notify the application
program, when a callback function has been registered via
USBH_BULK_RegisterNotification(). In order to communicate with such a device,
the application has to call the USBH_BULK_Open(), passing the device index. BULK
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:
Ability to send and receive data.
Handling of multiple BULK devices at the same time.
Notifications about BULK connection status.
Handling for an arbitrary number of endpoints.
Example code
An example application which uses the API is provided in the USBH_BULK_Start.c file.
This example demonstrates simple communication between the host and a Bulk device.
To run this sample a device programmed with the emUSB-Device sample USB_BULK_Test.c is required.
The sample demonstrates how to extract the endpoint addresses, which are required by the emUSB-Host BULK API.
The sample will send and receive data starting with 1 byte, after each successful echo the number of bytes is increased, up to 1024.
API Functions
This chapter describes the emUSB-Host BULK driver API functions.
These functions are defined in the header file USBH_BULK.h.
Deprecated parameter. Please use USBH_BULK_AddNotification to add new interfaces masks. To be backward compatible the mask added through this parameter will be automatically added when USBH_BULK_RegisterNotification is called.
Return value
USBH_STATUS_SUCCESS
Success or module already initialized.
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_BULK_Exit has to be called
the same number of times as this function was called.
USBH_BULK_Exit()
Description
Unregisters and de-initializes the BULK device module from emUSB-Host.
Before this function is called any notifications added via
USBH_BULK_AddNotification() must be removed
via USBH_BULK_RemoveNotification().
Has to be called the same number of times USBH_BULK_Init was
called in order to de-initialize the module.
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_BULK_Exit(). The only exception is USBH_BULK_Init(),
which would in turn re-init the module and allow further calls.
USBH_BULK_RegisterNotification()
Description
(Deprecated) Sets a callback in order to be notified when a device is added or removed.
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.
pInterfaceMask
Pointer to a structure of type USBH_INTERFACE_MASK. NULL means that all interfaces will be forwarded to the callback.
Return value
USBH_STATUS_SUCCESS on success or error code on failure.
Example
staticUSBH_NOTIFICATION_HOOK_Hook;/*********************************************************************** _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*/staticvoid_cbOnAddRemoveDevice(void*pContext,U8 DevIndex,USBH_DEVICE_EVENTEvent){(void)pContext;switch(Event){caseUSBH_DEVICE_EVENT_ADD:USBH_Logf_Application("**** Device added\n");_DevIndex =DevIndex;_DevIsReady =1;break;caseUSBH_DEVICE_EVENT_REMOVE:USBH_Logf_Application("**** Device removed\n");_DevIsReady =0;_DevIndex =-1;break;default:;// Should never happen}}<...>USBH_BULK_Init();USBH_BULK_AddNotification(&_Hook,_cbOnAddRemoveDevice,NULL);<...>
USBH_BULK_RegisterNotification()
Description
(Deprecated) Sets a callback in order to be notified when a device is added or removed.
USBH_STATUS_SUCCESS on success or error code on failure.
USBH_BULK_AllowShortRead()
Description
Enables or disables short read mode.
If enabled, the function USBH_BULK_Read() returns as soon as data was
read from the device. This allows the application to read data where the number of
bytes to read is undefined.
Pointer to a USBH_BULK_EP_INFO structure that receives the information.
Return value
USBH_STATUS_SUCCESS on success or error code on failure.
USBH_BULK_Read()
Description
Reads from the BULK device. Depending of the ShortRead mode (see USBH_BULK_AllowShortRead()),
this function will either return as soon as data is available or
all data have been read from the device.
This function will also return when a set timeout is expired,
whatever comes first.
The USB stack can only read complete packets from the USB device.
If the size of a received packet exceeds NumBytes then all data that does not
fit into the callers buffer (pData) is stored in an internal buffer and
will be returned by the next call to USBH_BULK_Read(). See also USBH_BULK_GetNumBytesInBuffer().
To read a null packet, set pData = NULL and NumBytes = 0.
For this, the internal buffer must be empty.
Pointer to a variable which receives the number of bytes read from 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 read part of the data. The number of bytes read successfully is always
stored in the variable pointed to by pNumBytesRead.
USBH_BULK_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 endpoint referenced.
The maximum packet size of the endpoint can be retrieved using USBH_BULK_GetEndpointInfo().
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_BULK_GetMaxTransferSize()
Description
Return the maximum transfer size allowed for the USBH_BULK_*Async functions.
Pointer to a variable which will receive the maximum transfer size for the specified endpoint.
Return value
USBH_STATUS_SUCCESS on success or error code on failure.
Additional information
Using this function is only necessary with the USBH_BULK_*Async functions,
other functions handle the limits internally.
These limits exist because certain USB controllers have hardware limitations.
Some USB controllers (OHCI, EHCI, …) do not have these limitations, therefore 0xFFFFFFFF will be returned.
USBH_BULK_ReadAsync()
Description
Triggers a read transfer to the BULK device. The result of
the transfer is received through the user callback.
This function will return immediately while the read transfer is
done asynchronously.
Pointer to the buffer that receives the data from the device. Ignored for ISO transfers.
BufferSize
Size of the buffer in bytes. Must be a multiple of of the maximum packet size of the USB device. Use USBH_BULK_GetMaxTransferSize() to get the maximum allowed size. Ignored for ISO transfers.
pfOnComplete
Pointer to a user function of type USBH_BULK_ON_COMPLETE_FUNC which will be called after the transfer has been completed.
pRWContext
Pointer to a USBH_BULK_RW_CONTEXT structure which will be filled with data after the transfer has been completed and passed as a parameter to the pfOnComplete function. The member ’pUserContext’ may be set before calling USBH_BULK_ReadAsync(). Other members need not be initialized and are set by the function USBH_BULK_ReadAsync(). The memory used for this structure must be valid, until the transaction is completed.
Return value
= USBH_STATUS_PENDING
Success, the data transfer is queued, the user callback will be called after the transfer is finished.
≠ USBH_STATUS_PENDING
An error occurred, the transfer is not started and user callback will not be called.
Triggers a write transfer to the BULK device. The result of
the transfer is received through the user callback.
This function will return immediately while the write transfer is
done asynchronously.
Pointer to a buffer which holds the data. Ignored for ISO transfers.
BufferSize
Number of bytes to write. Use USBH_BULK_GetMaxTransferSize() to get the maximum allowed size. Ignored for ISO transfers.
pfOnComplete
Pointer to a user function of type USBH_BULK_ON_COMPLETE_FUNC which will be called after the transfer has been completed.
pRWContext
Pointer to a USBH_BULK_RW_CONTEXT structure which will be filled with data after the transfer has been completed and passed as a parameter to the pfOnComplete function. pfOnComplete function. The member ’pUserContext’ may be set before calling USBH_BULK_WriteAsync(). Other members need not be initialized and are set by the function USBH_BULK_WriteAsync(). The memory used for this structure must be valid, until the transaction is completed.
Return value
= USBH_STATUS_PENDING
Success, the data transfer is queued, the user callback will be called after the transfer is finished.
≠ USBH_STATUS_PENDING
An error occurred, the transfer is not started and user callback will not be called.
Example
staticUSBH_BULK_RW_CONTEXT_ReadWriteContext;<...>/*********************************************************************** _OnWriteComplete*/staticvoid_OnWriteComplete(USBH_BULK_RW_CONTEXT*pRWContext){if(pRWContext->Status ==USBH_STATUS_SUCCESS){printf("Successfully written data to the device \n");}else{printf("WriteAsync callback returned %s \n",USBH_GetStatusStr(pRWContext->Status));// Error handling}<...>}<...>Status =USBH_BULK_WriteAsync(_hDevice,EPAddr,_acBuffer,NumBytes,_OnWriteComplete,&_ReadWriteContext);if(Status !=USBH_STATUS_PENDING){// Error handling.}<...>
The USB stack can only read complete packets from the USB device.
If the size of a received packet exceeds the number of bytes requested
with USBH_BULK_Read(), than all data that is not returned by USBH_BULK_Read()
is stored in an internal buffer.
Pointer to a variable which receives the number of bytes in the receive buffer.
Return value
USBH_STATUS_SUCCESS on success or error code on failure.
Example
//// Read only ONE byte to trigger the read transfer.// This means that the remaining bytes are in the internal packet buffer!//USBH_BULK_Read(hDevice,EPAddr,acData,1,&NumBytes,Timeout);if(NumBytes){//// We do not know how big the packet was which we received from the device,// since we only read 1 byte from the packet.// Therefore we still might have some data in the internal buffer!// Using USBH_BULK_GetNumBytesInBuffer we can check how many bytes are still in the// internal buffer (if any) and read those as well.//if(USBH_BULK_GetNumBytesInBuffer(hDevice,EPAddr,&RxBytes)==USBH_STATUS_SUCCESS){//// Read the remaining bytes.//if(RxBytes >0){USBH_BULK_Read(hDevice,EPAddr,&acData[1],RxBytes,&NumBytes,Timeout);}}}
USBH_BULK_SetupRequest()
Description
Sends a specific request (class vendor etc) to the device.
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.
wIndex
wIndex in the setup request.
pData
Additional data for the setup request.
pNumBytesData
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 on success or error code on failure.
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_BULK_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_BULK_WriteAsync(), 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.
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.
InterfaceID
Interface ID of the device.
USBH_BULK_EP_INFO
Description
Structure containing information about an endpoint.
Contains information about a completed, asynchronous transfers.
Is passed to the USBH_BULK_ON_COMPLETE_FUNC user
callback when using asynchronous write and read.
When this structure is passed to USBH_BULK_ReadAsync() or USBH_BULK_WriteAsync()
its member need not to be initialized.
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.
Type definitions
This chapter describes the types defined in the header file USBH_BULK.h.
This chapter describes the optional emUSB-Host add-on “LAN”.
It allows interfacing Ethernet-over-USB adapters with embOS/IP.
Introduction
The LAN software component of emUSB-Host allows communication with Ethernet-over-USB adapters.
These devices usually implement the CDC-ECM, RNDIS protocol or a proprietary protocol from the company ASIX.
All above protocols allow the transfer of Ethernet packets over USB. emUSB-Host LAN provides a seamless interface
with embOS/IP irrespective of the underlying USB protocol thereby allowing devices without Ethernet connectors to connect with a network.
This chapter provides an explanation of the LAN software component functions available to application developers.
All the functions and data types of this add-on are prefixed with ’USBH_LAN_’.
Overview
embOS/IP adds Ethernet interfaces for as many Ethernet-over-USB adapters as are expected to be used with the product. The interfaces are initially “down”.
emUSB-Host LAN accommodates multiple underlying classes to support different adapters. Each registered LAN driver notifies
the main LAN module when a device matching the LAN driver’s supported class (ASIX, RNDIS or CDC-ECM) has enumerated.
The LAN module in turn notifies the IP stack that an interface is “up” and communication begins.
emUSB-Host LAN is supported with version 3.30 of embOS/IP and higher.
Features
The following features are provided:
Compatibility with different Ethernet-over-USB adapters.
Integration with embOS/IP
Example code
Any embOS/IP example can be used.
IP_Config_USBH_LAN.c in detail
The embOS/IP configuration file IP_Config_USBH_LAN.c is a sample configuration for using emUSB-Host LAN as an interface with embOS/IP.
The function IP_X_Config is the main configuration function of the embOS/IP stack.
In this sample the NUM_INSTANCES define (4 by default) is used to determine how many interfaces are registered.
Each embOS/IP interface corresponds to one Ethernet-over-USB adapter on the emUSB-Host LAN side.
This means that in the default configuration 4 adapters can be used simultaneously (e.g. 4x CDC-ECM adapter or 2x ASIX, 1x CDC-ECM and 1x RNDIS or any other combination of the supported protocols).
The sample configuration initializes emUSB-Host and the emUSB-Host LAN component in the same function.
This is for convenience only, you can initialize emUSB-Host anywhere inside your application.
The initialization starts the stack and the LAN module allowing the Ethernet-over-USB adapters to enumerate.
Pointer to an LAN driver structure of type USBH_LAN_DRIVER. Currently the following drivers are available: USBH_LAN_DRIVER_ASIXUSBH_LAN_DRIVER_ECMUSBH_LAN_DRIVER_RNDIS
This chapter describes the optional emUSB-Host add-on “CCID device driver”.
It allows communication with a smart card reader.
Introduction
The CCID driver software component of emUSB-Host allows communication with CCID compatible
smart card readers. The Communication Device Class (CCID) is an abstract USB class protocol
defined by the USB Implementers Forum.
This chapter provides an explanation of the functions available to application developers
via the CCID driver software. All the functions and data types of this add-on are
prefixed with ’USBH_CCID_’.
Overview
A CCID device connected to the emUSB-Host is automatically configured and added to
an internal list. If the CCID driver has been registered, it is notified via a callback
when a CCID device has been added or removed. The driver then can notify the application
program, when a callback function has been registered via
USBH_CCID_AddNotification(). In order to communicate with such a device,
the application has to call the USBH_CCID_Open(), passing the device index. CCID
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 CCID devices.
Handling of multiple CCID devices at the same time.
Handling of CCID devices with multiple card slots.
Ability to send commands to a smart card and receive the response.
Ability to query the slot status.
Notifications about insertion and removal of smart cards.
Example code
An example application which uses the API is provided in the USBH_CCID_Start.c file.
This example waits for a smart card to be inserted and displays the serial number of the smart card in the I/O terminal of the
debugger (if it supports a serial number).
API Functions
This chapter describes the emUSB-Host CCID driver API functions.
These functions are defined in the header file USBH_CCID.h.
Has to be called the same number of times USBH_CCID_Init was
called in order to de-initialize the module.
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_CCID_Exit(). The only exception is USBH_CCID_Init(),
which would in turn re-init the module and allow further calls.
USBH_CCID_AddNotification()
Description
Adds a callback in order to be notified when a device is added or removed.
Sets the callback to retrieve slot change events
from the interrupt endpoint. If the device does not have an
interrupt endpoint, this function returns an error code.
Pointer to a buffer where the descriptor will be stored.
pNumBytesData
in Size of the buffer. out Upon successful completion this variable will contain the number of bytes copied, which is either the size of the descriptor or the size of the buffer if the descriptor was longer than the given buffer.
Return value
USBH_STATUS_SUCCESS on success or error code on failure.
USBH_CCID_Cmd()
Description
Sends a command to the CCID device and receives the response.
Pointer to variable that receives the slot status: 0 - smart card present and ready 1 - smart card present but inactive 2 - no smart card present other - device error
Return value
USBH_STATUS_SUCCESS on success or error code on failure.
in Size of buffer for response data (may be 0 to discard the response data). out Length of response data received from the smart card.
pResp
Pointer to the buffer that received the response data. Response data is stored by the function only, when it returns either USBH_STATUS_SUCCESS or USBH_STATUS_DEVICE_ERROR.
Return value
USBH_STATUS_SUCCESS on success or error code on failure.
Additional information
The response data of the card is truncated to a maximum of *pRespLen bytes.
If *pRespLen = 0 when calling the function, then all response data are discarded.
USBH_CCID_GetResponse()
Description
Get response data of a previous APDU command.
Is needed, after the the card has returned status code (SW1 SW2) = 61xx.
in Size of buffer for response data. out Length of response data received from the smart card.
pResp
Pointer to the buffer that received the response data. Response data is stored by the function only, when it returns either USBH_STATUS_SUCCESS or USBH_STATUS_DEVICE_ERROR.
Return value
USBH_STATUS_SUCCESS on success or error code on failure.
Additional information
The response data of the card is truncated to a maximum of *pRespLen bytes.
If *pRespLen = 0 when calling the function, then all response data are discarded.
USBH_STATUS_SUCCESS on success or error code on failure.
USBH_CCID_Abort()
Description
Stop any current transfer at the slot and return to a state where
the slot is ready to accept a new command. This function should also
be called after serious errors from any of the USB_CCID…() functions,
the restore the synchronization between the host and the card reader.
Bit mask of slot states. Bit n indicates state of slot n (n = 0 … NumSlots-1). If a smart card is present in the slot, the respective bit has a value of 1.
MIDI Device Driver (Add-On)
This chapter describes the optional emUSB-Host add-on “MIDI device driver”.
It allows communication with MIDI devices over USB.
Introduction
The MIDI driver software component of emUSB-Host allows communication with MIDI-compatible
devices. The MIDI Device Class (MIDI) is an abstract USB class protocol
defined by the USB Implementers Forum.
This chapter provides an explanation of the functions available to application developers
via the MIDI driver software. All the functions and data types of this add-on are
prefixed with ’USBH_MIDI_’.
Overview
A MIDI device connected to the emUSB-Host is automatically configured and added to
an internal list. If the MIDI driver has been registered, it is notified via a callback
when a MIDI device has been added or removed. The driver then can notify the application
program, when a callback function has been registered via
USBH_MIDI_AddNotification(). In order to communicate with such a device,
the application must call USBH_MIDI_Open(), passing the device index. MIDI
devices are identified by an index: the first connected device is assigned the index
0, the second index 1, and so on.
Features
The following features are provided:
Compatibility with different MIDI devices.
Handling of multiple MIDI devices at the same time (e.g. drum machine and synthesizer).
Handling of MIDI devices with multiple cables (e.g. USB to MIDI converters).
Ability to send MIDI commands to a device and receive MIDI commands from a device.
Notifications about insertion and removal of MIDI devices.
Example code
Example applications that demonstrate the capabilities of the USB host controlling MIDI devices
and processing events from MIDI devices.
The following examples are provided in the Application directory.
File name
Description
USBH_MIDI_Start.c
Runs on all boards. Displays USB MIDI events
received from any virtual cable from any USB
MIDI device.
USBH_MIDI_GUI_Keyboard.c
Configured to run on an STM32F746G-Discovery board.
Displays a virtual piano keyboard on the LCD and
reflects MIDI keyboard state (through Note On and
Note Off MIDI events) on the virtual keyboard.
Pressing the keys on the virtual keyboard sends
Note On an Note Off events to all attached MIDI
devices, so playing a connected synthesizer from
the virtual display is possible.
USBH_MIDI_HID_Keyboard.c
Will run on any board that supports two USB devices
simultaneously (e.g. single root hub plus external
hub, or a microcontroller with two root hubs).
Plugging in a MIDI device and a standard HID-compliant
USB keyboard enables control of the MIDI device from
a readily-available accessory. Each HID Key Down
and Key Up event is translated to an appropriate
MIDI Note On and Note Off event. The USB keyboard
can change the MIDI send channel to 1 through 12
using F1 to F12.
USBH_MIDI_HID_ScrollMessage.c
Will run on any board that supports two USB devices.
Scrolls a message across a Novation Launchpad Mini
MK2 under control of a Griffin Powermate, a HID device
that is a rotary encoder.
USBH_MIDI_GUI_PlayMIDI.c
Configured to run on an STM32F746G-Discovery board.
This example demonstrates integrating the emUSB-Host
MIDI class driver with the SEGGER emLib-MIDI library
in order to play Standard MIDI Files.
USBH_MIDI_Sequencer.c
Runs on all boards. With a Novation Launchpad Mini MK2
you can turn your embedded host into a pattern
sequencer or groovebox. Works especially well with
the emPower USB Host board.
USBH_MIDI_Message.c
Runs on all boards. Uses the Novation Launchpad Mini
MK2 as a display to scroll a message. Works especially
well with the emPower USB Host board.
USBH_MIDI_Reversi.c
Runs on all boards. This is a non-musical application
of a MIDI controller. With a Novation Launchpad Mini MK2
you can play Reversi against the computer. Works
especially well with the emPower USB Host board.
API Functions
This section describes the emUSB-Host MIDI driver API functions.
These functions are defined in the header file USBH_MIDI.h.
This function will release resources that were used by this device
driver. It must be called if the application is closed and must
to be called before USBH_Exit(). No more functions of this module
may be called after calling USBH_MIDI_Exit(). The
only exception is USBH_MIDI_Init(), which would in turn
reinitialize the module and allows further calls.
Pointer to buffer memory to use (minimum four bytes).
BufferLen
Size of buffer memory in bytes (minimum four bytes, and must also be a multiple of four).
Return value
= USBH_STATUS_SUCCESS
Success.
≠ USBH_STATUS_SUCCESS
Error indication.
Additional information
It is not necessary to set a buffer for a device, although
doing so will improve throughput. By default, all MIDI
events written by USBH_MIDI_WrEvent() will be sent immediately
as a four-byte USB transaction.
The buffer should ideally be a multiple of the MIDI event
size, which is four bytes, and of the USB endpoint’s
maximum packet size. Usually a buffer size of 64 bytes
is recommended, it will hold 16 MIDI events and nicely
matches the typical bulk endpoint size of 64 bytes.
USBH_MIDI_SetTimeouts()
Description
Sets up the timeouts the host waits until the
data transfer will be aborted for a specific MIDI device.
This function always reads exactly zero or one events. If there
is an error or a timeout, that status is returned by the function.
If an event is correctly received, the event is written to the
object pointed to by pEvent and the function returns zero.
The USB-MIDI event that is sent as CC SS XX YY in transmission
order is returned as a 32-bit value where CC is encoded in bits
31…24, SS in bits 23…16, XX in bits 15…8, and YY in bits
7…0.
Octet length of the object to write. Must be a multiple of four.
pWrDataLen
Pointer to the object that receives the number of bytes written. Can be null.
Return value
= USBH_STATUS_SUCCESS
Success.
≠ USBH_STATUS_SUCCESS
Error indication.
Additional information
By default the MIDI data is written to the device immediately
and is not buffered. If a buffer has been set using
USBH_MIDI_SetBuffer(), the data may be buffered internally.
Any buffered data can be sent to the device using USBH_MIDI_Send().
By default the MIDI event is written to the device immediately
and is not buffered. If a buffer has been set using
USBH_MIDI_SetBuffer(), the event is written to the buffer and,
when the buffer is full, all buffered MIDI events are sent. Any
buffered data can be sent to the device using USBH_MIDI_Send().
The USB-MIDI event that is sent as CC SS XX YY in transmission
order is encoded in Event as a 32-bit value where CC is encoded
in bits 31…24, SS in bits 23…16, XX in bits 15…8, and YY
in bits 7…0.
This chapter describes the optional emUSB-Host add-on “AUDIO device driver”.
It allows communication with USB audio devices.
Introduction
The AUDIO driver software component of emUSB-Host allows communication with USB Audio V1 compatible
devices like speakers or microphones.
This chapter provides an explanation of the functions available to application developers
via the AUDIO driver software. All the functions and data types of this add-on are
prefixed with ’USBH_AUDIO_’.
Overview
An audio device connected to the emUSB-Host is automatically configured and added to
an internal list. If the AUDIO driver has been registered, it is notified via a callback
when a audio device has been added or removed. The driver then can notify the application
program, when a callback function has been registered via
USBH_AUDIO_AddNotification(). In order to communicate with such a device,
the application has to call the USBH_AUDIO_Open(), passing the interface index. Audio
interfaces are identified by an index. The first connected interface gets assigned the index
0, the second index 1, and so on.
Audio devices contains multiple USB interfaces: One control interface and one or more audio streaming interfaces.
The control interface and at least one streaming interface must be opened using USBH_AUDIO_Open().
Via the control interface, different functional units can be accessed:
Feature units (to set volume, muting, etc.)
Selector units
Mixer units
The streaming interface is used to transfer audio data. It must be configured first to select the
appropriate audio parameters: Audio sample size, number of channels and sample frequency.
Audio data transfer is then done using the Read/Write API function.
When audio data is transferred in PCM encoding, it consists of multiple audio samples.
If for example the device uses 2 channels (stereo) and 16 bit data per channel the the data stream looks like:
Note
In order to use the AUDIO class driver, support for isochronous transfers must be enabled in the USB stack.
Make sure that there is a preprocessor define in the file USBH_Conf.h:
#defineUSBH_SUPPORT_ISO_TRANSFER 1
Example code
There are two example application which uses the API. One to access an audio output device like a speaker,
that shows how to output sound, see the file USBH_AUDIO_Speaker.c.
Another sample application demonstrates access to an audio input device like a microphone, see the file USBH_AUDIO_Microphone.c.
API Functions
This chapter describes the emUSB-Host AUDIO driver API functions.
These functions are defined in the header file USBH_AUDIO.h.
Has to be called the same number of times USBH_AUDIO_Init was
called in order to de-initialize the module.
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_AUDIO_Exit(). The only exception is USBH_AUDIO_Init(),
which would in turn re-init the module and allow further calls.
USBH_AUDIO_AddNotification()
Description
Adds a callback in order to be notified when a device is added or removed.
USBH_STATUS_SUCCESS on success or error code on failure.
USBH_AUDIO_GetDescriptorList()
Description
Retrieves a list of all descriptors for the AUDIO interface.
The memory for the list returned is allocated by this functions and must be
freed later using USBH_AUDIO_FreeDescriptorList().
Retrieves information about an audio streaming endpoint.
This function can be applied to an audio streaming interface only
(SubClass = USBH_AUDIO_SUBCLASS_STREAMING).
Ignore all endpoints with an alternate setting number lower than this value.
pEPInfo
Pointer to a USBH_AUDIO_EP_INFO structure, which is filled by the function.
Return value
USBH_STATUS_SUCCESS on success or error code on failure.
Additional information
To get information about all alternate settings, the function should be called the first time
with AlternateSetting = 0. On subsequent calls to USBH_AUDIO_GetEndpointInfo(), AlternateSetting should
be set to pEPInfo->AlternateSetting + 1. Repeat until the function returns USBH_STATUS_NOT_FOUND.
USBH_AUDIO_GetFeatureUnitInfo()
Description
Retrieves information about a feature unit.
This function can be applied to an audio control interface only
(SubClass = USBH_AUDIO_SUBCLASS_CONTROL).
Control unit request types. Use one of the USBH_AUDIO_REQUEST_GET_… macros.
Unit
ID of the feature unit.
Selector
Control selector, see USBH_AUDIO_SELECTOR_FU_… macros.
Channel
Control channel number.
pDataLen
in Size of the data buffer provided by pData (in bytes). out Length of the data returned by the audio device.
pBuff
Pointer to the buffer where the control data is stored. Details of the data returned depending on the given selector are specified in the document “Universal Serial Bus Device Class Definition for Audio Devices”.
Return value
USBH_STATUS_SUCCESS on success or error code on failure.
USBH_AUDIO_SetFeatureUnitControl()
Description
Set a control value of a feature unit.
This function can be used for audio 1.0 devices only.
Control selector, see USBH_AUDIO_SELECTOR_FU_… macros.
Channel
Control channel number.
DataLen
Length of the data to be set.
pData
Pointer to the data. Details of the data required depending on the given selector are specified in the document “Universal Serial Bus Device Class Definition for Audio Devices”.
Return value
USBH_STATUS_SUCCESS on success or error code on failure.
USBH_AUDIO_GetMixerUnitControl()
Description
Get a control value of a mixer unit.
This function can be used for audio 1.0 devices only.
USBH_STATUS_SUCCESS on success or error code on failure.
USBH_AUDIO_OpenOutChannel()
Description
Prepare a channel for audio OUT data. If successful,
successive calls to USBH_AUDIO_Write() should be used to send audio data.
This function can be applied to an audio streaming interface only
(SubClass = USBH_AUDIO_SUBCLASS_STREAMING).
Number of bytes per sample. Can be retrieved using USBH_AUDIO_GetEndpointInfo(). SampleSize = USBH_AUDIO_EP_INFO.NrChannels * USBH_AUDIO_EP_INFO.SubFrameSize.
USBH_STATUS_SUCCESS on success or error code on failure.
USBH_AUDIO_OpenInChannel()
Description
Prepare a channel for audio IN data. If successful, audio data will be read
from the device and can be retrieved using USBH_AUDIO_Read().
This function can be applied to an audio streaming interface only
(SubClass = USBH_AUDIO_SUBCLASS_STREAMING).
Write data to an audio streaming endpoint. The write request data is put into a queue
and will be send executed asynchronously. The function returns immediately.
If there are no space in the queue, it returns status USBH_STATUS_BUSY.
Size of the data to be send. Must be at least the size of one ISO packet for the endpoint used (≥ USBH_AUDIO_GetOutPacketSize(Handle, 0)).
pData
Pointer to the data. The data must remain valid until the transaction is complete.
Return value
USBH_STATUS_SUCCESS on success or error code on failure.
USBH_AUDIO_CheckBufferIdle()
Description
Check if a buffer used by a preceding call to USBH_AUDIO_Write() can be reused for the next transfer.
If there is no entry in the write queue for the given buffer, the function returns immediately
with status USBH_STATUS_SUCCESS. This also applies, if there was no preceding call to USBH_AUDIO_Write()
with the given buffer.
The functions returns USBH_STATUS_NEED_MORE_DATA, if the buffer can’t be flushed because there is not
enough data in the queue to build a full ISO data packet.
Pointer to a data buffer that was used in a preceding call to USBH_AUDIO_Write().
bWait
Defines behavior of the function: 0 - Function returns immediately. 1 - Function blocks until the buffer gets idle or an error occurs.
Return value
USBH_STATUS_SUCCESS
Buffer idle and can be used for new transfers.
USBH_STATUS_BUSY
Buffer is busy, transfer not completed. Only if bWait = 0.
other
Error code of failure.
USBH_AUDIO_Receive()
Description
Receive a data packet from an audio streaming endpoint. On success the function returns a
pointer to an internal buffer that contains the data packet. The data must be acknowledged
within one millisecond after it was received using the function USBH_AUDIO_Ack().
This will enable the driver to reuse the buffer to receive another packet.
Timeout given in milliseconds. A zero value results in an infinite timeout. If Timeout is -1, the function never blocks.
Return value
USBH_STATUS_SUCCESS
A data packet is returned by the function.
USBH_STATUS_TIMEOUT
No data is available.
other
Error code of failure.
USBH_AUDIO_Ack()
Description
Acknowledge a data packet that was received using USBH_AUDIO_Receive().
This will enable the driver to reuse the buffer provided by USBH_AUDIO_Receive()
to receive another packet.
USBH_STATUS_SUCCESS on success or error code on failure.
USBH_AUDIO_Read()
Description
Read data from an audio streaming endpoint.
This function will either return if all data have been read from the device
or when the timeout is expired. The function may have read some data and
stored into the buffer even if it returns an error.
The USB stack can only read complete packets from the USB device.
If the size of a received packet exceeds the requested length to be read
then all data that does not fit into the callers buffer (pBuff) is stored in an internal
buffer and will be returned by the next call to USBH_AUDIO_Read().
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.
This chapter describes the optional emUSB-Host add-on “CP210X device driver”.
It allows communication with CP210x USB devices, typically serving as
USB to UART bridges.
Introduction
The CP210X driver software component of emUSB-Host allows the communication with
CP210x devices. It implements the CP210x protocol specified by Silicon Labs which is a
vendor specific protocol. The protocol allows emulation of serial communication via
USB.
This chapter provides an explanation of the functions available to application developers via the CP210X driver software. All the functions and data types of this add-on
are prefixed with the “USBH_CP210X_” text.
Features
The following features are provided:
Compatibility with different CP210X devices.
Ability to send and receive data.
Ability to set various parameters, such as baudrate, number of stop bits, parity.
Handling of multiple CP210X devices at the same time.
Notifications about CP210X connection status.
Ability to query the CP210X line and modem status.
Example code
An example application which uses the API is provided in the USBH_CP210X_Start.c file.
This example displays information about the CP210X device in the I/O terminal of the
debugger. In addition the application then starts a simple echo server, sending back
the received data.
Compatibility
The following devices have been tested with the current CP210X driver:
CP2102
CP2103
CP2104
Further reading
For more information about the CP210X devices, please take a look at the hardware manuals and CP210x Virtual COM Port Interface (Document Reference No.: AN571) available from https://www.silabs.com/products/interface/usb-bridges
API Functions
This chapter describes the emUSB-Host CP210X driver API functions.
Before this function is called any notifications added via
USBH_CP210X_AddNotification() must be removed
via USBH_CP210X_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_CP210X_Exit(). The
only exception is USBH_CP210X_Init(), which would in turn
reinitialize the module and allows further calls.
USBH_CP210X_AddNotification()
Description
Adds a callback in order to be notified when a device is added or removed.
Define whether short read mode shall be used or not. 1 - Allow short read. 0 - Short read mode disabled.
Return value
= USBH_STATUS_SUCCESS
Successful.
≠ USBH_STATUS_SUCCESS
An error occurred.
Additional information
USBH_CP210X_AllowShortRead() sets the USBH_CP210X_Read() into
a special mode - short read mode. When this mode is enabled,
the function returns as soon as any data has been read from
the device. This allows the application to read data where
the number of bytes to read is undefined. To disable this mode,
AllowShortRead should be set to 0.
out Pointer to a variable which receives the number of bytes read from the device.
Timeout
Timeout given in milliseconds. A zero value results in an infinite timeout.
Return value
= USBH_STATUS_SUCCESS
Successful.
≠ USBH_STATUS_SUCCESS
An error occurred.
Additional information
USBH_CP210X_Read() always returns the number of bytes read in
pNumBytesRead. This function does not return until NumBytes bytes
have been read into the buffer unless short read mode is enabled.
Number of bits per word. Must be one of the following values: USBH_CP210X_BITS_8USBH_CP210X_BITS_7USBH_CP210X_BITS_6USBH_CP210X_BITS_5
StopBits
Number of stop bits. Must be one of the following values: USBH_CP210X_STOP_BITS_1USBH_CP210X_STOP_BITS_1_5USBH_CP210X_STOP_BITS_2
Parity
Parity - must be one of the following values: USBH_CP210X_PARITY_NONEUSBH_CP210X_PARITY_ODDUSBH_CP210X_PARITY_EVENUSBH_CP210X_PARITY_MARKUSBH_CP210X_PARITY_SPACE
Pointer to a variable of type U8 which receives the modem status from the device.
Return value
= USBH_STATUS_SUCCESS
Successful.
≠ USBH_STATUS_SUCCESS
An error occurred.
Additional information
The modem control line status byte (pModemStatus) is defined as follows:
bit 0: DTR state (as set by host or by handshaking logic in CP210x).
bit 1: RTS state (as set by host or by handshaking logic in CP210x).
bits 2-3: reserved.
bit 4: CTS state (as set by end device).
bit 5: DSR state (as set by end device).
bit 6: RI state (as set by end device).
bit 7: DCD state (as set by end device).
This chapter describes the optional emUSB-Host add-on “Video device driver”.
It allows communication with USB video devices.
Introduction
The Video driver software component of emUSB-Host allows communication with USB video V1.00 compatible
devices like webcams.
This chapter provides an explanation of the functions available to application developers
via the video driver software. All the functions and data types of this add-on are
prefixed with ’USBH_VIDEO_’.
Overview
A video device connected to the emUSB-Host is automatically configured and added to
an internal list. If the Video driver has been registered, it is notified via a callback
when a video device has been added or removed. The driver then can notify the application
program, when a callback function has been registered via
USBH_VIDEO_AddNotification(). In order to communicate with such a device,
the application has to call the USBH_VIDEO_Open(), passing the interface index. Video
interfaces are identified by an index. The first connected interface gets assigned the index
0, the second index 1, and so on.
Video devices contains multiple USB interfaces: One control interface and one or more video streaming interfaces.
Via the control interface, different functional units can be accessed:
Input/Output terminals
Selector units
Processing units
Extension units
The streaming interface is used to transfer video data. It must be configured first to select the
appropriate video parameters: format, resolution and frame rate interval.
Video data transfer is then done using a callback which is registered via USBH_VIDEO_OpenStream() together with the video parameters.
Still image capture method 0 is supported.
Note
In order to use the Video class driver, support for isochronous transfers must be enabled in the USB stack.
Make sure that there is a preprocessor define in the file USBH_Conf.h:
#defineUSBH_SUPPORT_ISO_TRANSFER 1
Note
Depnding on the used video device and the selected format and resolution it may be necessary for the USB driver to support high-bandwidth isochronous transfers.
Example code
The sample application USBH_VIDEO_Start.c shows how to retrieve information and capabilities from a video device and how to receive frame data.
API Functions
This chapter describes the emUSB-Host Video driver API functions.
These functions are defined in the header file USBH_VIDEO.h.
Acknowledge a data packet that was received via the read callback which was registered via USBH_VIDEO_OpenStream This will enable the driver to reuse the buffer to receive another packet.
Has to be called the same number of times USBH_VIDEO_Init was
called in order to de-initialize the module.
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_VIDEO_Exit(). The only exception is USBH_VIDEO_Init(),
which would in turn re-init the module and allow further calls.
USBH_VIDEO_AddNotification()
Description
Adds a callback in order to be notified when a device is added or removed.
out Pointer to a structure of type USBH_VIDEO_TERM_UNIT_INFO which will be filled with information about the terminal or unit if the function returns USBH_STATUS_SUCCESS.
Return value
USBH_STATUS_SUCCESS on success or error code on failure.
Additional information
For the Index parameter USBH_VIDEO_GetInterfaceInfo() can be used
to retrieve the number of terminals/units the device has.
USBH_VIDEO_TermUnitID2Index()
Description
Helper function to retrieve the index of a terminal or unit
using the terminal or unit ID.
out Pointer to a structure of type USBH_VIDEO_INPUT_HEADER_INFO which will be filled with information about the stream if the function returns USBH_STATUS_SUCCESS.
Return value
USBH_STATUS_SUCCESS on success or error code on failure.
USBH_VIDEO_GetFormatInfo()
Description
Retrieve information about a video Format descriptor.
out Pointer to a structure of type USBH_VIDEO_FORMAT_INFO which will be filled with information about a format if the function returns USBH_STATUS_SUCCESS.
Return value
USBH_STATUS_SUCCESS on success or error code on failure.
Additional information
For the FormatIdx parameter USBH_VIDEO_GetInputHeader() can be used
to retrieve the number of formats the device has.
The FormatIdx parameter is not the same as the bFormatIndex
value inside the video format descriptor.
USBH_VIDEO_GetFrameInfo()
Description
Retrieve information about a Frame descriptor which belongs to a specific format.
out Pointer to a structure of type USBH_VIDEO_FRAME_INFO which will be filled with information about a frame if the function returns USBH_STATUS_SUCCESS.
Return value
USBH_STATUS_SUCCESS on success or error code on failure.
Additional information
A format descriptor contains one or more frame descriptors.
For the FormatIdx parameter USBH_VIDEO_GetInputHeader() can be used
to retrieve the number of formats the device has.
The FormatIdx parameter is not the same as the bFormatIndex
value inside the video format descriptor.
For the FrameIdx parameter USBH_VIDEO_GetFormatInfo() can be used
to retrieve the number of frame descriptors a particular format has.
The FrameIdx parameter is not the same as the bFrameIndex
value inside the video format descriptor.
USBH_VIDEO_GetColorMatchingInfo()
Description
Retrieves the color matching descriptor from a given format index.
out Pointer to a structure of type USBH_VIDEO_COLOR_INFO which will be filled with information about the color matching descriptor if the function returns USBH_STATUS_SUCCESS.
Return value
USBH_STATUS_SUCCESS on success or error code on failure.
Pointer to a structure of type USBH_VIDEO_STREAM_CONFIG. The user must fill the structure with valid information for the chosen video setting.
pHandle
out Pointer to a value of type USBH_VIDEO_STREAM_HANDLE which will receive the valid open stream handle if the function returns USBH_STATUS_SUCCESS.
Return value
USBH_STATUS_SUCCESS on success or error code on failure.
USBH_VIDEO_Ack()
Description
Acknowledge a data packet that was received via the read callback
which was registered via USBH_VIDEO_OpenStream
This will enable the driver to reuse the buffer to receive another packet.
USBH_STATUS_SUCCESS on success or error code on failure.
USBH_VIDEO_ReadStatus()
Description
Reads status messages from the video device.
This function can also be used to check for hardware trigger
interrupts (when the user presses a button on the webcam).
Pointer to a variable which receives the number of bytes read from 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
The status packet format is documented inside the UVC 1.1 specification
chapter “2.4.2.2 Status Interrupt Endpoint”.
This function reads from the video device’s interrupt IN endpoint.
This endpoint is optional and some video devices do not have it,
in this case status requests are not possible.
If the function returns an error code (including USBH_STATUS_TIMEOUT) it already may
have read part of the data. The number of bytes read successfully is always
stored in the variable pointed to by pNumBytesRead.
Data structures
This chapter describes the emUSB-Host Video driver data structures.
Number of terminals and units reported within the corresponding video control interface.
InterfaceID
ID of the 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.
Terminal or Unit type. One of the following values: USBH_VIDEO_VC_INPUT_TERMINALUSBH_VIDEO_VC_OUTPUT_TERMINALUSBH_VIDEO_VC_SELECTOR_UNITUSBH_VIDEO_VC_PROCESSING_UNITUSBH_VIDEO_VC_EXTENSION_UNIT
bTermUnitID
Unique identifier (address space is shared between terminal and unit IDs).
USBH_VIDEO_INPUT_HEADER_INFO
Description
Structure containing information about a video stream.
Indicates the capabilities of this VideoStreaming interface: D0: Dynamic Format Change supported D7..1: Reserved
bTerminalLink
The terminal ID of the Output Terminal to which the video endpoint of this interface is connected
bStillCaptureMethod
Method of still image capture supported: 0: None 1: Method 1 2: Method 2 3: Method 3
bTriggerSupport
Specifies if hardware triggering is supported through this interface 0: Not supported 1: Supported
bTriggerUsage
Specifies how the host software shall respond to a hardware trigger interrupt event from this interface. This is ignored if the bTriggerSupport field is zero. 0: Initiate still image capture 1: General purpose button event.
bControlSize
Size of each bmaControls(x) field, in bytes
bmaControls
Each byte in this array corresponds to one format (e.g. bmaControls[0] is for the first format) Each bit indicates support for the following capabilities: D0: wKeyFrameRate D1: wPFrameRate D2: wCompQuality D3: wCompWindowSize D4: Generate Key Frame D5: Update Frame Segment
USBH_VIDEO_FORMAT_INFO
Description
Structure containing information about a video format.
Frame interval type. A value of 0 indicates a continuous frame interval (very rarely used), a value > 0 indicates the number of discrete frame intervals supported (amount of valid entries inside the u.dwFrameInterval array).
USBH_VIDEO_COLOR_INFO
Description
Structure containing information about a video format’s color matching.
Opto-electronic transfer characteristic: 0: Unspecified (unknown) 1: BT.709 (default) 2: BT.470-2 M 3: BT.470-2 B, G
bMatrixCoefficients
Matrix used to compute luma and chroma values from the color primaries: 0: Unspecified 1: BT. 709 2: FCC 3: BT.470-2 B, G 4: SMPTE 170M (BT.601, default) 5: SMPTE 240M 6-255: Reserved
USBH_VIDEO_PAYLOAD_HEADER
Description
Structure containing the payload header.
Users must check bHeaderLength and bmHeaderInfo to makes sure all all fields are valid.
Bitfield which provides information about the availability and validity of additional fields: D0: Frame ID D1: End of Frame flag D2: Presentation Time field valid D3: Source Clock Reference field valid D4: Reserved D5: Still Image flag D6: Error flag D7: End of header flag
SOFCounter
1KHz SOF token counter
dwPresentationTime
Presentation Time Stamp
SourceTimeClock
Source Clock Reference
USBH_VIDEO_STREAM_CONFIG
Description
Structure containing configuration with which the emUSB-Host Video class should start reading frame data from the device.
Index of the Frame interval to use (0 if the frame interval type is “continuous”).
IntervalValue
(Only used for continuous frame interval!) Interval in 100ns units. The application must make sure the value is within the dwMinFrameInterval and dwMaxFrameInterval limits and that dwFrameIntervalStep is respected.
Should be one of the following types: USBH_VIDEO_GET_CURUSBH_VIDEO_GET_MINUSBH_VIDEO_GET_MAXUSBH_VIDEO_GET_RESUSBH_VIDEO_GET_LENUSBH_VIDEO_GET_INFOUSBH_VIDEO_GET_DEF
Selector
Control Selector, see USBH_VIDEO_CS_* macros.
pData
Pointer to a buffer where the device response will be saved into.
pDataLen
in Number of bytes to requests from the device. This value must match the requested control selector. See “USB Device Class Definition for Video Devices revision 1.1” for details. out Number of bytes received.
Definition of the callback which is registered via USBH_VIDEO_OpenStream().
This callback is called by the stack when new video data is received.
To ensure good throughput this callback should block as little as possible.
USBH_STATUS_SUCCESS on success or error code on failure.
pBuf
Pointer to the last filled buffer.
NumBytes
Number of bytes inside the buffer.
Flags
Bitfield containing flags related to the received data: USBH_UVC_END_OF_FRAME
Additional information
After the data received has been handled the application must call USBH_VIDEO_Ack()
to allow for the internal buffer to be re-used by the stack.
USBH_VIDEO_PAYLOAD_CALLBACK
Description
Definition of the callback which is registered via USBH_VIDEO_OpenStream().
This function is called with each received payload.
This function is only necessary if you are interested in the payload
header fields (see USBH_VIDEO_PAYLOAD_HEADER structure).
Payloads are normally received every 125 us in high-speed and every 1 ms in full-speed.
USBH_STATUS_SUCCESS on success or error code on failure.
pHeader
Pointer to the payload header.
NumBytes
Number of bytes inside the buffer.
USB On-The-Go (Add-On)
This chapter describes the emUSB-Host add-on emUSB-OTG and how to use it.
The emUSB-OTG is an optional extension of emUSB-Host.
Introduction
Overview
USB On-The-Go (OTG) allows two USB devices to communicate with each other.
OTG introduces the dual-role device, meaning a device capable of functioning as
either host or peripheral.
USB OTG retains the standard USB host/peripheral model, in which a single host talks
to USB peripherals.
emUSB OTG offers a simple interface in order to detect the role of the USB OTG controller.
Features
The following features are provided:
Detection of the USB role of the device.
Virtually any USB OTG transceiver can be used.
Simple interface to OTG-hardware.
Seamless integration with emUSB-Host and emUSB-Device.
Example code
An example application which uses the API is provided in the USB_OTG_Start.c file of
your shipment. This example starts the OTG stack and waits until a valid session is
detected. As soon as a valid session is detected, the ID-pin state is checked to detect
whether emUSB-Device or emUSB-Host shall then be initialized. For emUSB-Device a
simple mouse sample is used. On emUSB-Host side an MSD-sample is used that
detects USB memory stick and shows information about the detected stick.
Excerpt from the example code:
/*********************************************************************** OTGTask** Function description* USB OTG handling task.* It implements a basic function how to check which USB stack shall be called.* It first checks whether the OTG chip has detected a valid session.* If so, the next step will be to check the state of the ID-pin of the cable.* If pin is 0 (grounded) -> a USB host cable is connected.* If pin is 1 (floating) -> a USB device is plugged in.**/voidOTGTask(void);voidOTGTask(void){intState;while(1){//// Initialize OTG stack//USB_OTG_Init();//// Wait for a valid session//for(;;){State =USB_OTG_GetSessionState();if(State !=USB_OTG_ID_PIN_STATE_IS_INVALID){break;}USB_OTG_OS_Delay(25);BSP_ToggleLED(0);USB_OTG_OS_Delay(25);BSP_ToggleLED(1);}//// Determine whether Device or Host stack shall be initialized and started.//USB_OTG_DeInit();USB_OS_Delay(10);if(State ==USB_OTG_ID_PIN_STATE_IS_HOST){_ExecUSBHost();}else{_ExecUSBDevice();}}}
OTG Driver
To use emUSB OTG, a driver matching the target hardware is required.
The driver handles both the OTG controller as well as the OTG transceiver.
The driver interface has been designed to take full advantage of hardware features such
as session detection and session request protocol.
API Functions
This chapter describes the emUSB-OTG API functions.
User provided function which configures the USB OTG stack.
Prototype
void USB_OTG_X_Config(void);
Additional information
This function is called by the start-up code of the USB OTG stack from USB_OTG_Init().
This function should initialize all necessary clocks and pins required for the OTG operation of your controller.
This chapter explains how to configure emUSB-Host.
Runtime configuration
The configuration of emUSB-Host for a target hardware is done at runtime: The emUSB-Host stack calls
a function named USBH_X_Config, that must be provided by the application. This function
performs board specific hardware initialization like configuring I/O pins of the MCU, setting up
PLL and clock divider necessary for USB and installing the interrupt service routine for USB.
In general many devices need to configure GPIO pins in order to use them with the
USB host controller. In most cases the following pins are necessary:
USB D+
USB D-
USB VBUS
USB GND
USB PowerOn
USB OverCurrent
Please note that those pins need to be initialized within the USBH_X_Config()
function before the host controller driver Add-function is called.
Additionally all runtime configuration of the USB stack is done in this function, for example:
Assign memory to be used by the emUSB-Host stack.
Select an appropriate driver for the USB host controller.
Set driver specific parameters like base address of the controller of transfer buffer sizes.
Set debug message output filter.
Set a memory address translation routine (if a MMU is used).
Enable HUB support.
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/<Board-Name>/Setup.
This files can be used as a template for a customized configuration.
Memory pools
To dynamically manage multiple USB devices that may be connected to emUSB-Host, it has to create data
structures containing information about these devices. This include data structures for each device, interface and
endpoints. Additionally data buffers and DMA descriptors may be required to actually perform data transfers to the device.
emUSB-Host will take all memory required for this data structures and buffers from memory pools that must be provided
by the application.
emUSB-Host uses up to two memory pools: The first is assigned using USBH_AssignMemory(), the second one with
USBH_AssignTransferMemory(). The latter may be necessary to satisfy special requirements of the USB controller
and driver to access memory uncached and perform DMA to these memory areas. Some drivers do not distinguish between
these two memory areas and therefore only require one memory pool. For details, see Host controller specifics.
The size of the memory pool should be customized for the needs of the application. The optimal memory pool
size for an application can be determined as follows:
Start with a bigger memory pool configuration.
Run the application in DEBUG mode using the maximum functionality (e.g. connect all devices that should run simultaneously
and perform all needful data transfers).
If warning messages regarding memory allocation appear in the debug output, enlarge the memory pool and restart the
procedure.
Call the function USBH_MEM_GetMaxUsed() to find out, how much memory of the pool was actually used by the USB stack.
Resize the memory pool accordingly.
Estimated values for the memory usage can be found in RAM usage.
Some drivers require additional memory for data buffers for each endpoint.
The buffer size may the tuned using USBH_ConfigTransferBufferSize().
USBH_X_Config()
Description
Initialize USB hardware and configure the USB-Host stack.
This function is called by the startup code of the emUSB-Host stack from
USBH_Init(). This is the place where a hardware driver can be added and configured.
voidUSBH_X_Config(void){//// Assigning memory should be the first thing//USBH_AssignMemory(&_aPool[0],ALLOC_SIZE);USBH_AssignTransferMemory(&_aTransferBufferPool[0],ALLOC_TRANSFER_SIZE);//// Allow external hubs//USBH_ConfigSupportExternalHubs(1);//// Wait 300ms for a new connected device//USBH_ConfigPowerOnGoodTime(300);//// Define log and warn filter//USBH_ConfigMsgFilter(USBH_WARN_FILTER_SET_ALL,0,NULL);// Output all warnings.USBH_ConfigMsgFilter(USBH_LOG_FILTER_SET,sizeof(_LogCategories),_LogCategories);//// Initialize USB hardware//_InitUSBHw();//// Add EHCI driver//USBH_EHCI_EX_Add((void*)(USB_EHCI_BASE_ADDR +0x100));//// Install interrupt service routine//BSP_USBH_InstallISR_Ex(USB0_IRQn,_ISR,USB_ISR_PRIO);}
Configuration functions
Functions that may or must be used in USBH_X_Config are listed in the following table.
Additional driver dependant functions exist for every USB host controller driver, see
Host controller specifics.
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.
Sets a mask that defines which logging or warning message should be logged.
Compile-time configuration
emUSB-Host can be used without changing any of the compile-time switches. All
compile-time configuration switches are preconfigured with valid values which match the
requirements of most applications. All compile-time switches and their default values
can be found in the file USBH_ConfDefaults.h.
To change the default configuration of emUSB-Host compile-time switches
can be added to USBH_Conf.h. Don’t change the USBH_ConfDefaults.h file
for easy updates of emUSB-Host.
Compile-time switches for debugging
USBH_DEBUG
Description
emUSB-Host can be configured to display debug messages and warnings
to locate an error or potential problems. This can be useful for debugging.
In a release (production) build of a target system, they are typically not required
and should be switches off.
To output the messages, emUSB-Host uses the logging routines contained
in USBH_ConfigIO.c which can be customizes.
USBH_DEBUG can be set to the following values:
0 - Used for release builds. Includes no debug options.
1 - Used in debug builds to include support for “panic” checks.
2 - Used in debug builds to include warning, log messages and “panic” checks. This significantly increases the code size.
Definition
#defineUSBH_DEBUG 0
USBH_LOG_BUFFER_SIZE
Description
Maximum size of a debug / warning message (in characters) that can be output.
A buffer of this size is created on the stack when a message is output.
Definition
#defineUSBH_LOG_BUFFER_SIZE 200
Use of standard C-library functions
emUSB-Host calls some functions from the standard C-library. If the standard C-library should not be used,
the following macros can be changed to call user defined functions instead:
Must be set to 1 if the USB stack shall support isochronous transfers
(e.g for audio and video applications).
If set to 0, all code that handles isochronous transfers is disabled,
which may significantly reduce the code size of the USB stack.
Definition
#defineUSBH_SUPPORT_ISO_TRANSFER 0
USBH_MAX_NUM_HOST_CONTROLLERS
Description
Maximum number of host controllers the USB stack can handle.
Definition
#defineUSBH_MAX_NUM_HOST_CONTROLLERS 4u
USBH_SUPPORT_VIRTUALMEM
Description
If set to 1 the USB stack allows translation of virtual to physical
memory addresses used for DMA operations (see USBH_Config_SetV2PHandler()).
If the target system does not have a MMU, it can be set to 0.
Definition
#defineUSBH_SUPPORT_VIRTUALMEM 1
USBH_REO_FREE_MEM_LIST
Description
The USB stack uses a memory heap to allocate data structures for each
connected USB device (see USBH_AssignMemory() and USBH_AssignTransferMemory()).
If USB devices are frequently connected and disconnected this may lead to
fragmentation of the heap memory. If this options is set, a reorganization
of all free memory areas in the heap is performed after each disconnection
of an USB device.
Definition
#defineUSBH_REO_FREE_MEM_LIST 0
USBH_USE_APP_MEM_PANIC
Description
The USB host stack calls the function “void USBH_MEM_Panic(void)”, if memory allocation
fails during initialization of the host stack (USBH_Init()).
The stack contains a default implementation of the function USBH_MEM_Panic() which
halts the system, indicating a fatal error.
An application may implement its own USBH_MEM_Panic() function, when setting
USBH_USE_APP_MEM_PANIC to ’1’.
After successful initialization using USBH_Init(), USBH_MEM_Panic() is never called.
The host controller waits this time after reset of a root hub port, before the device descriptor is requested or
the Set Address command is sent. Given in milliseconds.
Definition
#defineUSBH_WAIT_AFTER_RESET 180
USBH_HUB_WAIT_AFTER_RESET
Description
The host controller waits this time after reset of a external hub port, before the device descriptor is requested or
the Set Address command is sent. Given in milliseconds.
Definition
#defineUSBH_HUB_WAIT_AFTER_RESET 180u
WAIT_AFTER_SETADDRESS
Description
The USB stack waits this time before the next command is sent after Set Address. The device must answer to SetAddress on USB address 0 with the
handshake and than set the new address. This is a potential racing condition if this step is performed in the firmware.
Give the device this time to set the new address. Given in milliseconds.
Definition
#defineWAIT_AFTER_SETADDRESS 30u
USBH_RESET_RETRY_COUNTER
Description
If an error is encountered during USB reset, set address or enumeration the process is repeated USBH_RESET_RETRY_COUNTER times
before the port is finally disabled.
Definition
#defineUSBH_RESET_RETRY_COUNTER 5u
USBH_DELAY_FOR_REENUM
Description
Describes the time in milliseconds before a USB reset is restarted,
after the enumeration of the device (get descriptors, set configuration) has failed.
Definition
#defineUSBH_DELAY_FOR_REENUM 1000u
USBH_DELAY_BETWEEN_ENUMERATIONS
Description
On default, enumeration for multiple devices may be processed in parallel.
Setting USBH_DELAY_BETWEEN_ENUMERATIONS > 0 will serialize all enumerations using a delay
before a new enumeration is performed. The delay can be given in milliseconds.
Definition
#defineUSBH_DELAY_BETWEEN_ENUMERATIONS 0
USBH_DEFAULT_SETUP_TIMEOUT
Description
Default timeout (in milliseconds) for all setup requests during enumeration of a device.
After this time a not completed setup request is terminated. Windows gives 2 seconds to
answer to a setup request. Less than that some devices behave quite strange.
So it should ≥ 2000.
Definition
#defineUSBH_DEFAULT_SETUP_TIMEOUT 2000
URB handling
USBH_URB_QUEUE_SIZE
Description
If not 0, queue URBs, when the driver reports USBH_STATUS_NO_CHANNEL
and retry them later. The value gives the maximum number of URBs that
can be queued. Only used for BULK transfers.
Definition
#defineUSBH_URB_QUEUE_SIZE 0u
USBH_URB_QUEUE_RETRY_INTV
Description
URB queue retry interval in ms. Only used, if USBH_URB_QUEUE_SIZE ≠ 0.
Definition
#defineUSBH_URB_QUEUE_RETRY_INTV 5u
USBH_SUPPORT_HUB_CLEAR_TT_BUFFER
Description
If set, a CLEAR_TT_BUFFER request is send to the HUB after an URB was aborted.
Used only for USB devices that are using split transactions.
Not supported by all drivers.
Definition
#defineUSBH_SUPPORT_HUB_CLEAR_TT_BUFFER 0
Mass storage class configuration
USBH_MSD_MAX_DEVICES
Description
Maximum number of mass storage devices the USB stack can handle simultaneously.
Definition
#defineUSBH_MSD_MAX_DEVICES 10u
USBH_MSD_MAX_SECTORS_AT_ONCE
Description
Maximum number of sectors to read with a single MSD read command.
Certain sticks have a limitation where they can not read or write
too many sectors in one command. For example:
DTSE9 16GB read limit ~ 4096, DT Ultimate G2 16GB write limit ~ 1024.
Windows uses max 128 sectors. Linux uses max 240 sectors.
Definition
#defineUSBH_MSD_MAX_SECTORS_AT_ONCE 256u
USBH_MSD_EP0_TIMEOUT
Description
Specifies the timeout in milliseconds to be used for control requests
to a mass storage device, especially for ’GetMaxLun’ and ’ClearFeatureHalt’ commands.
Definition
#defineUSBH_MSD_EP0_TIMEOUT 5000u
USBH_MSD_CBW_WRITE_TIMEOUT
Description
Specifies the timeout in milliseconds for sending a command block
to a mass storage device.
Definition
#defineUSBH_MSD_CBW_WRITE_TIMEOUT 3000
USBH_MSD_CSW_READ_TIMEOUT
Description
Specifies the timeout in milliseconds for reading a status block
from a mass storage device. 10 seconds is compatible to Windows.
Definition
#defineUSBH_MSD_CSW_READ_TIMEOUT 10000
USBH_MSD_COMMAND_TIMEOUT
Description
Specifies the timeout in milliseconds for reading answer data
from a mass storage device when not reading sector data.
Definition
#defineUSBH_MSD_COMMAND_TIMEOUT 3000u
USBH_MSD_DATA_READ_TIMEOUT
Description
Read timeout in milliseconds for the data phase when reading ’Length’ bytes of sector data
from a mass storage device.
Maximum number of retries executed for TestUnitReady / ReadCapacity commands
on failure during enumeration of a mass storage device. Value must be < 255.
Definition
#defineUSBH_MSD_MAX_TEST_READY_RETRIES 200u
USBH_MSD_MAX_READY_WAIT_TIME
Description
Maximum time (in milliseconds) to wait for a LUN to become ready after enumeration
of a mass storage device, before the user notification callback is called.
Definition
#defineUSBH_MSD_MAX_READY_WAIT_TIME 20000
USBH_MSD_TEST_UNIT_READY_DELAY
Description
Minimum time (in milliseconds) between two TestUnitReady commands
send to mass storage device.
Definition
#defineUSBH_MSD_TEST_UNIT_READY_DELAY 5000
HID class configuration
USBH_HID_MAX_REPORTS
Description
Maximum number of reports (with different report ID’s) of one HID interface that can be handled.
Definition
#defineUSBH_HID_MAX_REPORTS 6u
USBH_HID_DISABLE_INTERFACE_PROTOCOL_CHECK
Description
Some HID devices, namely touch screens, report their interface protocol as “mouse” despite
being actual touch screens (normally bInterfaceProtocol is “None” for such devices).
If this happens with your touch screens you can enable this flag.
Specifies the timeout in milliseconds to be used for control requests
to a HID device, like ’GetReportDescriptor’ command.
Definition
#defineUSBH_HID_EP0_TIMEOUT 1000
CDC-ACM class configuration
USBH_CDC_DISABLE_AUTO_DETECT
Description
Can be used to disable the automatic detection of CDC devices.
In that case the user must use USBH_CDC_AddDevice/USBH_CDC_RemoveDevice
for addition and removal of devices.
Definition
#defineUSBH_CDC_DISABLE_AUTO_DETECT 0
USBH_CDC_EP0_TIMEOUT
Description
Specifies the timeout in milliseconds to be used for control requests
to a CDC device, like ’SetAlternateInterface’, ’ClearFeatureHalt’,
’SetLineCoding’ and ’SetControlLineState’ commands.
Definition
#defineUSBH_CDC_EP0_TIMEOUT 1000
BULK (Vendor) class configuration
USBH_BULK_EP0_TIMEOUT
Description
Specifies the timeout in milliseconds to be used for control requests
to a vendor (BULK) device, especially for ’SetAlternateInterface’ and ’ClearFeatureHalt’ commands.
Definition
#defineUSBH_BULK_EP0_TIMEOUT 1000
USBH_BULK_MAX_NUM_EPS
Description
Maximum number of endpoints that can be handled for a BULK (Vendor) device.
Definition
#defineUSBH_BULK_MAX_NUM_EPS 5u
Printer class configuration
USBH_PRINTER_EP0_TIMEOUT
Description
Specifies the timeout in milliseconds to be used for control requests
to a printer device, especially for ’GetPortStatus’ and ’SendVendorRequest’ commands.
Definition
#defineUSBH_PRINTER_EP0_TIMEOUT 1000
AUDIO class configuration
USBH_AUDIO_EP0_TIMEOUT
Description
Specifies the timeout in milliseconds to be used for control requests
to an AUDIO device.
Definition
#defineUSBH_AUDIO_EP0_TIMEOUT 1000
FT232 class configuration
USBH_FT232_EP0_TIMEOUT
Description
Specifies the timeout in milliseconds to be used for control requests
to a FT232 device, like ’ResetDevice’, ’SetBaudRate’, ’SetDtr’,
’ClrDtr’, ’SetRts’, ’ClrRts’, ’GetModemStatus’, ’SetChars’,
’Purge’, ’SetBreakOn’, ’SetBreakOff’, ’SetLatencyTimer’,
’GetLatencyTimer’, ’SetBitMode’, ’GetBitMode’
’SetDataCharacteristics’ and ’SetFlowControl’ commands.
Definition
#defineUSBH_FT232_EP0_TIMEOUT 1000
CP210X class configuration
USBH_CP210X_EP0_TIMEOUT
Description
Specifies the timeout in milliseconds to be used for control requests
to a CP210X device, like ’SetBaudRate’, ’SetDataCharacteristics’,
’SetModemHandshaking’, ’GetModemStatus’ and ’Purge’ commands.
Definition
#defineUSBH_CP210X_EP0_TIMEOUT 1000
Host controller specifics
For emUSB-Host different USB host controller drivers are provided. Normally, the
drivers are ready and do not need to be configured at all. Some drivers may need
to be configured in a special manner, due to some limitation of the controller.
This section lists the drivers which require special configuration and describes
how to configure those drivers.
EHCI driver
Normally EHCI controllers only handle high-speed USB devices. Some EHCI controllers contain a transaction translator (TT)
that enables them to handle full- and low-speed devices also. There are different Add-functions to configure the driver for
host controllers with or without a TT.
Systems with cached memory
If the EHCI driver is installed on a system using cached (data) memory, the following requirements must be considered:
A special region of RAM is necessary that can be accessed non-cached and non-buffered by the CPU.
The USB host controller must also be able to access this area via DMA.
If the system contains a MMU all memory can be used cached as usual. Additionally the MMU
should be configured to mirror whole or part of the cached memory to another address range for uncached access.
If the physical address is not equal to the virtual address of the non-cached memory area
(address translation by an MMU), a mapping function must be installed using USBH_Config_SetV2PHandler().
The translated addresses (physical addresses) are used for DMA by the host controller.
Cache functions that may be set with USBH_SetCacheConfig() are not used by the driver.
The function USBH_EHCI_Config_UseTransferBuffer() must be called, in order to tell the driver that
application defined buffers can not be accessed directly via DMA.
Transfer buffers are allocated for each endpoint with a default size of 16KB.
This results in a maximum transfer speed, but requires a huge memory pool. In order to save memory, the size
of the transfer buffers can be reduced to at least 512 bytes, see USBH_ConfigTransferBufferSize().
Systems without cached memory
On systems without cache there is no need to provide a separate memory area with USBH_AssignTransferMemory().
A single memory heap is sufficient for the USB stack, see USBH_AssignMemory().
Pointer to the base of the EHCI controllers register set.
Return value
Reference to the added host controller (0-based index).
Additional information
Suspend and resume of USB devices is not supported for the RT1050
series EHCI controller.
Due to a hardware issue devices connected to the roothub port
must stay connected for at least 250ms before they are removed.
Should a device be removed before that the USB controller
will crash and only recover after a power cycle of the MCU.
For this controller the transfer memory ( USBH_AssignTransferMemory )
must be put into the internal DTCM RAM (0x20000000 ~ 0x2007FFFF).
USBH_RT1170_Add()
Description
Adds a HS capable EHCI controller to the stack. This EHCI
initialization function is specific to the RT1170 series.
Pointer to the base of the EHCI controllers register set.
Return value
Reference to the added host controller (0-based index).
Additional information
Suspend and resume of USB devices is not supported for the RT1170
series EHCI controller.
Due to a hardware issue devices connected to the roothub port
must stay connected for at least 250ms before they are removed.
Should a device be removed before that the USB controller
will crash and only recover after a power cycle of the MCU.
For this controller the transfer memory ( USBH_AssignTransferMemory )
must be put into the internal DTCM RAM.
USBH_IMX6U5_Add()
Description
Adds a HS capable EHCI controller to the stack. This EHCI
initialization function is specific to the IMX6U5 series.
Pointer to the base of the EHCI controllers register set.
Return value
Reference to the added host controller (0-based index).
Additional information
Suspend and resume of USB devices is not supported for the IMX6U5
series EHCI controller.
Due to a hardware issue devices connected to the roothub port
must stay connected for at least 250ms before they are removed.
Should a device be removed before that the USB controller
will crash and only recover after a power cycle of the MCU.
USBH_EHCI_Config_SetM2MEndianMode()
Description
Setups the internal EHCI memory to memory transfer endianness mode.
This only has an effect on the DMA transfers.
Both SFRs and DMA descriptors are still in the endianness defined
by the MCU/EHCI controller manufacturer.
In normal cases the SFRs and DMA descriptors are in CPU native endianness mode.
USBH_EHCI_M2M_ENDIAN_MODE_LITTLE - use little endian mode for memory-2-memory (DMA) transfers USBH_EHCI_M2M_ENDIAN_MODE_BIG - use big endian mode for memory-2-memory (DMA) transfers
USBH_EHCI_Config_UseTransferBuffer()
Description
Configures the driver to use temporary transfer buffers instead using the user buffer directly.
This is necessary if the MCU uses cache.
The following must be considered if using the DWC2 high-speed driver.
This is valid, even if the USB controller is used in full-speed mode (like on the STM32H7xx with internal PHY).
If the driver is installed on a system using cached (data) memory,
cache functions for cleaning and invalidating cache lines must be provided and set with USBH_SetCacheConfig().
On some MCUs the USB controller is not able to access all RAM areas the application uses.
In this case a function can be installed that checks for memory valid for DMA access (see USBH_STM32Fx_HS_SetCheckAddress() functions below).
If the function reports a memory region not valid for DMA, the driver uses a temporary
transfer buffer to copy data to and from this area. The memory are provided with USBH_AssignMemory() must be DMA capable.
If there is not enough DMA capable memory, the application may provide two different memory areas: A DMA capable area using
USBH_AssignTransferMemory() and a second one with USBH_AssignMemory() which then will not be accessed via DMA.
Restrictions
Low-speed devices
On any STM32 MCUs using the internal USB FS PHY low-speed USB devices connected via an external hub are not recognized due to a hardware limitation.
If connected in this way it may happen, that the host controller gets disturbed and blocked.
In order to return to normal operation, a reset of the controller and the external hub may be necessary.
In any case try to avoid low-speed devices in such a constellation.
The issue seems to be related to the internal PHY of the STM32 MCUs. It usually not occurs, if the high-speed
USB controller is used in connection with an external (high-speed) PHY.
Split transactions
If the host controller operates in high-speed and a full or low-speed device is connected via an external hub,
the driver uses split transactions to access the device. Split transactions will only work reliable, if
The task running USBH_ISRTask() must have the highest priority in the system.
The task running USBH_Task() must have the second highest priority.
All other task must have a lower priority than USBH_Task().
Both USB tasks must not be delayed by any interrupt service routine for more than 500 µs.
Additionally split transactions require usage of a 125µs interrupt, which increases system load.
Isochronous endpoints (full-speed controller)
Due to insufficient FIFO memory in the full-speed USB controller, isochronous endpoints (which are used in AUDIO devices for example)
are supported with a maximum packet size of up to 384 bytes only.
Isochronous endpoints (high-speed controller)
Isochronous transactions (which are used in AUDIO devices for example) are not supported for full-speed devices connected
via an external hub. Only transfer intervals of one packet per frame for full-speed devices and one packet per microframe
for high-speed devices are supported.
High-bandwidth isochronous transfers are not supported.
Channel stuck
Because of an issue of the USB controller hardware, sometimes a channel used for a packet transfer can’t be re-initialized after it was used.
Instead the channel remains in an undefined state and can’t be used for new transfers. This mainly happens after interrupted transfers,
when a device is disconnected in the middle of a packet transfer, but the exact cause it not clear.
The emUSB driver implements some recovery mechanism to get stuck channels working again, but this does not work always.
If not, the channel is stuck and can’t be used any more until a reset of the USB controller.
The driver continues working using the remaining channels.
Because there is a limited number of channels, it may happen, that the driver runs out of channels and is not able to service all transfer requests
of the USB stack any more or gets not operational at all.
Pointer to the base of the controllers register set.
PhyType
0 - use external PHY connected via ULPI interface. 1 - use internal full speed PHY.
Return value
Reference to the added host controller (0-based index).
USBH_STM32F2_HS_SetCheckAddress()
Description
Installs a function that checks if an address can be used for DMA transfers.
Installed function must return 0, if DMA access is allowed for the given address,
1 otherwise.
Pointer to the base of the controllers register set.
PhyType
0 - use external PHY connected via ULPI interface. 1 - use internal full-speed PHY.
Return value
Reference to the added host controller (0-based index).
USBH_STM32F7_HS_SetCheckAddress()
Description
Installs a function that checks if an address can be used for DMA transfers.
Installed function must return 0, if DMA access is allowed for the given address,
1 otherwise.
Pointer to the base of the controllers register set.
PhyType
0 - use external PHY connected via ULPI interface. 1 - use internal full speed PHY.
Return value
Reference to the added host controller (0-based index).
USBH_STM32H7_HS_SetCheckAddress()
Description
Installs a function that checks if an address can be used for DMA transfers.
Installed function must return 0, if DMA access is allowed for the given address,
1 otherwise.
Pointer to the base of the controllers register set.
Return value
Reference to the added host controller (0-based index).
OHCI driver
OHCI controllers handle full-speed and low-speed USB devices.
Systems with cached memory
If the OHCI driver is installed on a system using cached (data) memory, the following requirements must be considered:
A special region of RAM is necessary that can be accessed non-cached and non-buffered by the CPU.
The USB host controller must also be able to access this area via DMA.
If the physical address is not equal to the virtual address of the non-cached memory area
(address translation by an MMU), a mapping function must be installed using USBH_Config_SetV2PHandler().
The translated addresses (physical address) are used for DMA by the host controller.
Cache functions that may be set with USBH_SetCacheConfig() are not used by the driver.
Systems without cached memory
On systems without cache there is no need to provide a separate memory area with USBH_AssignTransferMemory().
A single memory heap is sufficient for the USB stack, see USBH_AssignMemory().
On systems without cache and where the OHCI controller has access to the memory where application buffers are located USBH_OHCI_ZC_Add() (instead of USBH_OHCI_Add() )
can be used to improve performance.
Pointer to the base of the OHCI controllers register set.
Return value
Reference to the added host controller (0-based index).
Additional information
This version of the OHCI driver uses zero-copy where possible thereby
increasing transfer speeds and decreasing memory consumption.
The zero-copy version of the OHCI driver is currently NOT compatible
with any MCUs which use cache.
Certain MCUs do not allow the OHCI controller to access some memory regions.
For this purpose a callback should be registered via USBH_OHCI_ZC_SetCheckZeroCopyAddress()
USBH_OHCI_ZC_SetCheckZeroCopyAddress()
Description
Installs a function that checks if an address can be used for zero copy transfers.
Installed function must return 0, if zero copy access is allowed for the given address,
1 otherwise.
If the function reports a memory region not valid for zero copy, the driver uses a temporary
transfer buffer to copy data to and from this area.
USBH_OHCI_LPC546_Add()
Description
Adds a full-speed capable OHCI controller to the stack.
This add function, enables workarounds inside the OHCI driver
for the LPC546xx series. One of these workarounds creates
a limitation where an interval timeout of 1 can not be guaranteed
for interrupt endpoints as each interrupt endpoint transfer
completion has to be delayed by up to two frames.
Pointer to the base of the OHCI controllers register set.
Return value
Reference to the added host controller (0-based index).
Kinetis USBOTG FS driver
KinetisFS controllers handle full-speed and low-speed USB devices.
Systems without cached memory
On systems without cache there is no need to provide a separate memory area with USBH_AssignTransferMemory().
A single memory heap is sufficient for the USB stack, see USBH_AssignMemory().
Restrictions
WFI instruction can not be used when the USBOTG module is used. This is a hardware issue, see errata e7166 for chip masks 4N96B, 1N96B, 3N96B.
When the controller accesses the flash memory (e.g. when an application writes to a device from a const char array) it
is necessary to allow the controller access to the flash area and to set the bus master priority to the highest level, otherwise read accesses to the flash may be stalled which results in the controller getting less data than expected and respective follow-up errors.
This controller can only schedule a single transaction at a time. This means that hubs can not be used with this host controller.
Furthermore composite devices will not work properly if the application communicates on multiple interfaces at once. Devices which contain an
Interrupt IN endpoint which needs to be constantly polled by the host controller will also have issues as the Interrupt IN endpoint will hog
the only communication pipe, a good sample for this is the CDC class which consists of Bulk IN, Bulk OUT and Interrupt IN endpoints,
in this case the controller will be constantly busy polling the Interrupt IN endpoint and will not be able to communicate via the Bulk endpoints.
To work around the Interrupt IN issue emUSB-Host provides the functions USBH_CDC_SetConfigFlags() and USBH_HID_ConfigureAllowLEDUpdate().
The full-speed version of the controller can only handle up to 5 devices at once.
High-speed controller can handle up to 10 devices.
Data corruption
This following issue seems to be valid for RX and RZ devices but not for the Synergy platform:
It seems that the concurrent transfers are not working correctly with higher bandwidth and may result in data corruption:
Data that are sent on one pipe are received on another pipe or are mixed with received data.
ISO support
ISO packets are limited to a maximum size of 256 bytes.
Due to a hardware limitation, full-speed device connected through a USB high-speed hub to the highspeed controller,
cannot handle more than 188 bytes as a transfer size in isochronous mode.
Low-speed devices
RX62x and RX63x series contains a USB controller where low-speed device such as mice, keyboards are not recognized properly.
Therefore for these device, low-speed support is disabled. You may see in debug builds, that the warning message that
this is not possible.
Low-speed devices connected directly work starting with chip revision “B”.
FS support
Full-speed devices connected directly do not work.
HUB support
Although the USB controller of the ATSAMx7 MCUs support external HUBs, the application is very limited.
Because USB pipes can not be dynamically allocated to devices,
connecting and disconnecting devices arbitrarily to and from the HUB will result in blocked pipes very soon,
and new connected devices will not be recognized any more.
Also split transactions are not supported, so low-speed and full-speed devices can not be used via a high-speed HUB.
Endpoint Address limitation
This host controller only supports endpoint addresses from 0 to 10, if a device uses endpoint addresses higher than that it will not function.
This is a limitation of the controller and there is no workaround (see description of the “PEPNUM: Pipe Endpoint Number” field of the USBHS_HSTPIPCFGx register in the reference manual).
Base address of the USBHS controllers register set.
USBRAMAddr
Base address of the USBHS FIFO RAM.
Return value
Reference to the added host controller (0-based index).
LPC54xxx/LPC55xxx High-Speed driver
This section applies to LPC54xxx and LPC55xxx devices.
Using this driver a single memory heap is sufficient for the USB stack, see USBH_AssignMemory().
There is no need to provide a separate memory area with USBH_AssignTransferMemory().
The driver uses the dedicated USB1 RAM of the LPC54xxx MCU for endpoint transfer buffers.
Restrictions
Low-speed devices
The high-speed USB controller of the LPC54xxx/LPC55xxx will not reliable enumerate low-speed devices directly connected to the USB
port. Although a workaround is implemented in the driver, it may not work in all cases. Sometimes a power cycle is necessary
to recover from this error.
ISO support
ISO packets are limited to a maximum size of 1023 bytes.
LPC54xxx/LPC55xxx driver specific configuration functions
ISO packets are limited to a maximum size of 256 bytes.
Controller stuck
If devices are connected via a hub and any device is disconnected while a packet is transferred from this device,
then the USB controller of the PSoC 6 gets stuck and connections to all devices (including the hub)
are lost. The controller is not able to process any more tasks and will become operational only after a physical disconnect
and re-connect of the device at the root port (usually the hub).
Suspend / Resume
Host suspend and resume does not work, because the controller is not able to generate correct signaling on the USB bus.
Reference to the added host controller (0-based index).
Support
Contacting support
Before contacting support please make sure that you are using the latest version of the emUSB-Host package.
Also please check the chapter Configuring debugging output and run your application with enabled debug support.
If you are a registered emUSB-Host user and you need to contact the emUSB-Host support please
send the following information via email to ticket_emusb@segger.com By sending us an email your (personal) data will automatically be processed. For further information please refer to our privacy policy which is available at https://www.segger.com/legal/privacy-policy/. :
Your emUSB-Host registration number.
emUSB-Host version.
A detailed description of the problem
The configuration files USBH_Config*.*
Any error messages.
Please also take a few moments to help us to improve our service by providing a short feedback when your support case has been solved.
Debugging
emUSB-Host comes with various debugging options. These include optional warning
and log outputs, as well as other runtime options which perform checks at run time.
Message output
The debug builds of emUSB-Host include a fine-grained debug system which helps to
analyze the correct implementation of the stack in your application. All modules of
the emUSB-Host stack can output logging and warning messages via terminal I/O, if
the specific message type identifier is added to the log and/or warn filter mask. This
approach provides the opportunity to get and interpret only the logging and warning
messages which are relevant for the part of the stack that you want to debug.
By default, all warning messages are activated in all emUSB-Host sample configuration files.
All logging messages are disabled except for the messages from the initialization phase.
Note
It is not advised to enable all log messages as the large amount of output may affect timing.
Mode to configure message filter: USBH_LOG_FILTER_SET: Set message categories in log filter. USBH_LOG_FILTER_SET_ALL: Enable all log messages (parameter pCategories is ignored). USBH_LOG_FILTER_ADD: Add message categories to log filter. USBH_LOG_FILTER_CLR: Clear message categories in log filter. USBH_WARN_FILTER_SET: Set message categories in warning filter. USBH_WARN_FILTER_SET_ALL: Enable all warning messages (parameter pCategories is ignored). USBH_WARN_FILTER_ADD: Add message categories to warning filter. USBH_WARN_FILTER_CLR: Clear message categories in warning filter.
NumCategories
Number of messages categories contained in the array pCategories.
pCategories
Pointer to array of NumCategories messages categories that should be configured.
Additional information
Should be called from USBH_X_Config().
By default, the log message category USBH_MCAT_INIT and
all warning messages are enabled.
Please note that the more logging is enabled, the more the timing
of the application is influenced.
For available message types see the USBH_MCAT_… definitions in USBH.h.
Please note that enabling all log messages is not
necessary, nor is it advised as it will influence the timing greatly.
In a release build this function is not linked in. The default
implementation of this function disables all interrupts to avoid
further task switches, outputs the error string via terminal I/O
and loops forever. When using an emulator, you should set a
break-point at the beginning of this routine or simply stop the
program after a failure.
emUSB-Host is designed to be used in a multitasking environment. The interface to
the operating system is encapsulated in a single file, the USB-Host/OS interface.
This chapter provides descriptions of the functions required to fully support emUSB-Host in multitasking environments.
General information
emUSB-Host includes an OS abstraction layer which should make it possible to use an
arbitrary operating system together with emUSB-Host. To adapt emUSB-Host to a new
OS one only has to map the functions listed below in section OS layer API functions to the
native OS functions.
SEGGER took great care when designing this abstraction layer, to make it easy to under-
stand and to adapt to different operating systems.
The target RTOS should at least have the following features:
Blocks until the timeout expires or a USBH-event occurs.
Called from USBH_MainTask() only.
A USBH-event is signaled with USBH_OS_SignalNetEvent() called from an other task or ISR.
This chapter covers the performance and resource usage of emUSB-Host. It contains
information about the memory requirements in typical systems which can be used to
obtain sufficient estimates for most target systems.
Memory footprint
emUSB-Host is designed to fit many kinds of embedded design requirements. Several
features can be excluded from a build to get a minimal system. The code size depend
on the API functions called by the application.
The code was compiled for a Cortex-M4 CPU with size optimization.
Note that the values are only valid for an average configuration.
ROM usage
To save code memory, support for isochronous USB transfers in emUSB-Host can be disabled via the compile time
switch USBH_SUPPORT_ISO_TRANSFER. Currently isochronous transfers are required only to handle audio devices.
The following table shows the approximate ROM requirement of emUSB-Host (compiled using the SEGGER compiler with size optimization):
Component
ROM (iso disabled)
ROM (iso enabled)
Remark
USB core
6.4 KBytes
HUB Support
3.5 KBytes
CDC
5.0 KBytes
Vendor class
3.9 KBytes
CCID
5.3 KBytes
FT232
4.7 KBytes
HID Generic
5.5 KBytes
HID Mouse Keyboard
6.6 KBytes
MSD
5.3 KBytes
+ sizeof(file system)
MTP
12.3 KBytes
Printer
4.8 KBytes
MIDI
4.9 KBytes
AUDIO
6.9 KBytes
LAN using ASIX
8.8 KBytes
+ sizeof(emNET)
LAN using CDC-ECM
7.1 KBytes
+ sizeof(emNET)
LAN using RNDIS
7.5 KBytes
+ sizeof(emNET)
Driver EHCI
4.6 KBytes
6.5 KBytes
Driver OHCI
5.9 KBytes
7.3 KBytes
Driver STM32F4 FS
4.2 KBytes
4.9 KBytes
Driver STM32F4 HS
4.7 KBytes
5.4 KBytes
Driver STM32F7 HS
4.8 KBytes
5.6 KBytes
Driver Kinetis FS
2.9 KBytes
Driver Renesas RX64
4.5 KBytes
5.1 KBytes
Driver LPC54xxx HS
2.4 KBytes
3.3 KBytes
Driver LPC54xxx FS
6.4 KBytes
7.6 KBytes
Driver MUSB
2.4 KBytes
2.8 KBytes
Driver SAMV70
2.8 KBytes
RAM usage
The following table shows the average RAM requirement of emUSB-Host.
The actual RAM usage may vary depending on the USB host controller used,
the memory architecture of the target, the USB devices connected to emUSB-Host
and the type of operations performed with that devices.
Component
RAM
emUSB-Host core incl. one driver
3.8 KByte
For each connected generic HID device
2.8 KByte
For each connected CDC ACM device
4.1 KByte
For each connected Vendor (BULK) device
3.5 KByte
For each connected MSD device
2.3 KByte
For each connected Mouse
4.4 KByte
For each connected external HUB
1.9 KByte
For each connected LAN (ASIX) device
11.1 KByte
For each connected LAN (CDC-ECM) device
18.1 KByte
For each connected LAN (RNDIS) device
13.5 KByte
Performance
The following values have been tested using the CDC protocol.
An emPower evaluation board running emUSB-Device CDC class was connected to the host.
System with Synopsys (USB High-Speed) controller:
Description
Speed
Send speed
34.9 MByte/sec
Receive speed
39.0 MByte/sec
System with EHCI (USB High-Speed) controller:
Description
Speed
Send speed
30.9 MByte/sec
Receive speed
36.0 MByte/sec
System with OHCI (USB Full-Speed) controller:
Description
Speed
Send speed
800 KByte/sec
Receive speed
800 KByte/sec
Glossary
Term
Definition
BSP
Board support package.
CPU
Central Processing Unit. The “brain” of a microcontroller; the part of a processor that carries out instructions.
DMA
Direct Memory Access.
EOT
End Of Transmission.
FIFO
First-In, First-Out.
ISR
Interrupt Service Routine. The routine is called automatically by the processor when an interrupt is acknowledged. ISRs must preserve the entire context of a task (all registers).
MCU
Microcontroller unit.
MMU
Memory managing unit
NULL packet
See ZLP.
PLL
Phase-locked loop, used for clock generation inside a microcontroller.
RTOS
Real-time Operating System.
RTT
Real-Time Transfer. Method to output information from the target microcontroller as well as sending input to the application at a very high speed without affecting the target’s real time behavior.
Scheduler
The program section of an RTOS that selects the active task, based on which tasks are ready to run, their relative priorities, and the scheduling system being used.
Stack
An area of memory with LIFO storage of parameters, automatic variables, return addresses, and other information that needs to be maintained across function calls. In multitasking systems, each task normally has its own stack.
Superloop
A program that runs in an infinite loop and uses no real-time kernel. ISRs are used for real-time parts of the software.
Task
A program running on a processor. A multitasking system allows multiple tasks to execute independently from one another.
Tick
The OS timer interrupt. Usually equals 1 ms.
ZLP
Zero-Length-Packet
FAQ
This chapter answers some frequently asked questions.
Which CPUs can I use emUSB-Host with?
It can be used with any CPU (or MPU) for which a C compiler exists. Of course, it will work faster on 16/32-bit CPUs than on 8-bit CPUs.
Do I need a real-time operating system (RTOS) to use the emUSB-Host stack?
Yes, an RTOS is required.
Is the emUSB-Host API thread-safe?
Not generally. Different devices or endpoints can be handled in different tasks without restrictions.
For example a task may read from one endpoint or device while another task is writing to another endpoint or device.
If accessing the same resource, the user is responsible for locking API calls against each other.
emUSB-Host does not compile because of missing includes in the USBH_MSD_FS.c
file.
The USBH_MSD_FS.c file is a file system layer for emUSB-Host’s MSD module.
This layer is written for the SEGGER file system emFile.
If you do not have emFile you can use this file as a sample to write a file system
layer for your own file system.
Devices connected directly to my Host work, but do not work when connected
through a hub.
Please check your USBH_X_Config function. In it you should call
USBH_ConfigSupportExternalHubs(1) to enable hub support. Also consider restrictions listed in
Host controller specifics.
When I enable all logs via USBH_SetLogFilter(0xffffffff) my devices no longer enumerate.
Enabling too many log outputs can drastically influence the timing of the application
up to a point where it may no longer function. It is best practice to limit the
number of logs only to the ones you are interested in.