UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
1
A product of SEGGER Microcontroller GmbH & Co. KG
emUSB
Document: UM09001
Software version: 2.50e
Revision: 0
Date: Januar y 23, 2015
CPU-independent
User & Reference Guide
USB Device stack
www.segger.com
2
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
Disclaimer
Specifications written in this document are believed to be accurate, but are not guar-
anteed to be entirely free of error. The information in this manual is subject to
change for functional or performance improvements without notice. Please make sure
your manual is the latest edition. While the information herein is assumed to be
accurate, SEGGER Microcontroller GmbH & Co. KG (SEGGER) assumes no responsibil-
ity for any errors or omissions. SEGGER makes and you receive no warranties or con-
ditions, express, implied, statutory or in any communication with you. SEGGER
specifically disclaims any implied warranty of merchantability or fitness for a particu-
lar purpose.
Copyright notice
You may not extract portions of this manual or modify the PDF file in any way without
the prior written permission of SEGGER. The software described in this document is
furnished under a license and may only be used or copied in accordance with the
terms of such a license.
© 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG, Hilden / Germany
Trademarks
Names mentioned in this manual may be trademarks of their respective companies.
Brand and product names are trademarks or registered trademarks of their respec-
tive holders.
Contact address
SEGGER Microcontroller GmbH & Co. KG
In den Weiden 11
D-40721 Hilden
Germany
Tel.+49 2103-2878-0
Fax.+49 2103-2878-28
E-mail: support@segger.com
Internet: http://www.segger.com
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
3
Manual versions
This manual describes the current software version. If any error occurs, inform us
and we will try to assist you as soon as possible.
Contact us for further information on topics or routines not yet specified.
Print date: January 23, 2015
Software Revision Date By Description
2.50e 0 150123 YR
Chapter HID:
* Added new functions:
* USB_HID_GetNumBytesInBuffer()
* USB_HID_GetNumBytesInBufferEx()
* USB_HID_GetNumBytesRemToRead()
* USB_HID_GetNumBytesRemToReadEx()
* USB_HID_GetNumBytesToWrite()
* USB_HID_GetNumBytesToWriteEx()
* USB_HID_ReadEPOverlapped()
* USB_HID_ReadEPOverlappedEx()
* USB_HID_ReadEx()
* USB_HID_ReadExTimed()
* USB_HID_ReadTimed()
* USB_HID_StartReadTransfer()
* USB_HID_StartReadTransferEx()
* USB_HID_WaitForRX()
* USB_HID_WaitForRXEx()
* USB_HID_WaitForTX()
* USB_HID_WaitForTXEx()
* USB_HID_WriteEPOverlapped()
* USB_HID_WriteEPOverlappedEx()
* USB_HID_WriteEx()
* USB_HID_WriteExTimed()
* USB_HID_WriteTimed()
Removed typos.
2.50d 0 141215 YR Update to latest software version.
2.50c 0 141128 YR Update to latest software version.
2.50b 0 141125 YR
Update to latest software version.
Added the following function:
USB_BULK_TxIsPending
2.50a 0 141106 YR Update to latest software version.
internal 0 140929 YR
Improved most of the function descriptions in the CDC
chapter.
Added the following functions:
USB_CDC_StartReadTransferEx
USB_CDC_GetNumBytesInBufferEx
USB_CDC_GetNumBytesRemToReadEx
USB_CDC_GetNumBytesToWriteEx
USB_Stop()
USB_DeInit()
2.50 0 140725 YR Added the RNDIS chapter.
Minor improvements.
2.40m 2 140630 YR Update to latest software version.
internal 2 140618 YR
Updated the introduction chapter.
Fixed the descriptions of USB_CDC_Read* and
USB_CDC_Receive* functions.
2.40l 2 140606 SR Update to latest software version.
2.40k 2 140523 YR Update to latest software version.
Minor improvements to several function descriptions.
2.40i 2 140515 SR
Update to latest software version.
Added new drivers
Removed RNDIS chapter as the component is not released
yet.
2.40i 1 140415 SR Update to latest software version.
Minor bugfix.
2.40h 1 140411 SR Update to latest software version.
Added new driver.
2.40g 1 140410 SR Update to latest software version.
Minor bugfixes.
4
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
2.40f 1 140401 SR Update to latest software version.
Minor bugfixes.
2.40e 1 140313 SR Update to latest software version.
Minor bugfixes.
2.40d 1 140224 SR Update to latest software version.
Minor improvements.
2.40c 1 140213 SR Update to latest software version.
Minor improvements.
2.40b 1 140124 SR Update to latest software version.
Minor improvements.
2.40a 0 140110 YR Update to latest software version.
Minor improvements.
2.38f 1 131210 YR Removed some typos.
2.38f 0 131031 SR Update to latest software version.
2.38e 0 131021 SR Update to latest software version.
2.38d 0 131015 SR Update to latest software version.
2.38c 0 131004 YR Update to latest software version.
2.38 0 130920 YR Created a separate chapter for Bulk Host API V2.
internal 0 130705 MD Added MTP chapter.
internal 0 130410 YR Added the new Bulk Host API V2.
Removed some typos.
2.36 0 130208 YR
Added Certification chapter.
Added RNDIS chapter.
Updated available drivers.
Removed some typos.
2.34 1 111116 YR
Updated USB Core chapter:
* Added description for function:
USB__WriteEP0FromISR()
Removed some typos.
2.34 0 111111 SR
Updated CDC chapter:
* Added new function: USB_CDC_SetOnBreak()
* Updated the functions: USB_MSD_INST_DATA_DRIVER
Chapter Target USB driver:
* Added new drivers to the list.
Removed some typos.
2.32 0 101206 SR
Added new functions in USB Core chapter:
* USB_SetVendorRequestHook(), USB_SetIsSelfPowered()
Updated the Product Ids in Chapter GettingTheTar-
getUp\Configuration.
Updated MSD chapter:
* Added new picture on front page.
* Updated chapter Overview
* Added new function: USB_MSD_Connect(),
USB_MSD_Disconnect(), USB_MSD_RequestDisconnect(),
USB_MSD_UpdateWriteProtect(),
USB_MSD_WaitForDisconnection(),
* Updated the functions: USB_MSD_INST_DATA_DRIVER
Updated the CDC chapter:
* Added new Ex-Functions
* Added new serial status functions.
Added new picture to the front page of chapter HID.
Update Printer Class chapter:
* Added new picture to the front page to the chapter
* Added new information to the USB_PRINTER_API.
Chapter Target USB driver:
* Added new drivers to the list.
2.30 0 101022 SR Added the function for remote wakeup.
2.27 0 100730 MD Chapter "Printer Class" added.
Software Revision Date By Description
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
5
2.26 1 090127 SR
Chapter USB core:
* Added new functions: USB_SetMaxPower(),
USB_SetOnRxEP0(), USB_SetOnSetupHook()
Chapter Bulk Communication:
* Added new functions:
* USB_BULK_CancelRead()
* USB_BULK_CancelWrite()
* USB_BULK_ReadTimed()
* USB_BULK_SetOnRXHook()
* USB_BULK_WaitForTX()
* USB_BULK_WaitForRX()
* USB_BULK_WriteEx()
* USB_BULK_WriteExTimed
* USB_BULK_WriteNULLPacket()
* USB_BULK_WriteTimed().
Chapter CDC:
* Added new functions:
* USB_CDC_CancelRead()
* USB_CDC_CancelWrite()
* USB_CDC_ReadTimed()
* USB_CDC_ReceiveTimed()
Updated indexes in chapter CDC, Bulk communication,
MSD, HID.
2.22 1 080917 SR/
SK
Added new chapter Combining different USB components
(Multi-Interface)
All chapter reviewed and cleaned up.
2.22 0 080902 SR
Chapter USB core:
* Added new function USB_EnableIAD.
Chapter Bulk communication:
* Update description of USB_BULK_Receive.
Chapter MSD component:
* Updated "Final configuration".
* Updated "Class specific configuration functions.
Chapter CDC component:
* Added new functions: USB_CDC_ReadOverlapped(),
USB_CDC_WriteOverlapped(), USB_CDC_WaitForRx,
USB_CDC_WaitForTx().
Chapter Target USB driver:
* Updated available driver list.
Chapter FAQ:
* Added new
15.0 0 080403 SR Update company’s address and legal form.
14.0 0 071204 SR
Chapter "Target USB driver":
* Updated "Writing your own driver":
- pfStallEP changed to pfSetClrStallEP.
- Added new driver ST STR91x.
- Added description for pfResetEP.
Chapter "Bulk Communication":
* Added new function: USB_BULK_Receive()
* Added new function:
USB_BULK_GetNumBytesInBuffer()
13.0 0 071005 SK Chapter "Target USB driver":
* Section "Interrupt handling" added.
12.0 0 070706 SR
Chapter "USB core":
* Changed USB_GetStastus to USB_GetState
Chapter "MSD":
* "MSD_Start.c" changed to
"MSD_Start_StorageRAM.c"
* Added information to
"USB_MSD_INST_DATA_DRIVER"
* "Storage drivers supplied with this release" updated.
Chapter "Bulk communication":
* Changed text for USBBULK_GetMode/Ex.
Software Revision Date By Description
6
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
11.0 0 070704 SK
Chapter "Introduction":
* HID section added.
Chapter "USB Core":
* USB_GetState() added.
Chapter "HID":
* USBHID_Init() updated.
Chapter "Target OS Interface":
* USB_OS_RestoreI() removed.
* USB_OS_DI() removed.
Chapter "Target USB Driver":
* STR750 added.
10.0 0 070618 SK
Chapter "HID" added.
Chapter "USB Core" added.
Chapter "Bulk communication":
* USB core functions removed.
Chapter "Introduction":
* Section "Development environment" added.
9.0 0 070123 SK
emUSB components renamed:
* "emUSB with bulk component" to "emUSB-Bulk"
* "emUSB with MSD component" to "emUSB-MSD"
* "emUSB with CDC component" to "emUSB-CDC"
Chapter "Introduction":
* updated and enhanced
* emUSB-CDC added
8.0 0 070121 SK
Product name changed from "USB-Stack" to "emUSB".
Various changes in layout and structure.
Chapter "About" added.
Chapter "Introduction":
* updated
* "emUSB structure" graphic added.
Chapter "Bulk communication":
* USB_SetClassRequestHook():
- Function description added.
Chapter "CDC":
* Head of description of USB_CDC_LINE_CODING
changed.
7.0 0 070109 SR Added new chapter CDC.
6.0 0 061221 SR
Added new USBBulk HOST-API function
USBBULK_SetUSBId().
Company description added
5.0 0 061220 SR
Changed chapter 1.1.1 USB-Bulk stack:
Info reg. availability of the Host-driver source.
Updated chapter title "Getting the target up"
Updated chapter 1.1.2.3 Features
Updated chapter 1 - Information of max. data transfer
rates updated.
4.0 0 061212 SR
Added chapter "Mass Storage Device"
Changed chapter Background info:
-Updated
Changed chapter title "Configuring the target" to "Getting
the target up"
Moved any related information of files provided with the
USB stack to "Getting the target up"
3.0 0 061120 SR Added the extended HOST API functionality to manual
2.0 0 061115 SR
Updated chapter:
Target USB driver
Bulk Communication
1.0 0 060808 OO Initial Version
Software Revision Date By Description
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
7
About this document
Assumptions
This document assumes that you already have a solid knowledge of the following:
The software tools used for building your application (assembler, linker, C com-
piler)
The C programming language
The target processor
DOS command line.
If you feel that your knowledge of C is not sufficient, we recommend The C Program-
ming Language by Kernighan and Richie (ISBN 0-13-1103628), which describes the
standard in C-programming and, in newer editions, also covers the ANSI C standard.
How to use this manual
This manual explains all the functions and macros that emUSB offers. It assumes you
have a working knowledge of the C language. Knowledge of assembly programming
is not required.
Typographic conventions for syntax
This manual uses the following typographic conventions:
Style Used for
Body Body text.
Keyword Text that you enter at the command-prompt or that appears on
the display (that is system functions, file- or pathnames).
Parameter Parameters in API functions.
Sample Sample code in program examples.
Sample comment Comments in program examples.
Reference Reference to chapters, sections, tables and figures or other docu-
ments.
GUIElement Buttons, dialog boxes, menu names, menu commands.
Emphasis Very important sections
Table 1.1: Typographic conventions
8
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
EMBEDDED SOFTWARE
(Middleware)
emWin
Graphics software and GUI
emWin is designed to provide an effi-
cient, processor- and display control-
ler-independent graphical user
interface (GUI) for any application that
operates with a graphical display.
embOS
Real Time Operating System
embOS is an RTOS designed to offer
the benefits of a complete multitasking
system for hard real time applications
with minimal resources.
embOS/IP
TCP/IP stack
embOS/IP a high-performance TCP/IP
stack that has been optimized for
speed, versatility and a small memory
footprint.
emFile
File system
emFile is an embedded file system with
FAT12, FAT16 and FAT32 support. Var-
ious Device drivers, e.g. for NAND and
NOR flashes, SD/MMC and Compact-
Flash cards, are available.
USB-Stack
USB device/host stack
A USB stack designed to work on any
embedded system with a USB control-
ler. Bulk communication and most stan-
dard device classes are supported.
SEGGER TOOLS
Flasher
Flash programmer
Flash Programming tool primarily for micro con-
trollers.
J-Link
JTAG emulator for ARM cores
USB driven JTAG interface for ARM cores.
J-Trace
JTAG emulator with trace
USB driven JTAG interface for ARM cores with
Trace memory. supporting the ARM ETM (Embed-
ded Trace Macrocell).
J-Link / J-Trace Related Software
Add-on software to be used with SEGGER’s indus-
try standard JTAG emulator, this includes flash
programming software and flash breakpoints.
SEGGER Microcontroller GmbH & Co. KG develops
and distributes software development tools and ANSI C
software components (middleware) for embedded sys-
tems in several industries such as telecom, medical
technology, consumer electronics, automotive industry
and industrial automation.
SEGGER’s intention is to cut software development time
for embedded applications by offering compact flexible and easy to use middleware,
allowing developers to concentrate on their application.
Our most popular products are emWin, a universal graphic software package for embed-
ded applications, and embOS, a small yet efficient real-time kernel. emWin, written
entirely in ANSI C, can easily be used on any CPU and most any display. It is comple-
mented by the available PC tools: Bitmap Converter, Font Converter, Simulator and
Viewer. embOS supports most 8/16/32-bit CPUs. Its small memory footprint makes it
suitable for single-chip applications.
Apart from its main focus on software tools, SEGGER develops and produces programming
tools for flash micro controllers, as well as J-Link, a JTAG emulator to assist in develop-
ment, debugging and production, which has rapidly become the industry standard for
debug access to ARM cores.
Corporate Office:
http://www.segger.com
United States Office:
http://www.segger-us.com
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
9
1 Introduction....................................................................................................................15
1.1 Overview................................................................................................16
1.2 emUSB features ......................................................................................16
1.3 emUSB components................................................................................. 17
1.3.1 emUSB-Bulk ........................................................................................... 18
1.3.1.1 Purpose of emUSB-Bulk............................................................................ 18
1.3.2 emUSB-MSD ...........................................................................................19
1.3.2.1 Purpose of emUSB-MSD ........................................................................... 19
1.3.2.2 Typical applications..................................................................................19
1.3.2.3 emUSB-MSD features...............................................................................19
1.3.2.4 How does it work? ...................................................................................19
1.3.3 emUSB-CDC ........................................................................................... 21
1.3.3.1 Typical applications..................................................................................21
1.3.4 emUSB-HID ............................................................................................ 22
1.3.4.1 Typical applications..................................................................................22
1.3.5 emUSB-MTP............................................................................................23
1.3.5.1 Typical applications..................................................................................23
1.3.6 emUSB-Printer ........................................................................................24
1.3.6.1 Typical applications..................................................................................24
1.3.7 emUSB-RNDIS ........................................................................................25
1.3.7.1 Typical applications..................................................................................25
1.4 Requirements..........................................................................................26
1.4.1 Target system.........................................................................................26
1.4.2 Development environment (compiler).........................................................26
1.5 File structure ..........................................................................................27
1.5.1 Bulk communication component ................................................................ 28
1.5.2 MSD component ......................................................................................28
1.5.3 CDC component ......................................................................................28
1.5.4 HID component .......................................................................................28
2 Background information.................................................................................................31
2.1 USB ....................................................................................................... 32
2.1.1 Short Overview ....................................................................................... 32
2.1.2 Important USB Standard Versions..............................................................32
2.1.3 USB System Architecture..........................................................................33
2.1.4 Transfer Types ........................................................................................35
2.1.5 Setup phase / Enumeration.......................................................................35
2.1.6 Product / Vendor IDs................................................................................35
2.2 Predefined device classes..........................................................................36
2.3 USB hardware analyzers ........................................................................... 36
2.4 References .............................................................................................36
3 Getting started ...............................................................................................................37
3.1 How to setup your target system ............................................................... 39
3.1.1 Upgrade a trial version available on the web with source code. ......................39
3.1.2 Upgrading an embOS Start project............................................................. 40
3.1.3 Creating a project from scratch .................................................................42
3.2 Select the start application........................................................................43
3.3 Build the project and test it.......................................................................43
3.4 Configuration ..........................................................................................44
Table of Contents
10
User & reference ma nual for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
3.4.1 General emUSB configuration functions ...................................................... 45
3.4.2 Additional required configuration functions for emUSB-MSD .......................... 50
3.4.3 Descriptors............................................................................................. 50
4 USB Core.......................................................................................................................51
4.1 Overview ............................................................................................... 52
4.2 Target API.............................................................................................. 53
4.2.1 USB basic functions ................................................................................. 54
4.2.2 USB configuration functions ...................................................................... 61
4.2.3 USB control functions .............................................................................. 70
4.2.4 USB IAD functions................................................................................... 72
4.2.5 USB Remote wakeup functions.................................................................. 73
5 Bulk communication.......................................................................................................77
5.1 Generic bulk stack................................................................................... 78
5.2 The Kernel mode driver (PC)..................................................................... 78
5.2.1 Why is a driver necessary? ....................................................................... 78
5.2.2 Supported platforms................................................................................ 78
5.3 Installing the driver ................................................................................. 78
5.3.1 Recompiling the driver ............................................................................. 81
5.3.2 The .inf file............................................................................................. 82
5.3.3 Configuration.......................................................................................... 83
5.4 Example application................................................................................. 84
5.4.1 Running the example applications.............................................................. 85
5.4.2 Compiling the PC example application ........................................................ 87
5.5 Target API.............................................................................................. 88
5.5.1 Target interface function list ..................................................................... 89
5.5.2 USB-Bulk functions.................................................................................. 90
5.5.3 Data structures......................................................................................111
5.6 Host API ...............................................................................................113
5.6.1 Host API list ..........................................................................................114
5.6.2 USB-Bulk Basic functions.........................................................................116
5.6.3 USB-Bulk direct input/output functions......................................................120
5.6.4 USB-Bulk Control functions......................................................................126
6 Bulk Host API V2 .........................................................................................................143
6.1 Bulk Host API V2....................................................................................144
6.1.1 Bulk Host API V2 list...............................................................................145
6.1.2 USB-Bulk Basic functions.........................................................................147
6.1.3 USB-Bulk direct input/output functions......................................................152
6.1.4 USB-Bulk Control functions......................................................................159
6.1.4.1 USBBULK_GetConfigDescriptor() ..............................................................159
6.1.5 Data structures......................................................................................182
7 Mass Storage Device Class (MSD) ............................................................................183
7.1 Overview ..............................................................................................184
7.2 Configuration.........................................................................................185
7.2.1 Initial configuration ................................................................................185
7.2.2 Final configuration..................................................................................185
7.2.3 Class specific configuration functions ........................................................185
7.2.4 Running the example application ..............................................................190
7.2.4.1 MSD_Start_StorageRAM.c in detail ...........................................................190
7.3 Target API.............................................................................................191
7.3.1 API functions .........................................................................................192
7.3.2 Extended API functions ...........................................................................199
7.3.3 Data structures......................................................................................205
7.4 Storage Driver .......................................................................................214
7.4.1 General information................................................................................214
7.4.1.1 Supported storage types .........................................................................214
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller Systeme GmbH
11
7.4.1.2 Storage drivers supplied with this release ................................................. 214
7.4.2 Interface function list ............................................................................. 214
7.4.3 USB_MSD_STORAGE_API in detail ........................................................... 215
8 Media Transfer Protocol Class (MTP)..........................................................................223
8.1 Overview.............................................................................................. 224
8.1.1 Getting access to files ............................................................................ 225
8.1.2 Additional information ............................................................................ 227
8.2 Configuration ........................................................................................ 228
8.2.1 Initial configuration................................................................................ 228
8.2.2 Final configuration ................................................................................. 228
8.2.3 Class specific configuration ..................................................................... 228
8.2.4 Compile time configuration ..................................................................... 233
8.3 Running the sample application ............................................................... 233
8.3.1 USB_MTP_Start.c in detail ...................................................................... 233
8.4 Target API ............................................................................................ 235
8.4.1 API functions ........................................................................................ 235
8.4.2 Data structures ..................................................................................... 238
8.5 Storage Driver ...................................................................................... 245
8.5.1 General information ............................................................................... 245
8.5.2 Interface function list ............................................................................. 245
8.5.3 USB_MTP_STORAGE_API in detail ............................................................ 246
9 Communication Device Class (CDC)...........................................................................267
9.1 Overview.............................................................................................. 268
9.1.1 Configuration ........................................................................................ 268
9.2 The example application ......................................................................... 269
9.3 Installing the driver ............................................................................... 270
9.3.1 The .inf file ........................................................................................... 273
9.3.2 Installation verification ........................................................................... 274
9.3.3 Testing communication to the USB device ................................................. 275
9.4 Target API ............................................................................................ 278
9.4.1 Interface function list ............................................................................. 279
9.4.2 API functions ........................................................................................ 280
9.4.3 Data structures ..................................................................................... 301
10 Human Interface Device Class (HID).........................................................................307
10.1 Overview.............................................................................................. 308
10.1.1 Further reading ..................................................................................... 308
10.1.2 Categories ............................................................................................ 309
10.1.2.1 True HIDs............................................................................................. 309
10.1.2.2 Vendor specific HIDs .............................................................................. 309
10.2 Background information ......................................................................... 310
10.2.1 HID descriptors ..................................................................................... 310
10.2.1.1 HID descriptor....................................................................................... 310
10.2.1.2 Report descriptor................................................................................... 310
10.2.1.3 Physical descriptor................................................................................. 311
10.3 Configuration ........................................................................................ 312
10.3.1 Initial configuration................................................................................ 312
10.3.2 Final configuration ................................................................................. 312
10.4 Example application ............................................................................... 313
10.4.1 HID_Mouse.c ........................................................................................ 313
10.4.1.1 Running the example ............................................................................. 313
10.4.2 HID_Echo1.c......................................................................................... 314
10.4.2.1 Running the example ............................................................................. 314
10.4.2.2 Compiling the PC example application ...................................................... 315
10.5 Target API ............................................................................................ 316
10.5.1 Target interface function list.................................................................... 316
10.5.2 USB-HID functions................................................................................. 317
10.5.3 Data structures ..................................................................................... 330
12
User & reference ma nual for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
10.6 Host API ...............................................................................................331
10.6.1 Host API function list ..............................................................................332
10.6.2 USB-HID functions .................................................................................333
11 Printer Class ..............................................................................................................345
11.1 Overview ..............................................................................................346
11.1.1 Configuration.........................................................................................346
11.2 The example application..........................................................................347
11.3 Target API.............................................................................................350
11.3.1 Interface function list..............................................................................350
11.3.2 API functions .........................................................................................351
11.3.3 Data structures......................................................................................353
12 Remote NDIS (RNDIS)..............................................................................................355
12.1 Overview ..............................................................................................356
12.1.1 Working with RNDIS ...............................................................................356
12.1.2 Additional information.............................................................................357
12.2 Configuration........................................................................................358
12.2.1 Initial configuration ................................................................................358
12.2.2 Final configuration..................................................................................358
12.2.3 Class specific configuration ......................................................................358
12.2.4 Compile time configuration ......................................................................362
12.3 Running the sample application................................................................363
12.3.0.1 IP_Config_RNDIS.c in detail.....................................................................363
12.4 RNDIS + embOS/IP as a "USB Webserver" ................................................365
12.5 Target API.............................................................................................366
12.5.1 API functions .........................................................................................367
12.5.1.1 USB_RNDIS_Add() .................................................................................367
12.5.1.2 USB_RNDIS_Task() ................................................................................368
12.5.2 Data structures......................................................................................369
12.5.2.1 USB_RNDIS_INIT_DATA .........................................................................369
12.5.2.2 USB_RNDIS_EVENT_API .........................................................................370
12.5.2.3 USB_RNDIS_DRIVER_API........................................................................371
(*pfInit)() .............................................................................................372
(*pfGetPacketBuffer)()............................................................................372
(*pfWritePacket)() .................................................................................372
(*pfSetPacketFilter)() .............................................................................373
(*pfGetLinkStatus)() ..............................................................................373
(*pfGetLinkSpeed)()...............................................................................373
(*pfGetHWAddr)()..................................................................................374
(*pfGetStats)()......................................................................................375
(*pfGetMTU)() .......................................................................................376
(*pfReset)() ..........................................................................................376
12.5.2.4 USB_RNDIS_DRIVER_DATA.....................................................................377
(*pfCreate)().........................................................................................378
(*pfSignal)() .........................................................................................378
(*pfWaitTimed)() ...................................................................................379
13 Combining different USB components (Multi-Interface). ............................................381
13.1 Overview ..............................................................................................382
13.1.1 Single interface device classes .................................................................383
13.1.2 Multiple interface device classes ...............................................................384
13.1.3 IAD class ..............................................................................................384
13.2 Configuration.........................................................................................385
13.3 How to combine .....................................................................................386
13.4 emUSB component specific modification ....................................................388
13.4.1 BULK communication component..............................................................388
13.4.1.1 Device side............................................................................................388
13.4.1.2 Host side ..............................................................................................388
13.4.2 MSD component.....................................................................................390
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller Systeme GmbH
13
13.4.2.1 Device side ........................................................................................... 390
13.4.2.2 Host side .............................................................................................. 390
13.4.3 CDC component .................................................................................... 390
13.4.3.1 Device side ........................................................................................... 390
13.4.3.2 Host side .............................................................................................. 390
13.4.4 HID component ..................................................................................... 392
13.4.4.1 Device side ........................................................................................... 392
13.4.4.2 Host side .............................................................................................. 392
14 Target OS Interface ...................................................................................................393
14.1 General information ............................................................................... 394
14.1.1 Operating system support supplied with this release................................... 394
14.2 Interface function list ............................................................................. 395
14.3 Example ............................................................................................... 405
15 Target USB Driver......................................................................................................409
15.1 General information ............................................................................... 410
15.1.1 Available USB drivers ............................................................................. 410
15.2 Adding a driver to emUSB....................................................................... 412
15.3 Interrupt handling ................................................................................. 415
15.3.1 ARM7 / ARM9 based cores ...................................................................... 415
15.3.1.1 ARM specific IRQ handler ........................................................................ 416
15.3.1.2 Device specifics ATMEL AT91CAP9x .......................................................... 417
15.3.1.3 Device specifics ATMEL AT91RM9200........................................................ 417
15.3.1.4 Device specifics ATMEL AT91SAM7A3 ....................................................... 417
15.3.1.5 Device specifics ATMEL AT91SAM7S64, AT91SAM7S128, AT91SAM7S256...... 417
15.3.1.6 Device specifics ATMEL AT91SAM7X64, AT91SAM7X128, AT91SAM7X256...... 417
15.3.1.7 Device specifics ATMEL AT91SAM7SE ....................................................... 417
15.3.1.8 Device specifics ATMEL AT91SAM9260...................................................... 417
15.3.1.9 Device specifics ATMEL AT91SAM9261...................................................... 417
15.3.1.10 Device specifics ATMEL AT91SAM9263...................................................... 418
15.3.1.11 Device specifics ATMEL AT91SAMRL64, AT91SAMR64 ................................. 418
15.3.1.12 Device specifics NXP LPC214x ................................................................. 419
15.3.1.13 Device specifics NXP LPC23xx.................................................................. 419
15.3.1.14 Device specifics NXP (formerly Sharp) LH79524/5...................................... 419
15.3.1.15 Device specifics OKI 69Q62..................................................................... 419
15.3.1.16 Device specifics ST STR71x ..................................................................... 419
15.3.1.17 Device specifics ST STR750..................................................................... 419
15.3.1.18 Device specifics ST STR750..................................................................... 419
15.4 Writing your own driver.......................................................................... 420
15.4.1 USB initialization functions...................................................................... 422
15.4.2 General USB functions............................................................................ 423
15.4.3 General endpoint functions ..................................................................... 425
15.4.4 Endpoint 0 (control endpoint) related functions.......................................... 428
15.4.5 OUT-endpoint functions .......................................................................... 429
15.4.6 IN-endpoint functions............................................................................. 430
15.4.7 USB driver interrupt handling .................................................................. 432
16 Support ......................................................................................................................433
16.1 Problems with tool chain (compiler, linker)................................................ 434
16.1.1 Compiler crash ...................................................................................... 434
16.1.2 Compiler warnings ................................................................................. 434
16.1.3 Compiler errors ..................................................................................... 434
16.1.4 Linker problems .................................................................................... 434
16.2 Problems with hardware/driver................................................................ 435
16.3 Contacting support ................................................................................ 435
17 Certification................................................................................................................437
17.1 What is the Windows Logo Certification and why
14
User & reference ma nual for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
do I need it?438
17.2 Certification offer ...................................................................................439
17.3 Vendor and Product ID............................................................................439
17.4 Certification without SEGGER Microcontroller .............................................439
18 Performance & resource usage.................................................................................441
18.1 Memory footprint ...................................................................................442
18.1.1 ROM .....................................................................................................442
18.1.2 RAM .....................................................................................................442
18.2 Performance..........................................................................................443
19 FAQ............................................................................................................................445
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
15
Chapter 1
Introduction
This chapter will give a short introduction to emUSB, covering generic bulk, Mass
Storage Device (MSD), Communication Device Class (CDC), Human Interface Device
(HID), Media Transfer Protocol (MTP) class, Printer Class and Remote Network Driver
Interface Specification (RNDIS) class functionality. Host and target requirements are
covered as well.
16 CHAPTER 1 Introduction
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
1.1 Overview
This guide describes how to install, configure and use emUSB. It also explains the
internal structure of emUSB.
emUSB has been designed to work on any embedded system with a USB client con-
troller. It can be used with USB 1.1 or USB 2.0 devices.
The highest possible transfer rate on USB 2.0 full speed (12 Mbit/second) devices is
approximately 1 Mbyte per second. This data rate can indeed be achieved on fast
systems, such as Cortex-M devices running at 48 MHz and above.
USB 2.0 high speed mode (480 MBit/second) is also fully supported and is automati-
cally handled. Using USB high speed mode with an ARM9 or faster could achieve val-
ues of approx. 18 MBytes/second and faster.
The USB standard defines four types of communication: Control, isochronous, inter-
rupt, and bulk. Experience shows, that for most embedded devices the bulk mode is
the communication mode of choice because applications can utilize the full bandwidth
of the Universal Serial Bus.
1.2 emUSB features
Key features of emUSB are:
•High speed.
Can be used with or without an RTOS.
•Easy to use.
•Easy to port.
No custom USB host driver necessary.
Start / test application supplied.
Highly efficient, portable, and commented ANSI C source code.
Hardware abstraction layer allows rapid addition of support for new devices.
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
17
1.3 emUSB components
emUSB consists of three layers: A driver for hardware access, the emUSB core and at
least a USB class driver or the bulk communication component.
The different available hardware drivers, the USB class drivers, and the bulk commu-
nication component are additional packages, which can be combined and ordered as
they fit to the requirements of your project. Normally, emUSB consists of a driver
that fits to the used hardware, the emUSB core and at least one of the USB class
drivers.
Component Description
USB protocol layer
Bulk emUSB bulk component.
(emUSB-Bulk)
MSD emUSB Mass Storage Device class component.
(emUSB-MSD).
CDC emUSB Communication Device Class component.
(emUSB-CDC)
HID emUSB Human Interface Device Class component.
(emUSB-HID)
MTP emUSB Media Transfer Protocol component.
(emUSB-MTP)
Printer emUSB Printer Class component.
(emUSB-Printer)
RNDIS emUSB RNDIS component.
(emUSB-RNDIS)
Core layer
emUSB-Core The emUSB core is the intrinsic USB stack.
Hardware layer
Driver USB controller driver.
Table 1.1: emUSB components
18 CHAPTER 1 Introduction
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
1.3.1 emUSB-Bulk
The emUSB-Bulk stack consists of an embedded side, which is shipped as source
code, and a driver for the PC, which is typically shipped as an executable (.sys).
(The source of the PC driver can also be ordered.)
1.3.1.1 Purpose of emUSB-Bulk
emUSB-Bulk allows you to quickly and smoothly develop software for an embedded
device that communicates with a PC via USB. The communication is like a single,
high-speed, reliable channel (very similar to a TCP connection). This bidirectional
channel, with built-in flow control, allows the PC to send data to the embedded tar-
get, the embedded target to receive these bytes and reply with any number of bytes.
The PC is the USB host, the target is the USB client.
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
19
1.3.2 emUSB-MSD
1.3.2.1 Purpose of emUSB-MSD
Access the target device like an ordinary disk drive
emUSB-MSD enables the use of an embedded target device as a USB mass storage
device. The target device can be simply plugged-in and used like an ordinary disk
drive, without the need to develop a driver for the host operating system. This is pos-
sible because the mass storage class is one of the standard device classes, defined
by the USB Implementers Forum (USB IF). Virtually every major operating system on
the market supports these device classes out of the box.
No custom host drivers necessary
Every major OS already provides host drivers for USB mass storage devices, there is
no need to implement your own. The target device will be recognized as a mass stor-
age device and can be accessed directly.
Plug and Play
Assuming the target system is a digital camera using emUSB-MSD, videos or photos
taken by this camera can be conveniently accessed with the file system explorer of
the used operating system when the camera is connected to the computer.
1.3.2.2 Typical applications
Typical applications are:
•Digital camera
•USB stick
•MP3 player
•DVD player
Any target with USB interface: easy access to configuration and data files.
1.3.2.3 emUSB-MSD features
Key features of emUSB-MSD are:
Can be used with RAM, parallel flash, serial flash or mechanical drives
Support for full speed (12 Mbit/second) and high speed (480 Mbit/second) trans-
fer rates
OS-abstraction: Can be used with any RTOS, but no OS is required for MSD-only
devices
1.3.2.4 How does it work?
Use file system support from host OS
A device which uses emUSB-MSD will be recognized as a mass storage device and
can be used like an ordinary disk drive. If the device is unformatted when plugged-in,
the host operating system will ask you to format the device. Any file system provided
by the host can be used. Typically FAT is used, but other file systems such as NTFS
are possible too. If one of those file systems is used, the host is able to read from
and write to the device using the storage functions of the emUSB MSD component,
which define unstructured read and write operations. Thus, there is no need to
develop extra file system code if the application only accesses data on the target
from the host side. This is typically the case for simple storage applications, such as
USB memory sticks or ATA to USB bridges.
Only provide file system code on the target if necessary
Mass storage devices like USB sticks do not require their own file system implemen-
tation. File system program code is only required if the application running on the
target device has to access the stored data. The development of a file system is a
20 CHAPTER 1 Introduction
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
complex and time-consuming task and increases the time-to market. Thus we recom-
mend the use of a commercial file system like emFile, SEGGER’s file system for
embedded applications. emFile is a high performance library that is optimized for
minimum memory consumption in RAM and ROM, high speed and versatility. It is
written in ANSI C and runs on any CPU and on any media. Refer to www.segger.com/
emfile.html for more information about emFile.
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
21
1.3.3 emUSB-CDC
emUSB-CDC converts the target device into a serial communication device. A target
device running emUSB-CDC is recognized by the host as a serial interface
(USB2COM, virtual COM port), without the need to install a special host driver,
because the communication device class is one of the standard device classes and
every major operating system already provides host drivers for those device classes.
All PC software using a COM port will work without modifications with this virtual
COM port.
1.3.3.1 Typical applications
Typical applications are:
•Modem
Telephone system
•Fax machine
22 CHAPTER 1 Introduction
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
1.3.4 emUSB-HID
The Human Interface Device class (HID) is an abstract USB class protocol defined by
the USB Implementers Forum. This protocol was defined for handling devices that
humans use to control the operation of computer systems.
An installation of a custom host USB driver is not necessary because the USB human
interface device class is standardized and every major OS already provides host driv-
ers for it.
1.3.4.1 Typical applications
Typical examples
•Keyboard
Mouse and similar pointing devices
•Game pad
Front-panel controls - for example, switches and buttons.
Bar-code reader
Thermometer
•Voltmeter
Low-speed JTAG emulator
Uninterruptible power supply (UPS)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
23
1.3.5 emUSB-MTP
The Media Transfer Protocol (MTP) is a USB class protocol which can be used to trans-
fer files to and from storage devices. MTP is an alternative to MSD as it operates on a
file level rather than on a storage sector level.
The advantage of MTP is the ability to access the storage medium from the host PC
and from the device at the same time.
Because MTP works ath the file level this also eliminates the risk of damaging the file
system when the communication to the host has been canceled unexpectedly (e.g.
the cable was removed).
MTP is supported by most operating systems without the need to install third-party
drivers.
1.3.5.1 Typical applications
Typical applications are:
•Digital camera
•USB stick
•MP3 player
•DVD player
Telephone
Any target with USB interface: easy access to configuration and data files.
24 CHAPTER 1 Introduction
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
1.3.6 emUSB-Printer
emUSB-Printer converts the target device into a printing device. A target device run-
ning emUSB-Printer is recognized by the host as a printer. Unless the device identi-
fies itself as a printer already recognized by the host PC, you must install a driver to
be able to communicate with the USB device.
1.3.6.1 Typical applications
Typical applications are:
Laser/Inkjet printer
•CNC machine
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
25
1.3.7 emUSB-RNDIS
emUSB-RNDIS allows to create a virtual Ethernet adapter through which the host PC
can communicate with the device using the Internet protocol suite (TCP, UDP, FTP,
HTTP, Telnet). This allows the creation of USB based devices which can host a web-
server or act as a telnet terminal or a FTP server. emUSB-RNDIS offer a unique cus-
tomer experience and allows to save development and hardware cost by e.g. using a
website as a user interface instead of creating an application for every major OS and
by eliminating the Ethernet hardware components from your device.
1.3.7.1 Typical applications
Typical applications are:
USB-Webserver
USB-Terminal (e.g. Telnet)
•USB-FTP-Server
26 CHAPTER 1 Introduction
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
1.4 Requirements
1.4.1 Target system
Hardware
The target system must have a USB controller. The memory requirements are
approximately 6 Kbytes ROM for the emUSB-Bulk stack or 10 Kbytes ROM for
emUSB-Bulk and emUSB-MSD and approximately 1 Kbytes of RAM (only used for
buffering). Additionally memory for data storage is required, typically either on-
board flash memory (parallel or serial) or an external flash memory card is required.
In order to have the control when the device shall be enumerated by the host, a swit-
chable attach is necessary. This is a switchable pull-up connected to the D+-Line of
USB.
Software
emUSB is optimized to be used with embOS but works with any other supported
RTOS or without an RTOS in a superloop. For information regarding the OS integra-
tion refer to Target OS Interface on page 393.
1.4.2 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/ANSI 9899:1990 (C90) with support for C++ style comments (//)
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; most 8-bit compilers can be used as well.
A C++ compiler is not required, but can be used. The application program can there-
fore also be programmed in C++ if desired.
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
27
1.5 File structure
The following table shows the contents of the emUSB root directory:
Depending on the chosen emUSB component, the following additional subdirectories
are available:
Directory Contents
Application
Contains the application program. Depending on which stack is
used, several files are available for each stack. Detailed infor-
mation can be found in the corresponding chapter.
Config Contains configuration files (USB_Conf.h, Config_xxx.h, where
xxx describes the driver that is used.).
Doc Contains the emUSB documentation.
Hardware
Contains a simple implementation of the required hardware
interface routines. Full implementation of the hardware routine
for several CPU and eval board can be found on the SEGGER’s
website: http://www.segger.com
Inc Contains include files.
OS Contains operating systems dependent files which allows to run
emUSB with different RTOS’s.
USB Contains the emUSB source code.
Note: Do not change the source code in this directory.
Table 1.2: Supplied directory structure of emUSB core package
28 CHAPTER 1 Introduction
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
1.5.1 Bulk communication component
1.5.2 MSD component
1.5.3 CDC component
1.5.4 HID component
Directory Contents
Bulk\Windows-
Driver
Contains the kernel mode USB driver for the PC (Win32, NT
platform), the compiled driver (.sys). the .inf file required for
installation. The source code of the Windows driver is included,
if a source code version of emUSB-Bulk has been ordered.
Bulk\Sam-
pleApp
Contains a PC sample project to help you bring up and test the
system.
USB\Bulk Includes all files that are necessary for the generic bulk commu-
nication.
Table 1.3: Additional subdirectories for emUSB bulk communication component
Directory Contents
USB\MSD
Contains all files that handle the specific USB-MSD commands.
Different storage drivers, such as a RAM storage device driver or
emFile device driver are also available.
Table 1.4: Additional subdirectories for emUSB MSD component
Directory Contents
CDC
The driver installation file (USBser.inf) located in this directory
can be used to install the USB-CDC device (Virtual COM-Port) on
> Windows 2000 platforms.
USB\CDC Contains all files specific for the USB-CDC communication.
Table 1.5: Additional subdirectories for emUSB CDC component
Directory Contents
HID\SampleApp Contains a PC sample project to help you bring up and test the
system.
USB\HID Includes all files that are necessary for the HID component.
Table 1.6: Additional subdirectories for emUSB HID communication component
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
29
30 CHAPTER 1 Introduction
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
31
Chapter 2
Background information
This is a short introduction to USB. The fundamentals of USB are explained and links
to additional resources are given.
Information provided in this chapter is not required to use the software.
32 CHAPTER 2 Background information
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontro ller GmbH & Co. KG
2.1 USB
2.1.1 Short Overview
The Universal Serial Bus (USB) is a bus architecture for connecting multiple peripher-
als to a host computer. It is an industry standard — maintained by the USB Imple-
menters 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 already mentioned hot-
plug capability 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 did not only lead to broad market acceptance, but it also added sev-
eral 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.
2.1.2 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 Mbytes/second for low speed and 12 Mbytes/second
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 Mbytes/second (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.
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
33
2.1.3 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 host controller driver (HCD) which provides the functionality of the host con-
troller hardware.
The USB Driver (USBD) Layer which implements the high level functions used by
USB device drivers in terms of the functionality provided by the HCD.
The USB Device drivers which establish connections to USB devices. The driver
classes are also located here and provide generic access to certain types of
devices such as printers or mass storage devices.
34 CHAPTER 2 Background information
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontro ller GmbH & Co. KG
USB Device
Two types of devices exist: hubs and functions. Hubs provide for 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. A USB device must be configured by the host before its
functions can be used. 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 an embedded device uses emUSB-MSD, the embedded
device will appear as a USB mass storage device, and the host OS provides the driver
out of the box. In general, there is no need to develop a custom driver to communi-
cate with target devices that use one of the USB class protocols.
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 the device supports. 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.
As can be seen, the descriptors form a tree. The root is the device descriptor with n
configuration descriptors as children, each of which has m interface descriptors which
in turn have o endpoint descriptors each.
Device
descriptor
Configuration
descriptor
Interface
descriptor
Endpoint
descriptor
1...n configuration descriptors
1...m interface descriptors
1...o endpoint descriptors
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
35
2.1.4 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 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 con-
stant 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
bursty quantities. Bulk transfer has wide dynamic latitude in transmission con-
straints. 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 typi-
cally 90% or more of the bandwidth available for USB transfers.
2.1.5 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, which are in the configurable section
of the USB-MSD stack. 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 client. This part of the setup is called enumeration.
2.1.6 Product / Vendor IDs
The Product and Vendor IDs are necessary to identify the USB device. The Product ID
describes a specific device type and does not need to be unique between different
devices of the same type. USB host systems like Windows use the Product ID/Vendor
ID combination to identify which drivers are needed.
For example: all our J-Link v8 devices have the Vendor ID 0x1366 and Product ID
0x0101.
A Vendor and Product ID is necessary only when development of the product is fin-
ished; during the development phase, the supplied Vendor and Product IDs can be
used as samples.
Possible options to obtain a Vendor ID or Product ID are described in the chapter
Vendor and Product ID on page 439.
36 CHAPTER 2 Background information
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontro ller GmbH & Co. KG
2.2 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.
Device classes provide a standardized way of communication between host and
device and typically work with a class driver which comes with the host operating
system.
Using a predefined device class where applicable minimizes the amount of work to
make a device usable on different host systems.
emUSB-Device supports the following device classes:
Mass Storage Device Class (MSD)
Human Interface Device Class (HID)
Communication Device Class (CDC)
Printer Device Class (PDC)
2.3 USB hardware analyzers
A variety of USB hardware analyzers are on the market with different capabilities.
If you are developing an application using USB, it should not be necessary to have a
USB analyzer, but we still recommend you do.
Simple yet powerful USB-Analyzers are available for less than $1000.
2.4 References
For additional information see the following documents:
Universal Serial Bus Specification, Revision 2.0
Universal Serial Bus Mass Storage Class Specification Overview, Rev 1.2
UFI command specification: USB Mass Storage Class, UFI Command Specifica-
tion, Rev 1.0
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
37
Chapter 3
Getting started
The first step in getting emUSB up and running is typically to compile it for the target
system and to run it in the target system. This chapter explains how to do this.
38 CHAPTER 3 Getting started
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
39
3.1 How to setup your target system
To get the USB up and running, 3 possible ways currently available:
Upgrade a trial version available on the web with source code.
Upgrading an embOS Start project
Creating a project from scratch.
3.1.1 Upgrade a trial version available on the web with source
code.
Simply download a trial package available from the SEGGER website.
After downloading, extract the trial project and open the workspace/project file which
is located in the start folder.
The source files in the USB folder from the emUSB shipment shall be copied into the
40 CHAPTER 3 Getting started
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
USB folder of the trial package.
Afterwards the project needs to be updated by adding the source files into the
project.
3.1.2 Upgrading an embOS Start project
Integrating emUSB
The emUSB default configuration is preconfigured with valid values, which matches
the requirements of the most applications. emUSB 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 into this project.
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 IAR
Embedded Workbench® IDE is used for all examples and screenshots, but every
other ANSI C toolchain can also be used. It is also possible to use make files; in this
case, when we say “add to the project, this translates into “add to the make file”.
Procedure to follow
Integration of emUSB is a relatively simple process, which consists of the following
steps:
Step 1: Open an embOS project and compile it.
Step 2: Add emUSB to the start project
Step 3: Compile the project
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
41
Step 1: Open an embOS start project
We recommend that you use one of the supplied embOS start projects for your target
system. Compile the project and run it on your target hardware.
Step 2: Adding emUSB to the start project
Add all source files in the following directory to your project:
Config
USB
UTIL (optional)
The Config folder includes all configuration files of emUSB. The configuration files
are preconfigured with valid values, which match the requirements of most applica-
tions. Add the hardware configuration USB_Config_<TargetName>.c supplied with
the driver shipment.
If your hardware is currently not supported, use the example configuration file and
the driver template to write your own driver. The example configuration file and the
driver template is located in the Sample\Driver\Template folder.
The Util folder is an optional component of the emUSB shipment. It contains opti-
mized MCU and/or compiler specific files, for example a special memcopy function.
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 direc-
tory 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
USB
42 CHAPTER 3 Getting started
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
3.1.3 Creating a project from scratch
To get the target system to behave like a mass storage device or generic bulk device
on the USB bus, a few steps have to be taken:
A project or make file has to be created for the used toolchain.
The configuration may need to be adjusted.
The hardware routines for the USB controller have to be implemented.
Add the path of the required USB header files to the include path.
To get the target up and running is a lot easier if a USB chip is used for which a tar-
get hardware driver is already available. In that case, this driver can be used.
Creating the project or make file
The screenshot below gives an idea about a possible project setup.
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
43
3.2 Select the start application
For quick and easy testing of your emUSB integration, start with the code found in
the folder Application. Add USB_HID_Mouse.c as your applications to your project.
3.3 Build the project and test it
Build the project. It should compile without errors and warnings. If you encounter
any problem during the build process, check your include path and your project con-
figuration settings. To test the project, download the output into your target and
start the application.
After connecting the USB cable to the target device, the mouse pointer should hop
from left to right.
44 CHAPTER 3 Getting started
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
3.4 Configuration
An application using emUSB must contain the following functions:
These functions are included in the every example application. The functions could be
used without modifications in the development phase of your application, but you
may not bring a product on the market without modifying the information like vendor
Id and product Id.
Function Description
General emUSB configuration functions
USB_GetVendorId() Should return the vendor Id of the target.
USB_GetProductId() Should return the product Id of the target.
USB_GetVendorName() Should return the manufacturer name.
USB_GetProductName() Should return the product Id of the target.
USB_GetSerialNumber() Should return the manufacturer name.
Additional require d configuration functions for emUSB-MSD
USB_MSD_GetVendorName() Should return the vendor name.
USB_MSD_GetProductVer() Should return the product version.
USB_MSD_GetSerialNo() Should return the serial number.
Table 3.1: Functions that are required in emUSB applications
Ids Description
Default vendor Id for all applications
0x8765 Example vendor Id for all examples.
Used prod uc t I ds
0x1234 Example product Id for all bulk samples.
0x1000 Example product Id for all MSD samples.
0x1200 Example product Id for the MSD CD-ROM sam-
ple.
0x1111 Example product Id for all CDC samples.
0x1112 Example product Id for HID mouse sample.
0x1114 Example product Id for the vendor specific HID
sample.
0x2114 Example product Id for the Printer class sam-
ple.
Table 3.2: List of used product and vendor Ids
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
45
3.4.1 General emUSB configuration functions
3.4.1.1 USB_GetVendorId()
Description
Should return the vendor Id of the target.
Prototype
U16 USB_GetVendorId(void);
Example
U16 USB_GetVendorId(void) {
return 0x8765;
}
Additional information
The vendor Id is assigned by the USB Implementers Forum (www.usb.org). For tests,
the default number above (or pretty much any other number) can be used. However,
you may not bring a product to market without having been assigned your own ven-
dor Id.
For emUSB-Bulk and emUSB-CDC: If you change this value, do not forget to make
the same change to the .inf file as described in section The .inf file on page 82 or
The .inf file on page 273. Otherwise, the Windows host will be unable to locate the
driver.
46 CHAPTER 3 Getting started
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
3.4.1.2 USB_GetProductId()
Description
Should return the product Id of the target.
Prototype
U16 USB_GetProductId(void);
Example
U16 USB_GetProductId(void) {
return 0x1111;
}
Additional information
The product Id in combination with the vendor Id creates a worldwide unique identi-
fier. For tests, you can use the default number above (or pretty much any other num-
ber).
For emUSB-Bulk and emUSB-CDC: If you change this value, do not forget to make
the same change to the .inf file as described in section The .inf file on page 82 or
The .inf file on page 273. Otherwise, the Windows host will be unable to locate the
driver.
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
47
3.4.1.3 USB_GetVendorName()
Description
Should return the manufacturer name.
Prototype
const char * USB_GetVendorName(void);
Example
const char * USB_GetVendorName(void) {
return "Vendor";
}
Additional information
The manufacturer name is used during the enumeration phase. The product name
and the serial number should together give a detailed information about which device
is connected to the host.
48 CHAPTER 3 Getting started
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
3.4.1.4 USB_GetProductName()
Description
Should return the product name.
Prototype
const char * USB_GetProductName(void);
Example
const char * USB_GetProductName(void) {
return "Bulk device";
}
Additional information
The product name is used during the enumeration phase. The manufacturer name
and the serial number should together give a detailed information about which device
is connected to the host.
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
49
3.4.1.5 USB_GetSerialNumber()
Description
Should return the serial number.
Prototype
const char * USB_GetSerialNumber(void);
Example
const char * USB_GetSerialNumber(void) {
return "12345678";
}
Additional information
The serial number is used during the enumeration phase. The manufacturer and the
product name should together give a detailed information to the user about which
device is connected to the host.
50 CHAPTER 3 Getting started
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
3.4.2 Additional required configuration functions for emUSB-
MSD
Refer to Configuration on page 185 for more information about the required addi-
tional configuration functions for emUSB-MSD.
3.4.3 Descriptors
All configuration descriptors are automatically generated by emUSB and do not
require configuration.
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
51
Chapter 4
USB Core
This chapter describes the basic functions of the USB Core.
52 CHAPTER 4 USB Core
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
4.1 Overview
This chapter describes the functions of the core layer of USB Core. This functions are
required for all USB class drivers and the unclassified bulk communication compo-
nent.
General information
To communicate with the host, the example application project includes a USB-spe-
cific header USB.h and one of the USB libraries (or instead of the libraries the source
files, if you have a source version of USB Core). These libraries contain API functions
to communicate with the USB host through the USB Core driver.
Every application using USB Core must perform the following steps:
1. Initialize the USB stack. To initialize the USB stack USB_Init() has to be called.
USB_Init() performs the low-level initialization of the USB stack and calls
USB_X_AddDriver() to add a driver to the USB stack.
2. Add communication endpoints. You have to add the required endpoints with the
compatible transfer type for the desired interface before you can use any of the
USB class drivers or the unclassified bulk communication component.
For the emUSB bulk component, refer to USB_BULK_INIT_DATA on page 111 for
information about the initialization structure that is required when you want to
add a bulk interface.
For the emUSB MSD component, refer to USB_MSD_INIT_DATA on page 205 and
USB_MSD_INST_DATA on page 207 for information about the initialization struc-
tures that are required when you want to add an MSD interface.
For the emUSB CDC component, refer to USB_CDC_INIT_DATA on page 301 for
information about the initialization structure that is required when you want to
add a CDC interface.
For the emUSB HID component, refer to USB_HID_INIT_DATA on page 330 for
information about the initialization structure that is required when you want to
add a HID interface.
3. Start the USB stack. Call USB_Start() to start the USB stack.
Example applications for every supported USB class and the unclassified bulk compo-
nent are supplied. We recommend using one of these examples as a starting point for
your own application. All examples are supplied in the \Application\ directory.
Target USB components
emUSB Core
Driver
Bulk
USB class drivers
HIDCDCMSD
Printer
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
53
4.2 Target API
This section describes the functions that can be used by the target application.
Function Description
USB basic functions
USB_AddDriver() Adds a USB device driver to the emUSB
stack.
USB_GetState() Returns the state of the USB device.
USB_Init() Initializes the emUSB Core.
USB_IsConfigured() Checks if the USB device is configured.
USB_Start() Starts the emUSB core.
USB_Stop() Stops the emUSB core.
USB_DeInit() Deinitializes the emUSB Core.
USB configuration functions
USB_AddEP() Returns an endpoint “handle” that can be
used for the desired USB interface.
USB_SetAddFuncDesc()
Sets a callback for setting additional
information into the configuration
descriptor.
USB_SetClassRequestHook() Sets a callback to handle class setup
requests.
USB_SetVendorRequestHook() Sets a callback to handle vendor setup
requests.
USB_SetIsSelfPowered() Sets whether the device is self-powered
or not.
USB_SetMaxPower() Sets the target device current consump-
tion.
USB_SetOnRxEP0() Sets a callback to handle data read of
endpoint 0.
USB_SetOnSetupHook() Sets a callback to handle EP0 setup pack-
ets.
USB__WriteEP0FromISR() Writes data to a USB EP.
USB_StallEP() Stalls an endpoint.
USB_WaitForEndOfTransfer() Waits for a data transfer to be ended.
USB IAD functions
USB_EnableIAD() Allows to combine multi-interface device
classes with single-interface classes.
USB RemoteW a keUp functions
USB_SetAllowRemoteWakeUp() Allows the device to publish that remote
wake is available.
USB_DoRemoteWakeup() Performs a remote wakeup to the host.
Table 4.1: Target USB Core interface function list
54 CHAPTER 4 USB Core
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
4.2.1 USB basic functions
4.2.1.1 USB_AddDriver()
Description
Adds a USB device driver to the USB stack. This function should be called from within
USB_X_AddDriver() which is implemented in USB_X.c.
Prototype
void USB_AddDriver(const USB_HW_DRIVER * pDriver);
Additional information
To add the driver, use USB_AddDriver() with the identifier of the compatible driver.
Refer to the section Available USB drivers on page 410 for a list of supported devices
and their valid identifiers.
Example
USB_AddDriver(&USB_Driver_AtmelRM9200);
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
55
4.2.1.2 USB_GetState()
Description
Returns the state of the USB device.
Prototype
int USB_GetState(void);
Return value
The return value is a bitwise OR combination of the following state flags.
Additional information
A USB device has several possible states. Some of these states are visible to the USB
and the host, while others are internal to the USB device. Refer to Universal Serial
Bus Specification, Revision 2.0, Chapter 9 for detailed information.
Note 1:
Attached in a USB sense of the word does not mean that the device is physically con-
nected to the PCvia a USB cable, it only means that the pull-up resistor on the device
side is connected. The status can be "attached" regardless of whether the device is
connected to a host or not.
USB state flags
USB_STAT_ATTACHED Device is attached. (Note 1)
USB_STAT_READY Device is ready.
USB_STAT_ADDRESSED Device is addressed.
USB_STAT_CONFIGURED Device is configured.
USB_STAT_SUSPENDED Device is suspended.
56 CHAPTER 4 USB Core
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
4.2.1.3 USB_Init()
Description
Initializes the USB device with its settings.
Prototype
void USB_Init(void);
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
57
4.2.1.4 USB_IsConfigured()
Description
Checks if the USB device is initialized and ready.
Prototype
char USB_IsConfigured(void);
Return value
0: USB device is not configured.
1: USB device is configured.
58 CHAPTER 4 USB Core
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
4.2.1.5 USB_Start()
Description
Starts the emUSB Core.
Prototype
void USB_Start(void);
Additional information
This function should be called after configuring USB Core. It initiates a hardware
attach and updates the endpoint configuration. When the USB cable is connected to
the device, the host will start enumeration of the device.
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
59
4.2.1.6 USB_Stop()
Description
Stops the USB communication. This function also makes sure that the device is
detached from the USB host.
Prototype
void USB_Stop(void);
60 CHAPTER 4 USB Core
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
4.2.1.7 USB_DeInit()
Description
De-initializes the complete USB stack.
Prototype
void USB_DeInit(void);
Additional information
This function also calls USB_Stop() internally.
Not all drivers have a DeInit callback function, if you need to use DeInit and your
driver does not have the callback - please contact SEGGER.
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
61
4.2.2 USB configuration functions
4.2.2.1 USB_AddEP()
Description
Returns an endpoint “handle” that can be used for the desired USB interface.
Prototype
unsigned USB_AddEP(U8 InDir,
U8 TransferType,
U16 Interval,
U8 * pBuffer,
unsigned BufferSize);
Return value
On success: A valid endpoint handle is returned.
On failure: 0 is returned.
Parameter Description
InDir
Specifies the direction of the desired endpoint.
1 - IN
0 - OUT
TransferType
Specifies the transfer type of the endpoint.
The following values are allowed:
USB_TRANSFER_TYPE_BULK
USB_TRANSFER_TYPE_ISO
USB_TRANSFER_TYPE_INT
Interval Specifies the interval in microframes [0.125 µs] for the endpoint.
This value can be zero for a bulk endpoint.
pBuffer Pointer to a buffer that is used for OUT-transactions.
For IN-endpoints this parameter must be NULL.
BufferSize Size of the buffer.
Table 4.2: USB_AddEP() parameter list
62 CHAPTER 4 USB Core
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
4.2.2.2 USB_SetAddFuncDesc()
Description
Sets a callback for setting additional information into the configuration descriptor.
Prototype
void USB_SetAddFuncDesc(USB_ADD_FUNC_DESC * pfAddDescFunc);
Additional information
USB_ADD_FUNC_DESC is defined as follows:
typedef void USB_ADD_FUNC_DESC(USB_INFO_BUFFER * pInfoBuffer);
Parameter Description
pfAddDescFunc Pointer to a function that should be called when building the
configuration descriptor.
Table 4.3: USB_SetAddFuncDesc() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
63
4.2.2.3 USB_SetClassRequestHook()
Description
Sets a callback for a function that handles setup class request packets.
Prototype
void USB_SetClassRequestHook(unsigned Interface,
USB_ON_CLASS_REQUEST * pfOnClassrequest);
Additional information
Note that the callback will be called within an ISR.
If it is necessary to send data from the callback function through endpoint 0, use the
function USB__WriteEP0FromISR().
USB_ON_CLASS_REQUEST is defined as follows:
typedef void USB_ON_CLASS_REQUEST(const USB_SETUP_PACKET * pSetup-
Packet);
Parameter Description
Interface Specifies the Interface number of the class on which the hook
shall be installed.
pfOnClassrequest Pointer to a function that should be called when a setup class
request/packet is received.
Table 4.4: USB_SetClassRequestHook() parameter list
64 CHAPTER 4 USB Core
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
4.2.2.4 USB_SetVendorRequestHook()
Description
Sets a callback for a function that handles setup vendor request packets.
Prototype
void USB_SetVendorRequestHook (unsigned InterfaceNum,
USB_ON_CLASS_REQUEST * pfOnVendorRequest);
Additional information
Note that the callback will be called within an ISR, therefore it should never block.
If it is necessary to send data from the callback function through endpoint 0, use the
function USB__WriteEP0FromISR().
USB_ON_CLASS_REQUEST is defined as follows:
typedef void USB_ON_CLASS_REQUEST(const USB_SETUP_PACKET * pSetup-
Packet);
Parameter Description
Interface Specifies the Interface number of the class on which the hook
shall be installed.
pfOnClassrequest Pointer to a function that should be called when a setup ven-
dor request/packet is received.
Table 4.5: USB_SetClassRequestHook() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
65
4.2.2.5 USB_SetIsSelfPowered()
Description
Sets whether the device is self-powered or not.
Prototype
void USB_SetIsSelfPowered(U8 IsSelfPowered);
Additional information
This function shall be called before USB_Start(), as it will specify if the device is self-
powered or not.
The default value is 0 (not self-powered).
Parameter Description
IsSelfPowered 0 - Device is not self-powered.
1 - Device is self-powered.
Table 4.6: USB_SetClassRequestHook() parameter list
66 CHAPTER 4 USB Core
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
4.2.2.6 USB_SetMaxPower()
Description
Sets the maximum power consumption reported to the host during enumeration.
Prototype
void USB_SetMaxPower(U8 MaxPower);
Additional information
This function shall be called before USB_Start(), as it will specify how much power
the device will consume from the host.
If this function is not called, a default value of 100 mA will be used.
Parameter Description
MaxPower Specifies the max power consumption given in mA.
MaxPower shall be in range between 0mA - 500mA.
Table 4.7: USB_SetClassRequestHook() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
67
4.2.2.7 USB_SetOnRxEP0()
Description
Sets a callback to handle non-setup data presented on endpoint 0.
Prototype
void USB_SetOnRxEP0(USB_ON_RX_FUNC * pfOnRx);
Additional information
Note that the callback will be called within an ISR, therefore it should never block.
If it is necessary to send data from the callback function through endpoint 0, use the
function USB__WriteEP0FromISR().
USB_ON_RX_FUNC is defined as follows:
typedef void USB_ON_RX_FUNC(const U8 * pData, unsigned NumBytes);
Parameter Description
pfOnRx Pointer to a function that should be called when receiving data
other than setup packets.
Table 4.8: USB_SetOnRxEP0() parameter list
68 CHAPTER 4 USB Core
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
4.2.2.8 USB_SetOnSetupHook()
Description
Sets a callback for a function that handles setup class request packets.
Prototype
void USB_SetOnSetupHook (unsigned InterfaceNum, USB_ON_SETUP * pfOnSetup);
Additional information
Note that the callback will be called within an ISR.
If it is necessary to send data from the callback function through endpoint 0, use the
function USB__WriteEP0FromISR().
USB_ON_SETUP is defined as follows:
typedef int USB_ON_SETUP(const USB_SETUP_PACKET * pSetupPacket);
Parameter Description
Interface Specifies the Interface number of the class on which the hook
shall be installed.
pfOnClassrequest Pointer to a function that should be called when a setup class
request/packet is received.
Table 4.9: USB_SetClassRequestHook() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
69
4.2.2.9 USB__WriteEP0FromISR()
Description
Writes data to a USB EP.
Prototype
void USB__WriteEP0FromISR(const void* pData, unsigned NumBytes,
char Send0PacketIfRequired);
Parameter Description
pData Data that should be written.
NumBytes Number of bytes to write.
Send0PacketIfRequ
ired
Specifies that a zero-length packet should be sent when the
last data packet to the host is a multiple of MaxPacketSize.
Normally MaxPacketSize for control mode transfer is 64 byte.
Table 4.10: USB_WriteEP0FromISR() parameter list
70 CHAPTER 4 USB Core
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
4.2.3 USB control functions
4.2.3.1 USB_StallEP()
Description
Stalls an endpoint.
Prototype
void USB_StallEP(U8 EPIndex);
Parameter Description
EPIndex Endpoint handle that needs to be stalled.
Table 4.11: USB_StallEP() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
71
4.2.3.2 USB_WaitForEndOfTransfer()
Description
Waits for a data transfer to complete.
Prototype
void USB_WaitForEndOfTransfer(U8 EPIndex);
Parameter Description
EPIndex Endpoint handle to wait for end of transfer.
Table 4.12: USB_WaitForEndOfTransfer() parameter list
72 CHAPTER 4 USB Core
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
4.2.4 USB IAD functions
4.2.4.1 USB_EnableIAD()
Description
Enables combination of multi-interface device classes with single-interface classes or
other multi-interface classes.
Prototype
void USB_EnableIAD(void);
Additional information
Simple device classes such as HID and MSD or BULK use only one interface descrip-
tor to describe the class. The interface descriptor also contains the device class code.
The CDC device class uses more than one interface descriptor to describe the class.
The device class code will then be written into the device descriptor. It may be possi-
ble to add an interface which does not belong to the CDC class, but it may be cor-
rectly recognized by the host.
In order to allow this, a new descriptor type was introduced:
IAD (Interface Association Descriptor), this descriptor will encapsulate the multi-
interface class into this IA descriptor, so that it will be seen as one single interface
and will then allow to add other device classes.
If you intend to use the CDC component with any other component, please call
USB_EnableIAD() before adding the CDC component through USB_CDC_Add().
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
73
4.2.5 USB Remote wakeup functions
Remote wakeup is a feature that allows a device to wake a host system from a USB
suspend state.
In order to do this a special resume signal is sent over the USB data lines.
Additionally the USB host controller and operating system shall be able to handle this
signaling.
Windows OS:
Currently Windows OS only supports the wakeup feature on devices based on HID
mouse/keyboard, CDC Modem and RNDIS Ethernet class. Remote wakeup for MSD,
generic bulk and CDC serial is not supported by Windows. So therefore a HID mouse
class even as dummy interface within your USB configuration is currently mandatory.
A sample is provided for adding such a dummy class.
Windows must also be told that the device shall wake the PC from the suspend state.
This is done by setting the option "Allow this device to bring the computer out of
standby".
Mac OS X
Mac OS X supports remote wakeup for all device classes.
74 CHAPTER 4 USB Core
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
4.2.5.1 USB_SetAllowRemoteWakeUp()
Description
Allows the device to publish that remote wake is available.
Prototype
void USB_SetAllowRemoteWakeUp(U8 AllowRemoteWakeup);
Additional information
This function must be called before the function USB_Start() is called. This ensures
that the Host is informed that USB remote wake up is available.
Parameter Description
AllowRemoteWakeup 1 - Allows and publishes that remote wakeup is available.
0 - Publish that remote wakeup is not available.
Table 4.13: USB_SetAllowRemoteWakeUp() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
75
4.2.5.2 USB_DoRemoteWakeup()
Description
Performs a remote wakeup in order to wake up the host from the standby/suspend
state.
Prototype
void USB_DoRemoteWakeUp(void);
Additional information
This function cannot be called from an ISR context
76 CHAPTER 4 USB Core
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
77
Chapter 5
Bulk communication
This chapter describes how to get emUSB-Bulk up and running.
78 CHAPTER 5 Bulk communication
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
5.1 Generic bulk stack
The generic bulk stack is located in the directory USB. All C files in the directory
should be included in the project (compiled and linked as part of your project). The
files in this directory are maintained by SEGGER and should not require any modifica-
tion. All files requiring modifications have been placed in other directories.
5.2 The Kernel mode driver (PC)
In order to communicate with a target (client) running emUSB, an emUSB bulk kernel
mode driver must be installed on Windows PC’s. Typically, this is done as soon as
emUSB runs on target hardware.
Installation of the driver and how to recompile it is explained in this chapter.
5.2.1 Why is a driver necessary?
In Microsoft’s Windows operating systems, all communication with real hardware is
implemented with kernel-mode drivers. Normal applications run in user-mode. In
user mode, hardware access is not permitted. All access to hardware is done through
the operating system and the operating system uses a kernel mode driver to access
the actual hardware. In other words: every piece of hardware requires one or more
kernel mode drivers to function. Windows supplies drivers for most common types of
hardware, but it does not come with a generic bulk communication driver. It comes
with drivers for certain classes of devices, such as keyboard, mouse and mass stor-
age (for example, a USB stick). This makes it possible to connect a USB mouse and
without having to install a driver for it: Windows already has a driver for it.
Unfortunately, there is no generic kernel mode driver which allows communication to
any type of device in bulk mode. This is why a kernel mode driver needs to be sup-
plied in order to work with emUSB-Bulk.
5.2.2 Supported platforms
The kernel mode driver works on all NT-type platforms. This includes Windows 2000
and Windows XP (home and professional), Windows 2003 Server and Windows Vista.
Windows NT itself does not support USB; Win98 is not supported by the driver.
5.3 Installing the driver
When the target device is plugged into the computer's USB port, or when the com-
puter is first powered up after connecting the emUSB device, Windows will detect the
new hardware.
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
79
The wizard will complete the installation for the detected device. First select the
Search for a suitable driver for my device option and click on the Next button.
In the next step, select the Specify a location option and click the Next button.
The wizard needs the path to the correct driver files for the new device.
Use the directory navigator to select the USBBulk.inf file and click the Open button.
80 CHAPTER 5 Bulk communication
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
The wizard confirms the choice and starts to copy, after clicking the Next button.
At this point, the installation is complete. Click the Finish button to dismiss the wiz-
ard.
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
81
5.3.1 Recompiling the driver
To recompile the driver, the Device Developer Kit (NTDDK), as well as an installation
of Microsoft Visual C++ 6.0 or Visual Studio .net is needed.
The workspace is placed in the subdirectory Driver. In order to open it, double click
the workspace file USBDriver.dsw.
A workspace similar to the screenshot below is opened.
Choose Build | Build USBBulk.sys (Shortcut: F7) to compile and link the driver.
82 CHAPTER 5 Bulk communication
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
5.3.2 The .inf file
The .inf file is required for installation of the kernel mode driver.
The shipped file is as follows:
;
;
; USB BULK Device driver inf
;
;
[Version]
Signature="$CHICAGO$"
Class=USB
ClassGUID={36FC9E60-C465-11CF-8056-444553540000}
provider=%MfgName%
DriverVer=08/07/2003
[SourceDisksNames]
1="USB BULK Installation Disk",,,
[SourceDisksFiles]
USBBulk.sys = 1
USBBulk.inf = 1
[Manufacturer]
%MfgName%=DeviceList
[DeviceList]
%USB\VID_8765&PID_1234.DeviceDesc%=USBBULK.Dev, USB\VID_8765&PID_1234
;[PreCopySection]
;HKR,,NoSetupUI,,1
[DestinationDirs]
USBBULK.Files.Ext = 10,System32\Drivers
[USBBULK.Dev]
CopyFiles=USBBULK.Files.Ext
AddReg=USBBULK.AddReg
[USBBULK.Dev.NT]
CopyFiles=USBBULK.Files.Ext
AddReg=USBBULK.AddReg
[USBBULK.Dev.NT.Services]
Addservice = USBBULK, 0x00000002, USBBULK.AddService
[USBBULK.AddService]
DisplayName = %USBBULK.SvcDesc%
ServiceType = 1 ; SERVICE_KERNEL_DRIVER
StartType = 3 ; SERVICE_DEMAND_START
ErrorControl = 1 ; SERVICE_ERROR_NORMAL
ServiceBinary = %10%\System32\Drivers\USBBULK.sys
LoadOrderGroup = Base
[USBBULK.AddReg]
HKR,,DevLoader,,*ntkern
HKR,,NTMPDriver,,USBBULK.sys
[USBBULK.Files.Ext]
USBBulk.sys
;---------------------------------------------------------------;
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
83
[Strings]
MfgName="MyCompany"
USB\VID_8765&PID_1234.DeviceDesc="USB Bulk Device"
USBBULK.SvcDesc="USB Bulk device driver"
red - required modifications
green - possible modifications
You must personalize the .inf file on the red marked positions. Changes on the
green marked positions are optional and not necessary for correct operation of the
device.
Replace the red marked positions with the personal vendor Id (VID) and product Id
(PID). These changes must match the modifications in the configuration functions to
work correctly.
The required modifications of the configuration functions are described in the section
Configuration on page 44.
5.3.3 Configuration
To get emUSB up and running as well as doing an initial test, the configuration as it is
delivered should not be modified. The configuration section can later on be modified
to match your real application. The configuration must only be modified if emUSB
should be used in a final product. Refer to section Configuration on page 44 for
detailed information about the functions which must be adapted.
84 CHAPTER 5 Bulk communication
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
5.4 Example application
Example applications for both the target (client) and the PC (host) are supplied.
These can be used for testing the correct installation and proper function of the
device running emUSB.
The application is a modified echo server (BULK_Echo1.c); the application receives
data byte by byte, increments every single byte and sends it back to the host.
To use this application, make sure to use the corresponding example files both on the
host-side as on the target side. The example applications on the PC host are named
in the same way, just without the prefix BULK_. (For example, if the host runs
Echo1.exe, BULK_Echo1.c has to be included into your project, compiled and down-
loaded into your target.) There are additional examples that can be used for testing
emUSB.
The following start application files are provided:
The example applications for the target-side are supplied in source code in the
Application directory.
File Description
BULK_Echo1.c This application was described in the upper text.
BULK_EchoFast.c This is the faster version of Bulk_Echo1.c
BULK_Test.c This application can be used to test emUSB-Bulk with differ-
ent packet sizes received from and sent to the PC host.
Table 5.1: Supplied sample applications
Host (PC)
Target
USB bulk
example
application.
(for example:
Echo1.exe)
Target programmed
with the example
application consistent
with the application
running on host side
(for example:
BULK_Echo1.c).
USB connection
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
85
Depending on which application is running on the emUSB device, use one of the fol-
lowing example applications:
To use these examples, the application on the PC host should use the same example
file to work correctly. The example applications on the PC host are named in the
same way. The example applications for the host-side are supplied in both source
code and executable form in the Bulk\SampleApp directory. For information how to
compile the host examples refer to Compiling the PC example application on page 87.
The start application will of course later on be replaced by the real application pro-
gram. For the purpose of getting emUSB up and running as well as doing an initial
test, the start application should not be modified.
5.4.1 Running the example applications
To test the emUSB-Bulk component, build and download the application of choice for
the target-side. If you connect your target to the host via USB while the example
application is running, Windows will detect the new hardware.
To run one of the example applications, simply start the executable, for example by
double clicking it. If the USB-Bulk device is not connected to the PC or the driver is
not installed, the following message box should pop up.
If a connection can be established, it exchanges data with the target, testing the USB
connection.
Example output of Echo1.exe:
File Description
Echo1.exe If the BULK_Echo1.c sample application is running on the
emUSB-Bulk device, use this application.
EchoFast.exe If the BULK_EchoFast.c sample application is running on the
emUSB-Bulk device, use this EchoFast application.
Test.exe If the BULK_Test.c application is running on the emUSB-Bulk
device, use this application to test the emUSB-Bulk stack.
Table 5.2: Supplied host applications
86 CHAPTER 5 Bulk communication
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
Example output of EchoFast.exe:
Example output of Test.exe:
If the host example application can communicate with the emUSB device, the exam-
ple application will be in interactive mode for the Echo1 and the EchoFast applica-
tion. In case of an error, a message box is displayed.
Error Messages Description
Unable to connect
to USB BULK device
The USB device is not connected to the PC or the connec-
tion is faulty.
Could not write to
device The PC sample application was not able to write one byte.
Could not read
from device (time-
out)
The PC sample application was not able to read one byte.
Wrong data read The result of the target sample application is not correct.
Table 5.3: List of error messages
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
87
5.4.2 Compiling the PC example application
For compiling the example application you need a Microsoft compiler. The compiler is
part of Microsoft Visual C++ 6.0 or Microsoft Visual Studio .Net.
The source code of the sample application is located in the subfolder Bulk\SAM-
PLEAPP. Open the file USBBULK_Start.dsw and compile the source choose Build |
Build SampleApp.exe (Shortcut: F7). To run the executable choose Build | Exe-
cute SampleApp.exe (Shortcut: CTRL-F5).
88 CHAPTER 5 Bulk communication
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
5.5 Target API
This chapter describes the functions that can be used with the target system.
General information
To communicate with the host, the sample application project includes USB-specific
header and source files (USB.h, USB_Main.c, USB_Setup.c, USB_Bulk.c,
USB_Private.h). These files contain API functions to communicate with the USB host
through the emUSB driver.
Purpose of the USB Device API functions
To have an easy start up when writing an application on the device side, these API
functions have a simple interface and handle all operations that need to be done to
communicate with the host emUSB kernel mode driver.
Therefore, all operations that need to write to or read from the emUSB are handled
internally by the provided API functions.
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
89
5.5.1 Target interface function list
Routine Explanation
USB-Bulk functions
USB_BULK_Add() Adds an USB-Bulk interface to emUSB.
USB_BULK_CancelRead() Cancels a non-blocking read operation
that is pending.
USB_BULK_CancelWrite() Cancels a non-blocking write operation
that is pending.
USB_BULK_GetNumBytesInBuffer() Returns the number of byte in BULK-OUT
buffer.
USB_BULK_GetNumBytesRemToRead() Returns the number of bytes which have
to be read.
USB_BULK_GetNumBytesToWrite() Returns the number of bytes which have
to be written.
USB_BULK_Read() USB-Bulk read.
USB_BULK_ReadOverlapped() Non-blocking version of
USB_BULK_Read().
USB_BULK_ReadTimed() Starts a read operation that shall be done
within a given timeout.
USB_BULK_Receive() Read data from host and return immedi-
ately as soon as data has been received.
USB_BULK_SetOnRXHook() Installs a hook that shall be called when
an USB packet is received.
USB_BULK_TxIsPending() Checks whether the IN endpoint is cur-
rently pending.
USB_BULK_WaitForTX() Waits for a non-blocking write operation
that is pending.
USB_BULK_WaitForRX() Waits for a non-blocking write operation
that is pending.
USB_BULK_Write() Starts a blocking write operation.
USB_BULK_WriteEx()
Starts a blocking write operation that
allows to specify whether a NULL packet
shall be sent or not.
USB_BULK_WriteExTimed() Starts an USB-Bulk WriteEx operation
that shall be done within a given timeout.
USB_BULK_WriteOverlapped() Non-blocking version of
USB_Bulk_Write().
USB_BULK_WriteOverlappedEx()
USB_BULK_WriteNULLPacket() Sends a NULL (zero-length) packet to
host.
USB_BULK_WriteTimed() Starts an USB-Bulk Write operation that
shall be done within a given timeout.
Data structures
USB_BULK_INIT_DATA Initialization structure which is required
when adding a bulk interface.
USB_ON_RX_FUNC Function called when data is received.
Table 5.4: Target interface function list
90 CHAPTER 5 Bulk communication
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
5.5.2 USB-Bulk functions
5.5.2.1 USB_BULK_Add()
Description
Adds interface for USB-Bulk communication to emUSB.
Prototype
void USB_BULK_Add( const USB_BULK_INIT_DATA * pInitData );
Additional information
USB_BULK_INIT_DATA is defined as follows:
typedef struct {
U8 EPIn; // Endpoint for sending data to the host
U8 EPOut; // Endpoint for receiving data from the host
};
Parameter Description
pInitData Pointer to USB_BULK_INIT_DATA structure.
Table 5.5: USB_BULK_Add() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
91
5.5.2.2 USB_BULK_CancelRead()
Description
Cancels any non-blocking/blocking read operation that is pending.
Prototype
void USB_BULK_CancelRead(void);
Additional information
This function shall be called when a pending asynchronous read operation should be
canceled. The function can be called from any task. In case of canceling a blocking
operation, this function must be called from another task.
92 CHAPTER 5 Bulk communication
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
5.5.2.3 USB_BULK_CancelWrite()
Description
Cancels a non-blocking/blocking read operation that is pending.
Prototype
void USB_BULK_CancelWrite(void);
Additional information
This function shall be called when a pending asynchronously write operation should
be canceled. It can be called from any task. In case of canceling a blocking operation,
this function must be called from another task.
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
93
5.5.2.4 USB_BULK_GetNumBytesInBuffer()
Description
Returns the number of bytes that are available in the internal BULK-OUT endpoint
buffer.
Prototype
unsigned USB_BULK_GetNumBytesInBuffer(void);
Additional information
If the host is sending more data than your target application has requested, the
remaining data will be stored in an internal buffer.
The function USB_BULK_GetNumBytesInBuffer() shows how many bytes are avail-
able in this buffer.
Example:
Your host application sends 50 bytes.
Your target application only requests to receive 1 byte.
In this case the target application will get 1 byte and the remaining 49 bytes are
stored in an internal buffer.
When your target application now calls USB_BULK_GetNumBytesInBuffer() it will
return the number of bytes that are available in the internal buffer (49).
94 CHAPTER 5 Bulk communication
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
5.5.2.5 USB_BULK_GetNumBytesRemToRead()
Description
This function is to be used in combination with USB_BULK_ReadOverlapped()
After starting the read operation this function can be used to periodically check how
many bytes still have to be read.
Prototype
unsigned USB_BULK_GetNumBytesRemToRead(void);
Return value
>= 0 Number of bytes which have not yet been read.
Additional information
Alternatively the blocking function USB_BULK_WaitForRX() can be used.
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
95
5.5.2.6 USB_BULK_GetNumBytesToWrite()
Description
This function is to be used in combination with USB_BULK_WriteOverlapped()/
USB_BULK_WriteOverlappedEx().
After starting the write operation this function can be used to periodically check how
many bytes still have to be written.
Prototype
unsigned USB_BULK_GetNumBytesToWrite(void);
Return value
>= 0 Number of bytes which have not yet been written.
Additional information
Alternatively the blocking function USB_BULK_WaitForTX() can be used.
96 CHAPTER 5 Bulk communication
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
5.5.2.7 USB_BULK_Read()
Description
Reads data from the host. This function blocks until NumBytes has been received or
until the device is disconnected.
Prototype
int USB_BULK_Read(void* pData, unsigned NumBytes);
Return value
Number of bytes that have been received.
In case of an error -1 is returned.
Parameter Description
pData Pointer to a buffer where the received data will be stored.
NumBytes Number of bytes to read.
Table 5.6: USB_BULK_Read() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
97
5.5.2.8 USB_BULK_ReadOverlapped()
Description
Reads data from the host asynchronously.
Prototype
int USB_BULK_ReadOverlapped(void* pData, unsigned NumBytes);
Return value
Number of bytes that have already been received or have been copied from internal
buffer. The value can be less or equal to NumBytes.
Additional information
This function will not block the calling task. The read transfer will be initiated and the
function returns immediately. In order to synchronize, USB_BULK_WaitForRX() needs
to be called. Alternatively the function USB_BULK_GetNumBytesRemToRead() can be
called periodically to check whether all bytes have been written or not.
Parameter Description
pData Pointer to a buffer where the received data will be stored.
NumBytes Number of bytes to read.
Table 5.7: USB_BULK_ReadOverlapped() parameter list
98 CHAPTER 5 Bulk communication
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
5.5.2.9 USB_BULK_ReadTimed()
Description
Reads data from the host with a given timeout.
Prototype
int USB_BULK_ReadOverlapped(void* pData, unsigned NumBytes, unsigned ms);
Return value
Number of bytes that have been read within the given timeout.
Additional information
This function blocks a task until all data have been read or a timeout expires. This
function also returns when the device is disconnected from host or when a USB reset
occurrs.
Parameter Description
pData Pointer to a buffer where the received data will be stored.
NumBytes Number of bytes to read.
ms timeout given in milliseconds.
Table 5.8: USB_BULK_ReadTimed() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
99
5.5.2.10 USB_BULK_SetOnRXHook()
Description
Sets a callback that is executed on reception of a data packet form the host.
Prototype
void USB_BULK_SetOnRXHook(USB_ON_RX_EP * pfOnRx);
Additional information
Setting up a callback function may be necessary to allow a monitoring task to sus-
pend and shall be woken up when data have been received.
The callback function will be called within a interrupt service routine, so we advice
that you ensure the callback completes quickly.
Parameter Description
pfOnRx Pointer to the callback function.
Table 5.9: USB_BULK_SetOnRXHook() parameter list
100 CHAPTER 5 Bulk communication
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
5.5.2.11 USB_BULK_TxIsPending()
Description
Checks whether the TX (IN endpoint) is currently pending. Can be called in any con-
text.
Prototype
int USB_BULK_TxIsPending(void);
Return value
1 - We have queued a package to be sent.
0 - Queue is empty.
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
101
5.5.2.12 USB_BULK_Receive()
Description
Reads data from host and returns as soon as data has been received.
Prototype
int USB_BULK_Receive(void * pData, unsigned NumBytes);
Return value
>= 0 Number of bytes that have been read.
-1 Error.
Additional information
If no error occurs, this function returns the number of bytes received.
Calling USB_BULK_Receive() will return as much data as is currently available—up to
the size of the buffer specified.
Parameter Description
pData Pointer to a buffer where the received data will be stored.
NumBytes Maximum number of bytes to read.
Table 5.10: USB_BULK_Receive() parameter list
102 CHAPTER 5 Bulk communication
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
5.5.2.13 USB_BULK_WaitForRX()
Description
This function is used in combination with USB_BULK_ReadOverlapped(), it waits for
the read data transfer from the host to complete.
Prototype
void USB_BULK_WaitForRX(void);
Additional information
After starting the read operation via USB_BULK_ReadOverlapped() this function can
be used to wait until the transfer is complete.
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
103
5.5.2.14 USB_BULK_WaitForTX()
Description
This function is used in combination with USB_BULK_WriteOverlapped(), it waits for
the write data transfer from the host to complete.
Prototype
void USB_BULK_WaitForTX(void);
Additional information
After starting the write operation via USB_BULK_WriteOverlapped() this function can
be used to wait until the transfer is complete.
104 CHAPTER 5 Bulk communication
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
5.5.2.15 USB_BULK_Write()
Description
Sends data to the USB host. This function blocks until NumBytes has been received
or until the device is disconnected.
Prototype
int USB_BULK_Write(const void * pData, unsigned NumBytes);
Return value
> 0 Number of bytes that have been written.
0 Error.
Parameter Description
pData Data that should be written.
NumBytes Number of bytes to write.
Table 5.11: USB_BULK_Write() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
105
5.5.2.16 USB_BULK_WriteEx()
Description
Sends data to the host with the option to send a zero-length packet at the end of the
data transfer.
Prototype
int USB_BULK_WriteEx(const void* pData,
unsigned NumBytes,
char Send0PacketIfRequired);
Additional information
Normally USB_BULK_Write is called to let the stack send that whole packet to the
host and send an optional zero-length packet to tell the host that this was the last
packet. This is the case when the last packet that shall be sent is MaxPacketSize
bytes in size.
When using this function, the zero-length packet handling can be controlled. This
means the function can be called when sending data in multiple steps. Please make
sure that NumBytes is always a multiple of MaxPacketSize, except for the last trans-
mission.
Example
static U8 _aDataBuffer[512];
static void _Send(void) {
unsigned NumBytes2Send;
unsigned NumBytesRead;
NumBytes2Send = _GetNumBytes2Send();
while (NumBytes2Send >= sizeof(_aDataBuffer)) {
NumBytesRead = _GetData(&_aDataBuffer[0], sizeof(_aDataBuffer));
USB_BULK_WriteEx(&_aDataBuffer[0], NumBytesRead, 0);
NumBytes2Send -= NumBytesRead;
}
USB_BULK_WriteEx(&_aDataBuffer[0], NumBytes2Send, 1);
}
Parameter Description
pData Pointer to a buffer that contains the written data.
NumBytes Number of bytes to write.
Send0PacketIfRequired
Specifies that a zero-length packet shall be sent when
the last data packet is a multiple of MaxPacketSize.
Normally MaxPacketSize for full-speed devices is 64
bytes.
For high-speed devices the normal packet size is between
64 and 512 bytes.
Table 5.12: USB_BULK_WriteEx() parameter list
106 CHAPTER 5 Bulk communication
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
5.5.2.17 USB_BULK_WriteExTimed()
Description
Sends data to the host with the option to send a zero-length packet at the end of the
data transfer and a timeout option.
Prototype
int USB_BULK_WriteEx(const void* pData,
unsigned NumBytes,
char Send0PacketIfRequired
unsigned ms);
Return value
Number of bytes that have been written within the given timeout.
Additional information
This function blocks a task until all data have been written or a timeout occurs. This
function also returns when target is disconnected from host or when a USB reset
occurred.
Parameter Description
pData Pointer to a buffer that contains the written data.
NumBytes Number of bytes to write.
Send0PacketIfRequired
Specifies that a zero-length packet shall be sent when
the last data packet to the host is a multiple of MaxPack-
etSize.
Normally MaxPacketSize for full-speed devices is 64 byte.
For high-speed devices the normal packet size is between
64-512 bytes.
ms timeout
Table 5.13: USB_BULK_WriteExTimed() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
107
5.5.2.18 USB_BULK_WriteOverlapped()
Description
Write data to the host asynchronously.
Prototype
int USB_BULK_WriteOverlapped(const void* pData, unsigned NumBytes);
Return value
Number of bytes that were accepted and sent to the host. The value can be less or
equal to NumBytes.
Additional information
This function will not block the calling task. The write transfer will be initiated and
the function returns immediately. In order to synchronize, USB_BULK_WaitForTX()
needs to be called.
Parameter Description
pData Pointer to data that should be sent to the host.
NumBytes Number of bytes to write.
Table 5.14: USB_BULK_WriteOverlapped() parameter list
108 CHAPTER 5 Bulk communication
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
5.5.2.19 USB_BULK_WriteOverlappedEx()
Description
Write data to the host asynchronously.
Prototype
int USB_BULK_WriteOverlappedEx(const void* pData,
unsigned NumBytes,
char Send0PacketIfRequired);
Return value
Number of bytes that have already been sent to the host. The value can be less or
equal to NumBytes.
Additional information
This function will not block the calling task. The write transfer will be initiated and
the function returns immediately. In order to synchronize, USB_BULK_WaitForTX()
needs to be called.
Parameter Description
pData Pointer to data that should be sent to the host.
NumBytes Number of bytes to write.
Send0PacketIfRequired
Specifies that a zero-length packet shall be sent when
the last data packet to the host is a multiple of MaxPack-
etSize.
Normally MaxPacketSize for full-speed devices is 64 byte.
For high-speed devices the normal packet size is between
64-512 bytes.
Table 5.15: USB_BULK_WriteOverlappedEx() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
109
5.5.2.20 USB_BULK_WriteTimed()
Description
Writes data from the host with a given timeout.
Prototype
int USB_BULK_WriteOverlapped(const void* pData,
unsigned NumBytes,
unsigned ms);
Return value
Number of bytes that have been written within the given timeout.
Additional information
This function blocks a task until all data have been written or a timeout occurs. This
function also returns when target is disconnected from host or when a USB reset
occurred.
Parameter Description
pData Pointer to a buffer that contains the written data.
NumBytes Number of bytes to write.
ms timeout
Table 5.16: USB_BULK_ReadOverlapped() parameter list
110 CHAPTER 5 Bulk communication
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
5.5.2.21 USB_BULK_WriteNULLPacket()
Description
Sends a zero-length packet to the host.
Prototype
void USB_BULK_WriteNULLPacket(void);
Additional information
This function is useful to indicate that either no data are available or to indicate that
this is the last packet of the data stream.
In normal cases sending a zero-length packet as a termination packet is not neces-
sary since the stack handles this automatically when calling any USB_BULK write
function (except for USB_BULK_WriteEx routines).
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
111
5.5.3 Data structures
5.5.3.1 USB_BULK_INIT_DATA
Description
Initialization structure which is required when adding a bulk interface to emUSB-
Bulk.
Prototype
typedef struct {
U8 EPIn;
U8 EPOut;
} USB_BULK_INIT_DATA;
Example
Example excerpt from BULK_Echo1.c:
static void _AddBULK(void) {
static U8 _abOutBuffer[USB_MAX_PACKET_SIZE];
USB_BULK_INIT_DATA Init;
Init.EPIn = USB_AddEP(1, USB_TRANSFER_TYPE_BULK, USB_MAX_PACKET_SIZE, NULL, 0);
Init.EPOut = USB_AddEP(0, USB_TRANSFER_TYPE_BULK, USB_MAX_PACKET_SIZE,
_abOutBuffer, USB_MAX_PACKET_SIZE);
USB_BULK_Add(&Init);
}
Member Description
EPIn Endpoint for sending data to the host.
EPOut Endpoint for receiving data from the host
Table 5.17: USB_BULK_INIT_DATA elements
112 CHAPTER 5 Bulk communication
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
5.5.3.2 USB_ON_RX_FUNC
Description
Callback function prototype that is used when calling the USB_BULK_SetOnRXHook()
function.
Prototype
typedef void USB_ON_RX_FUNC(const U8 * pData, unsigned NumBytes);
Member Description
pData Pointer to the data that have been received.
NumBytes Number of bytes that have been received.
Table 5.18: USB_ON_RX_FUNC elements
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
113
5.6 Host API
This chapter describes the functions that can be used with the Windows host system.
General information
To communicate with the target USB-Bulk stack, the sample application project
includes USB-Bulk specific source and header files (USBBulk.c, USBBULK.h). These
files contain API functions to communicate with the USB-Bulk target through the
USB-Bulk driver.
Purpose of the USB Host API functions
To have an easy start-up when writing an application on the host side, these API
functions have a simple interface and handle all required operations to communicate
with the target USB-Bulk stack.
Therefore, all operations that need to open a channel, writing to or reading from the
USB-Bulk stack are handled internally by the provided API functions.
Additional information can also be retrieved from the USB driver.
114 CHAPTER 5 Bulk communication
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
5.6.1 Host API list
The functions below are available on the host (Windows PC) side.
Function Description
USB-Bulk basic functions
USBBULK_Open() Opens pipes to communicate with the
first USB-Bulk device.
USBBULK_OpenEx() Opens pipes to communicate with a spec-
ified USB-Bulk device.
USBBULK_Close()
Closes the pipes which are used for the
communication with the first USB-Bulk
device.
USBBULK_CloseEx()
Closes the pipes which are used for the
communication to a specified USB-Bulk
device.
USB-Bulk direct input/output functions
USBBULK_Read() Reads data from the first USB-Bulk
device.
USBBULK_ReadEx() Reads data from a specified USB-Bulk
device.
USBBULK_Write() Writes data to the first USB-Bulk device.
USBBULK_WriteEx() Writes data to a specified USB-Bulk
device.
USBBULK_WriteRead() Reads and writes data from/to the first
USB-Bulk device.
USBBULK_WriteReadEx() Reads and writes data from/to a specified
USB-Bulk device.
USB-Bulk control functions
USBBULK_GetDriverCompileDate() Gets the compile date and time of the
USB-Bulk driver.
USBBULK_GetDriverVersion() Retrieves the version of the USB-Bulk
driver.
USBBULK_GetConfigDescriptor()
Gets the received target USB configura-
tion descriptor of the first USB-Bulk
device.
USBBULK_GetConfigDescriptorEx()
Gets the received target USB configura-
tion descriptor of a specified USB-Bulk
device.
USBBULK_GetMode() Returns the read operation mode of the
USB-Bulk device.
USBBULK_GetModeEx() Returns the read operation mode of the
USB-Bulk driver.
USBBULK_GetNumAvailableDevices() Returns the number of connected USB-
Bulk devices.
USBBULK_GetReadMaxTransferSize()
Retrieves the maximum transfer size of a
read transaction the driver can receive
from an application.
USBBULK_GetReadMaxTransferSizeEx()
Retrieves the maximum transfer size of a
read transaction the driver can receive
from an application.
USBBULK_GetSN() Returns the serial number of the USB tar-
get device.
USBBULK_GetWriteMaxTransferSize()
Retrieves the maximum transfer size of a
write transaction the driver can handle
from an application.
Table 5.19: Host API function list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
115
USBBULK_GetWriteMaxTransferSizeEx()
Retrieves the maximum transfer size of a
write transaction the driver can handle
from an application.
USBBULK_SetMode() Sets the read operation mode of the
USB-Bulk driver.
USBBULK_SetModeEx() Sets the read operation mode of the
USB-Bulk driver.
USBBULK_SetTimeout() Sets a read timeout for a read transac-
tion.
USBBULK_SetTimeoutEx() Sets a read timeout for a read transac-
tion.
USBBULK_SetUSBId() Sets the vendor Id and product id that
are used for connecting to the device.
Function Description
Table 5.19: Host API function list
116 CHAPTER 5 Bulk communication
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
5.6.2 USB-Bulk Basic functions
5.6.2.1 USBBULK_Open()
Description
Opens a read and write connection to the first connected target device using emUSB-
Bulk.
Prototype
void * USBBULK_Open(void);
Return value
'!= NULL' if a connection to the target running emUSB-Bulk could be established.
'== NULL' if a connection could not be established.
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
117
5.6.2.2 USBBULK_OpenEx()
Description
Opens a read and write connection to a specified device using the emUSB-Bulk ker-
nel-mode driver.
Prototype
void * USBBULK_OpenEx(unsigned Id);
Return value
'!= NULL' if a connection to the target running emUSB-Bulk could be established.
'== NULL' if a connection could not be established.
Parameter Description
Id Id number of the device [0..31].
Table 5.20: USBBULK_OpenEx() parameter list
118 CHAPTER 5 Bulk communication
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
5.6.2.3 USBBULK_Close()
Description
Closes all connections to the first target device using emUSB-Bulk.
Prototype
void USBBULK_Close(void);
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
119
5.6.2.4 USBBULK_CloseEx()
Description
Closes all connections to a specified device using emUSB-Bulk.
Prototype
void USBBULK_CloseEx(unsigned Id);
Parameter Description
Id Id number of the device [0..31].
Table 5.21: USBBULK_CloseEx() parameter list
120 CHAPTER 5 Bulk communication
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
5.6.3 USB-Bulk direct input/output functions
5.6.3.1 USBBULK_Read()
Description
Reads data from the first target device running emUSB-Bulk.
Prototype
int USBBULK_Read(void * pBuffer, unsigned NumBytes);
Return value
'== NumBytes': All bytes have successfully been read.
'< NumBytes': A timeout occurred during read, when the emUSB driver is in normal
mode, otherwise (short-read mode) the emUSB driver returns the number of bytes
that have been read from the device before a timeout occured (less than NumBytes).
’== -1’: Cannot read from the device.
Additional information
USBBULK_Read() sends the read request to the USB-Bulk driver. Because the driver
can only read a certain number of bytes from the device (the default value is 64
Kbytes) the driver will abort the transaction.
Therefore if NumBytes exceeds this limit, USBBULK_Read() will read the desired Num-
Bytes in chunks of the maximum read size the driver can handle.
Parameter Description
pBuffer Pointer to a buffer where the received data will be stored.
NumBytes Number of bytes to read.
Table 5.22: USBBULK_Read() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
121
5.6.3.2 USBBULK_ReadEx()
Description
Reads data from a specified target device running emUSB-Bulk.
Prototype
int USBBULK_ReadEx(unsigned Id, void * pBuffer, unsigned NumBytes);
Return value
'== NumBytes': All bytes have successfully been read.
'< NumBytes': A timeout occurred during read, when the emUSB driver is in normal
mode. Otherwise the emUSB driver returns the number of bytes that have been read
from the device.
’== -1’: Cannot read from device.
Additional information
USBBULK_ReadEx() sends the read request to the emUSB driver. Because the driver
can only read a certain amount of bytes from the device (the default value is 64
Kbytes) the driver will abort the transaction.
Therefore, if NumBytes exceeds this limit, USBBULK_Read() will read the desired Num-
Bytes in chunks of the maximum read size the driver can handle.
Parameter Description
Id Id number of the device [0..31].
pBuffer Pointer to a buffer where the received data will be stored.
NumBytes Number of bytes to read.
Table 5.23: USBBULK_ReadEx() parameter list
122 CHAPTER 5 Bulk communication
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
5.6.3.3 USBBULK_Write()
Description
Writes data to the first target device running emUSB-Bulk.
Prototype
int USBBULK_Write(const void * pBuffer, unsigned NumBytes);
Return value
'== NumBytes': All bytes have successfully been written.
'< NumBytes': A write error occurred.
Additional information
USBBULK_Write() sends the write request to the emUSB driver. Because the driver
can only write a certain amount of bytes to device (the default value is 64 Kbytes)
the driver will abort the transaction.
Therefore if NumBytes exceeds this limit, USBBULK_Write() will write the desired
NumBytes in chunks of the maximum write size the driver can handle.
Parameter Description
pBuffer Pointer to a buffer to transfer.
NumBytes Number of bytes to write.
Table 5.24: USBBULK_Write() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
123
5.6.3.4 USBBULK_WriteEx()
Description
Writes data to a specified target device running emUSB-Bulk.
Prototype
int USBBULK_WriteEx(unsigned Id, const void * pBuffer, unsigned NumBytes);
Return value
'== NumBytes': All bytes have successfully been written.
'< NumBytes': A write error occurred.
Additional information
USBBULK_WriteEx() sends the write request to the emUSB driver. Since the driver
can only write a certain amount of bytes to the device (the default value is 64
Kbytes) the driver will abort the transaction.
Therefore if NumBytes exceeds this limit, USBBULK_Write() will write the desired
NumBytes in chunks of the maximum write size the driver can handle.
Parameter Description
Id Id number of device [0..31].
pBuffer Pointer to a buffer to transfer.
NumBytes Number of bytes to write.
Table 5.25: USBBULK_WriteEx() parameter list
124 CHAPTER 5 Bulk communication
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
5.6.3.5 USBBULK_WriteRead()
Description
Writes and reads data to and from the first target device running emUSB-Bulk.
Prototype
int USBBULK_WriteRead(const void * pWrBuffer, unsigned WrNumBytes
void * pRdBuffer, unsigned RdNumBytes);
Return value
'== NumBytes': All bytes have successfully been read after writing the data.
'< NumBytes': A timeout occurred during read, when the emUSB driver is in normal
mode. Otherwise the emUSB driver returns the number of bytes that have been read
from the device.
’== -1’: Cannot read from the device after write.
Additional information
This function cannot be used with short mode enabled.
Parameter Description
pWrBuffer Pointer to a buffer to transfer.
WrNumBytes Number of bytes to write.
pRdBuffer Pointer to a buffer where the received data will be stored.
RdNumBytes Number of bytes to read.
Table 5.26: USBBULK_WriteRead() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
125
5.6.3.6 USBBULK_WriteReadEx()
Description
Writes and reads data to and from specified target device running emUSB-Bulk.
Prototype
int USBBULK_WriteReadEx(unsigned Id,
const void * pWrBuffer,
unsigned WrNumBytes
void * pRdBuffer,
unsigned RdNumBytes);
Return value
'== NumBytes': All bytes have successfully been read after writing the data.
'< NumBytes': A timeout occurred during read, when the emUSB driver is in normal
mode, otherwise the emUSB driver returns the number of bytes that have been read
from device.
’== -1’ - Cannot read from the device after write.
Additional information
This function cannot be used with short mode enabled.
Parameter Description
Id Id number of device [0..31].
pWrBuffer Pointer to a buffer to transfer.
WrNumBytes Number of bytes to write.
pRdBuffer Pointer to a buffer where the received data will be stored.
RdNumBytes Number of bytes to read.
Table 5.27: USBBULK_WriteReadEx() parameter list
126 CHAPTER 5 Bulk communication
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
5.6.4 USB-Bulk Control functions
5.6.4.1 USBBULK_GetDriverCompileDate()
Description
Gets the compile date and time of the emUSB bulk communication driver.
Prototype
unsigned USBBULK_GetDriverCompileDate(char * s, unsigned Size);
Return value
If the function succeeds, the return value is nonzero and the buffer pointed by s con-
tains the compile date and time of the emUSB driver in the standard format:
mm dd yyyy hh:mm:ss
If the function fails, the return value is zero.
Parameter Description
sPointer to a buffer to store the compile date string.
Size Size, in bytes, of the buffer pointed to by s.
Table 5.28: USBBULK_GetDriverCompileDate() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
127
5.6.4.2 USBBULK_GetDriverVersion()
Description
Retrieves the version of the emUSB bulk communication driver.
Prototype
unsigned USBBULK_GetDriverVersion(void);
Return value
If the function succeeds, the return value is the driver version of the driver as deci-
mal value:
<Major Version><Minor Version><Subversion>. 24201 means 2.42a
If the function fails, the return value is zero; the version could not be retrieved.
128 CHAPTER 5 Bulk communication
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
5.6.4.3 USBBULK_GetConfigDescriptor()
Description
Gets the received target USB configuration descriptor of the first device running
emUSB-Bulk.
Prototype
int USBBULK_GetConfigDescriptor(void * pBuffer, int Size);
Return value
If the function succeeds, the return value is nonzero and the buffer pointed by
pBuffer contains the USB target device configuration descriptor.
If the function fails, the return value is zero.
Parameter Description
pBuffer Pointer to a buffer to store the config descriptor.
Size Number of bytes to read.
Table 5.29: USBBULK_GetConfigDescriptor() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
129
5.6.4.4 USBBULK_GetConfigDescriptorEx()
Description
Gets the received target USB configuration descriptor of a specified device running
emUSB-Bulk.
Prototype
int USBBULK_GetConfigDescriptor(unsigned Id, void * pBuffer, int Size);
Return value
If the function succeeds, the return value is nonzero and the buffer pointed by
pBuffer contains the USB target device configuration descriptor.
If the function fails, the return value is zero.
Parameter Description
Id Id number of the device [0..31].
pBuffer Pointer to a buffer to store the config descriptor.
Size Number of bytes to read.
Table 5.30: USBBULK_GetConfigDescriptorEx() parameter list
130 CHAPTER 5 Bulk communication
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
5.6.4.5 USBBULK_GetMode()
Description
Returns the read operation mode of the driver for the first device running emUSB-
Bulk.
Prototype
unsigned USBBULK_GetMode(void);
Return value
USBBULK_MODE_BIT_ALLOW_SHORT_READ - Short read mode is enabled.
0 - Short read mode is disabled.
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
131
5.6.4.6 USBBULK_GetModeEx()
Description
Returns the read operation mode of the driver for a specified device running emUSB-
Bulk.
Prototype
unsigned USBBULK_GetModeEx(unsigned Id);
Return value
USBBULK_MODE_BIT_ALLOW_SHORT_READ - Short read mode is enabled.
0 - Short read mode is disabled.
Parameter Description
Id Id number of device [0..31].
Table 5.31: USBBULK_GetModeEx() parameter list
132 CHAPTER 5 Bulk communication
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
5.6.4.7 USBBULK_GetNumAvailableDevices()
Description
Returns the number of connected USB-Bulk devices.
Prototype
unsigned USBBULK_GetNumAvailableDevices(U32 * pMask);
Return value
If the function succeeds, the return value is the number of available devices running
emUSB-Bulk. For each emUSB device that is connected, a bit in pMask is set.
For example if device 0 and device 2 are connected to the host, the value pMask
points to will be 0x00000005.
If the function fails, the return value is zero.
Parameter Description
pMask Pointer to a U32 variable to receive the connected device mask. This
parameter can be NULL.
Table 5.32: USBBULK_GetNumAvailableDevices() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
133
5.6.4.8 USBBULK_GetReadMaxTransferSize()
Description
Retrieves the maximum transfer size of a read transaction the driver can receive
from an application for the first device running emUSB-Bulk.
Prototype
unsigned USBBULK_GetReadMaxTransferSize(void);
Return value
If the function succeeds, the return value is the maximum transfer size in bytes the
driver can accept from an application.
If the function fails, the return value is zero.
134 CHAPTER 5 Bulk communication
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
5.6.4.9 USBBULK_GetReadMaxTransferSizeEx()
Description
Retrieves the maximum transfer size of a read transaction the driver can receive
from an application for a specified device running emUSB-Bulk.
Prototype
unsigned USBBULK_GetReadMaxTransferSizeEx(unsigned Id);
Return value
If the function succeeds, the return value is the maximum transfer size in bytes the
driver can accept from an application.
If the function fails, the return value is zero.
Parameter Description
Id Id number of device [0..31].
Table 5.33: USBBULK_GetReadMaxTransferSizeEx() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
135
5.6.4.10 USBBULK_GetSN()
Description
Retrieves the USB serial number as a string that was returned by the device during
enumeration.
Prototype
int USBBULK_GetSN(unsigned Id, char * pBuffer, unsigned NumBytes);
Return value
If the function succeeds, the return value is nonzero and the buffer pointed by
pBuffer contains the null-terminated serial number of the device running emUSB-
Bulk.
If the function fails, the return value is zero.
Parameter Description
Id Id number of device [0..31].
pBuffer Pointer to a buffer to store the serial number of the device.
NumBytes Size of the buffer in bytes.
Table 5.34: USBBULK_GetSN() parameter list
136 CHAPTER 5 Bulk communication
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
5.6.4.11 USBBULK_GetWriteMaxTransferSize()
Description
Retrieves the maximum transfer size of a write transaction the driver can handle
from an application (for the first device running emUSB-Bulk).
Prototype
unsigned USBBULK_GetWriteMaxTransferSize(void);
Return value
If the function succeeds, the return value is the maximum transfer size in bytes the
driver can accept from an application to send data to the target device.
If the function fails, the return value is zero.
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
137
5.6.4.12 USBBULK_GetWriteMaxTransferSizeEx()
Description
Retrieves the maximum transfer size of a write transaction the driver can handle
from an application for a specified device running emUSB-Bulk.
Prototype
unsigned USBBULK_GetWriteMaxTransferSizeEx(unsigned Id);
Return value
If the function succeeds, the return value is the maximum transfer size in bytes the
driver can accept from an application to send data to the target device.
If the function fails, the return value is zero.
Parameter Description
Id Id number of device [0..31].
Table 5.35: USBBULK_GetWriteMaxtransferSizeEx() parameter list
138 CHAPTER 5 Bulk communication
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
5.6.4.13 USBBULK_SetMode()
Description
Sets the read operation mode of the driver for a device running emUSB-Bulk.
Prototype
unsigned USBBULK_SetMode(unsigned Mode);
Return value
If the function succeeds, the return value is nonzero. The read and write mode for
the driver has been successfully set.
If the function fails, the return value is zero.
Additional information
USBBULK_MODE_BIT_ALLOW_SHORT_READ allows short read transfers. Short transfers
are transfers of less bytes than requested. If this bit is specified, the read function
USBBULK_Read() returns as soon as data is available, even if it is just a single byte.
Example
static void _TestMode(void) {
unsigned Mode;
char * pText;
Mode = USBBULK_GetMode();
if (Mode & USBBULK_MODE_BIT_ALLOW_SHORT_READ) {
pText = "USE_SHORT_MODE";
} else {
pText = "USE_NORMAL_MODE";
}
printf("USB-Bulk driver is in %s\n", pText);
printf("Set mode to USBBULK_MODE_BIT_ALLOW_SHORT_READ\n");
USBBULK_SetMode(USBBULK_MODE_BIT_ALLOW_SHORT_READ);
Mode = USBBULK_GetMode();
if (Mode & USBBULK_MODE_BIT_ALLOW_SHORT_READ) {
pText = "USE_SHORT_MODE";
} else {
pText = "USE_NORMAL_MODE";
}
printf("USB-Bulk driver is now in %s\n", pText);
}
Parameter Description
Mode
Read and write mode for the USB-Bulk driver.
This is a combination of the following flags, combined by binary OR:
USBBULK_MODE_BIT_ALLOW_SHORT_READ
Table 5.36: USBBULK_SetMode() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
139
5.6.4.14 USBBULK_SetModeEx()
Description
Sets the read operation mode of the driver for a specified device running emUSB-
Bulk.
Prototype
unsigned USBBULK_SetModeEx(unsigned Id, unsigned Mode);
Return value
If the function succeeds, the return value is nonzero. The read and write mode for
the driver has been successfully set.
If the function fails, the return value is zero.
Additional information
USBBULK_MODE_BIT_ALLOW_SHORT_READ allows short read transfers. Short transfers
are transfers of less bytes than requested. If this bit is specified, the read function
USBBULK_ReadEx() returns as soon as data is available, even if it is just a single
byte.
Example
static void _TestModeEx(unsigned DeviceId) {
unsigned Mode;
char * pText;
Mode = USBBULK_GetModeEx(DeviceId);
if (Mode & USBBULK_MODE_BIT_ALLOW_SHORT_READ) {
pText = "USE_SHORT_MODE";
} else {
pText = "USE_NORMAL_MODE";
}
printf("USB-Bulk driver is in %s for device %d\n", pText, DeviceId);
printf("Set mode to USBBULK_MODE_BIT_ALLOW_SHORT_READ\n");
USBBULK_SetModeEx(DeviceId, USBBULK_MODE_BIT_ALLOW_SHORT_READ);
Mode = USBBULK_GetModeEx(DeviceId);
if (Mode & USBBULK_MODE_BIT_ALLOW_SHORT_READ) {
pText = "USE_SHORT_MODE";
} else {
pText = "USE_NORMAL_MODE";
}
printf("USB-Bulk driver is now in %s for device %d\n", pText, DeviceId);
}
Parameter Description
Id Id of the device.
Mode
Read and write mode for the USB-Bulk driver.
This is a combination of the following flags, combined by binary or:
USBBULK_MODE_BIT_ALLOW_SHORT_READ
Table 5.37: USBBULK_SetModeEx() parameter list
140 CHAPTER 5 Bulk communication
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
5.6.4.15 USBBULK_SetTimeout()
Description
Sets a read timeout for a read operation to the first device running emUSB-Bulk.
Prototype
void USBBULK_SetTimeout(int Timeout);
Parameter Description
Timeout Timeout in milliseconds set for a read operation.
Table 5.38: USBBULK_SetTimeout() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
141
5.6.4.16 USBBULK_SetTimeoutEx()
Description
Sets a read timeout for a read operation.
Prototype
void USBBULK_SetTimeout(unsigned Id, int Timeout);
Parameter Description
Id Id number of device [0..31].
Timeout Timeout in milliseconds set for a read operation.
Table 5.39: USBBULK_SetTimeOutEx() parameter list
142 CHAPTER 5 Bulk communication
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
5.6.4.17 USBBULK_SetUSBId()
Description
Sets the Vendor ID and product ID that are used for connecting to the device.
Prototype
void USBBULK_SetUSBId(U16 VendorId, U16 ProductId);
Additional information
It is necessary to call this function before opening any connection to the device.
The initial values for these IDs are:
VendorId = 0x8765
ProductId = 0x1234
Parameter Description
VendorId The vendor ID that was assigned by USB.org.
ProductId The product ID that is used for the device.
Table 5.40: USBBULK_SetUSBId() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
143
Chapter 6
Bulk Host API V2
This chapter describes a new version of the Bulk Host API.
144 CHAPTER 6 Bulk Host API V2
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
6.1 Bulk Host API V2
This chapter describes the functions that can be used with the Windows host system.
General information
The Bulk API V2 was introduced because the Bulk API V1 is not as flexible as required
by modern-day applications.
Improvements in the Bulk API V2 include but are not limited to:
Dynamic addition of enumerated devices
Run-time configuration of Vendor IDs and Product IDs
Masking of multiple Product and Vendor IDs
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
145
6.1.1 Bulk Host API V2 list
The functions below are available on the host (Windows PC) side.
Function Description
USB-Bulk basic functions
USBBULK_Open() Opens an existing device.
USBBULK_Close() Closes an opened device.
USBBULK_Init() Initializes the API module.
USBBULK_Exit() Called on exit.
USBBULK_SetUSBId() Sets the Vendor and Product IDs.
USB-Bulk direct input/output functions
USBBULK_Read() Reads from an opened device.
USBBULK_Write() Writes data to the device.
USBBULK_WriteRead() Writes and reads from the device.
USBBULK_CancelRead() Cancels an initiated read.
USBBULK_ReadTimed() Reads from an opened device with a
timeout.
USBBULK_WriteTimed() Writes data to the device with a time-
out.
USBBULK_FlushRx() Removes data from the receive buffer.
USB-Bulk control functions
USBBULK_GetConfigDescriptor() Returns the configuration descriptor of
the device.
USBBULK_GetMode() Returns the transfer mode of the
device.
USBBULK_GetReadMaxTransferSize() Returns the max size the driver can
read at once.
USBBULK_GetWriteMaxTransferSize() Returns the max size the driver can
write at once.
USBBULK_ResetPipe() Resets the pipes that are opened to
the device.
USBBULK_ResetDevice() Resets the device via a USB reset.
USBBULK_SetMode() Set the read and write mode of the
device.
USBBULK_SetReadTimeout() Set the read timeout for an opened
device.
USBBULK_SetWriteTimeout() Set the write timeout for an opened
device.
USBBULK_GetEnumTickCount() Returns the time when the USB device
has been enumerated.
USBBULK_GetReadMaxTransferSizeDown() Returns the max read transfer size of
the device.
USBBULK_GetWriteMaxTransferSizeDown() Returns the max write transfer size of
the device.
USBBULK_SetReadMaxTransferSizeDown() Set the max read transfer size of the
device.
USBBULK_SetWriteMaxTransferSizeDown() Set the max write transfer size of the
device.
USBBULK_GetSN() Gets the serial number of the device.
USBBULK_GetDevInfo() Retrieves information about an opened
USBBULK device.
USBBULK_GetProductName() Returns the product name.
USBBULK_GetVendorName() Returns the vendor name.
Table 6.1: Bulk Host API V2 function list
146 CHAPTER 6 Bulk Host API V2
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
USB-Bulk general GET fu nctions
USBBULK_GetDriverCompileDate() Gets the compile date of the driver.
USBBULK_GetDriverVersion() Returns the driver version.
USBBULK_GetVersion() Returns the USBBULK API version.
USBBULK_GetNumAvailableDevices() Returns the number of available
devices.
USBBULK_GetUSBId() Returns the set Product and Vendor
IDs.
Data structures
USBBULK_DEV_INFO Device information structure (Vendor
ID, Product ID, SN, Device Name).
Function Description
Table 6.1: Bulk Host API V2 function list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
147
6.1.2 USB-Bulk Basic functions
6.1.2.1 USBBULK_Open()
Description
Opens an existing device. The id of the device can be retrieved by the function
USBBULK_GetNumAvailableDevices() via the pDeviceMask parameter. Each bit set in
the DeviceMask represents an available device. Currently 32 devices can be managed
at once.
Prototype
USBBULK_API USB_BULK_HANDLE WINAPI USBBULK_Open (unsigned DevIndex);
Return value
!= 0 - Handle to the opened device.
== 0 - Device cannot be opened.
Parameter Description
Id 0..31 Device Id to be opened.
Table 6.2: USBBULK_Open() parameter list
148 CHAPTER 6 Bulk Host API V2
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
6.1.2.2 USBBULK_Close()
Description
Closes an opened device.
Prototype
USBBULK_API void WINAPI USBBULK_Close (USB_BULK_HANDLE hDevice);
Parameter Description
hDevice Handle to the device that shall be closed.
Table 6.3: USBBULK_Close() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
149
6.1.2.3 USBBULK_Init()
Description
This function needs to be called before any other. This ensures that all structures and
threads are initialized. It also sets a callback in order to be notified when a device is
added or removed.
Prototype
USBBULK_API void WINAPI USBBULK_Init(USBBULK_NOTIFICATION_FUNC *
pfNotification, void * pContext);
Example
U32 DeviceMask;
/*********************************************************************
*
* _OnDevNotify
*
* Function description:
* Is called when a new device is found or an existing device is removed.
*
* Parameters:
* pContext - Pointer to a context given when USBBULK_Init is called
* Index - Device Index that has been added or removed.
* Event - Type of event, currently the following are available:
* USBBULK_DEVICE_EVENT_ADD
* USBBULK_DEVICE_EVENT_REMOVE
*
*/
static void __stdcall _OnDevNotify(void * pContext,
unsigned Index,
USBBULK_DEVICE_EVENT Event) {
switch(Event) {
case USBBULK_DEVICE_EVENT_ADD:
printf("The following DevIndex has been added: %d", Index);
NumDevices = USBBULK_GetNumAvailableDevices(&DeviceMask);
break;
case USBBULK_DEVICE_EVENT_REMOVE:
printf("The following DevIndex has been removed: %d", Index);
NumDevices = USBBULK_GetNumAvailableDevices(&DeviceMask);
break;
}
}
void MainTask(void) {
<...>
USBBULK_Init(_OnDevNotify, NULL);
<...>
}
Parameter Description
pfNotification Pointer to the user callback.
pContext Context data that shall be called with the callback function.
Table 6.4: USBBULK_Init() parameter list
150 CHAPTER 6 Bulk Host API V2
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
6.1.2.4 USBBULK_Exit()
Description
This is a cleanup function, it shall be called when exiting the application.
Prototype
USBBULK_API void WINAPI USBBULK_Exit(void);
Additional information
We recommend to call this function before exiting the application in order to remove
all handles and resources that have been allocated.
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
151
6.1.2.5 USBBULK_SetUSBId()
Description
Set the Vendor and Product ID mask the USBBULK API should look for.
Prototype
USBBULK_API void WINAPI USBBULK_SetUSBId(U16 VendorId, U16 ProductId);
Additional information
It is necessary to call this function first before opening any connection to the device.
The initial values for these IDs are:
VendorId = 0x8765
ProductId = 0x1234
Parameter Description
VendorId The desired Vendor ID mask that shall be used with the USBBULK
API
ProductId The desired Product ID mask that shall be used with the USBBULK
API
Table 6.5: USBBULK_SetUSBId() parameter list
152 CHAPTER 6 Bulk Host API V2
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
6.1.3 USB-Bulk direct input/output functions
6.1.3.1 USBBULK_Read()
Description
Reads data from target device running emUSB-Bulk.
Prototype
USBBULK_API int WINAPI USBBULK_Read (USB_BULK_HANDLE hDevice,
void * pBuffer, int NumBytes);
Return value
'== NumBytes': All bytes have successfully been read.
'< NumBytes': A timeout occurred during read, when the emUSB driver is in normal
mode, otherwise the emUSB driver returns the number of bytes that have been read
from device.
’<= -1’: Cannot read from the device.
Additional information
USBBULK_Read() sends the read request to the USB-Bulk driver. Because the driver
can only read a certain amount of bytes from the device (the default value is 64
Kbytes) the driver will abort the transaction.
Therefore if NumBytes exceeds this limit, USBBULK_Read() will read the desired Num-
Bytes in chunks of the maximum read size the driver can handle.
Parameter Description
hDevice Handle to the opened device.
pBuffer Pointer to a buffer that shall store the data.
NumBytes Number of bytes to be read.
Table 6.6: USBBULK_Read() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
153
6.1.3.2 USBBULK_Write()
Description
Writes data to the device.
Prototype
USBBULK_API int WINAPI USBBULK_Write (USB_BULK_HANDLE hDevice,
const void * pBuffer, int NumBytes);
Return value
'== NumBytes': All bytes have successfully been written.
'< NumBytes': A write error occurred.
’<= -1’: Cannot write to the device.
Additional information
USBBULK_Write() sends the write request to the emUSB driver. Because the driver
can only write a certain amount of bytes to device (the default value is 64 Kbytes)
the driver will abort the transaction.
Therefore if NumBytes exceeds this limit, USBBULK_Write() will write the desired
NumBytes in chunks of the maximum write size the driver can handle.
Parameter Description
hDevice Handle to the opened device.
pBuffer Pointer to a buffer that contains the data.
NumBytes Number of bytes to be written.
Table 6.7: USBBULK_Write() parameter list
154 CHAPTER 6 Bulk Host API V2
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
6.1.3.3 USBBULK_WriteRead()
Description
Writes and reads data to and from target device running emUSB-Bulk.
Prototype
USBBULK_API int WINAPI USBBULK_WriteRead(USB_BULK_HANDLE hDevice,
const void * pWrBuffer, int WrNumBytes, void * pRdBuffer, int RdNumBytes);
Return value
'== NumBytes': All bytes have successfully been read after writing the data.
'< NumBytes': A timeout occurred during read, when the emUSB driver is in normal
mode. Otherwise the emUSB driver returns the number of bytes that have been read
from the device.
’<= -1’: Cannot read from the device after write.
Additional information
This function can not be used when short read mode is enabled.
Parameter Description
hDevice Handle to the opened device.
pWrBuffer Pointer to a buffer that contains the data.
WrNumBytes Number of bytes to be written.
pRdBuffer Pointer to a buffer that shall store the data.
RdNumBytes Number of bytes to be read.
Table 6.8: USBBULK_WriteRead() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
155
6.1.3.4 USBBULK_CancelRead()
Description
This function cancels an initiated read operation.
Prototype
USBBULK_API void WINAPI USBBULK_CancelRead(USB_BULK_HANDLE hDevice);
Parameter Description
hDevice Handle to the opened device.
Table 6.9: USBBULK_CancelRead() parameter list
156 CHAPTER 6 Bulk Host API V2
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
6.1.3.5 USBBULK_ReadTimed()
Description
Reads data from target device running emUSB-Bulk within a given timeout.
Prototype
USBBULK_API int WINAPI USBBULK_Read (USB_BULK_HANDLE hDevice,
void * pBuffer,
int NumBytes
unsigned ms);
Return value
'== NumBytes': All bytes have successfully been read.
'< NumBytes': A timeout occurred during read, when the emUSB driver is in normal
mode, otherwise the emUSB driver returns the number of bytes that have been read
from device.
’<= -1’: Cannot read from the device.
Additional information
USBBULK_ReadTimed() sends the read request to the USB-Bulk driver. Because the
driver can only read a certain amount of bytes from the device (the default value is
64 Kbytes) the driver will abort the transaction.
Therefore if NumBytes exceeds this limit, USBBULK_ReadTimed() will read the desired
NumBytes in chunks of the maximum read size the driver can handle.
Parameter Description
hDevice Handle to the opened device.
pBuffer Pointer to a buffer that shall store the data.
NumBytes Number of bytes to be read.
ms Timeout in milliseconds.
Table 6.10: USBBULK_ReadTimed() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
157
6.1.3.6 USBBULK_WriteTimed()
Description
Writes data to the device within a given timeout.
Prototype
USBBULK_API int WINAPI USBBULK_Write (USB_BULK_HANDLE hDevice,
const void * pBuffer,
int NumBytes
unsigned ms);
Return value
'== NumBytes': All bytes have successfully been written.
'< NumBytes': A timeout occurred during write.
'< 0': A write error occurred.
Additional information
USBBULK_WriteTimed() sends the write request to the emUSB driver. Because the
driver can only write a certain amount of bytes to device (the default value is 64
Kbytes) the driver will abort the transaction.
Therefore if NumBytes exceeds this limit, USBBULK_WriteTimed() will write the
desired NumBytes in chunks of the maximum write size the driver can handle.
Parameter Description
hDevice Handle to the opened device.
pBuffer Pointer to a buffer that contains the data.
NumBytes Number of bytes to be written.
ms Timeout in milliseconds.
Table 6.11: USBBULK_WriteTimed() parameter list
158 CHAPTER 6 Bulk Host API V2
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
6.1.3.7 USBBULK_FlushRx()
Description
This function removes all data which was cached by the API from the internal receive
buffer.
Prototype
USBBULK_API int WINAPI USBBULK_FlushRx (USB_BULK_HANDLE hDevice);
Parameter Description
hDevice Handle to the opened device.
Table 6.12: USBBULK_FlushRx() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
159
6.1.4 USB-Bulk Control functions
6.1.4.1 USBBULK_GetConfigDescriptor()
Description
Gets the received target USB configuration descriptor of a specified device running
emUSB-Bulk.
Prototype
USBBULK_API int WINAPI USBBULK_GetConfigDescriptor(USB_BULK_HANDLE hDevice,
void* pBuffer, int Size);
Return value
== 0 - Operation failed. Either an invalid handle was used or the buffer that shall
store the config descriptor is too small.
!= 0 - The operation was successful.
If the function succeeds, the buffer pointed by pBuffer contains the USB target
device configuration descriptor.
Parameter Description
hDevice Handle to an opened device.
pBuffer Pointer to the buffer that shall store the descriptor.
Size Size of the buffer, given in bytes.
Table 6.13: USBBULK_GetConfigDescriptor() parameter list
160 CHAPTER 6 Bulk Host API V2
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
6.1.4.2 USBBULK_GetMode()
Description
Returns the current mode of the device.
Prototype
USBBULK_API unsigned WINAPI USBBULK_GetMode(USB_BULK_HANDLE hDevice);
Return value
USBBULK_MODE_BIT_ALLOW_SHORT_READ - Short read mode is enabled.
USBBULK_MODE_BIT_ALLOW_SHORT_WRITE - Short write mode is enabled.
0 - Normal mode is set.
Additional information
A combination of both modes is possible.
Parameter Description
hDevice Handle to an opened device.
Table 6.14: USBBULK_GetMode() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
161
6.1.4.3 USBBULK_GetReadMaxTransferSize()
Description
Retrieves the maximum transfer size of a read transaction the driver can receive
from an application for a specified device running emUSB-Bulk.
Prototype
USBBULK_API unsigned WINAPI USBBULK_GetReadMaxTransferSize(USB_BULK_HANDLE
hDevice);
Return value
== 0 - Operation failed. Either an invalid handle was used or
the transfer size cannot be read.
!= 0 - The operation was successful.
Parameter Description
hDevice Handle to an opened device.
Table 6.15: USBBULK_GetReadMaxTransferSize() parameter list
162 CHAPTER 6 Bulk Host API V2
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
6.1.4.4 USBBULK_GetWriteMaxTransferSize()
Description
Retrieves the maximum transfer size of a write transaction the driver can handle
from an application for a specified device running emUSB-Bulk.
Prototype
USBBULK_API unsigned WINAPI USBBULK_GetWriteMaxTransferSize(USB_BULK_HANDLE
hDevice);
Return value
== 0 - Operation failed. Either an invalid handle was used or
the transfer size cannot be read.
!= 0 - The operation was successful.
Parameter Description
hDevice Handle to an opened device.
Table 6.16: USBBULK_GetWriteMaxTransferSize() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
163
6.1.4.5 USBBULK_ResetPipe()
Description
Resets the pipes that are opened to the device.
It also flushes any data the USB bulk driver would cache.
Prototype
USBBULK_API int WINAPI USBBULK_ResetPipe(USB_BULK_HANDLE hDevice);
Return value
== 0 - Operation failed. Either an invalid handle was used or
the pipes cannot be flushed.
!= 0 - The operation was successful.
Parameter Description
hDevice Handle to an opened device.
Table 6.17: USBBULK_ResetPipe() parameter list
164 CHAPTER 6 Bulk Host API V2
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
6.1.4.6 USBBULK_ResetDevice()
Description
Resets the device via a USB reset.
This can be used when the device does not work properly and may be reactivated via
USB reset. This will force a re-enumeration of the device.
Prototype
USBBULK_API int WINAPI USBBULK_ResetDevice(USB_BULK_HANDLE hDevice);
Return value
== 0 - Operation failed. Either an invalid handle was used or
the pipes cannot be flushed.
!= 0 - The operation was successful.
Additional information
After the device has been reset it is necessary to re-open the device as the current
handle will become invalid.
Parameter Description
hDevice Handle to an opened device.
Table 6.18: USBBULK_ResetDevice() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
165
6.1.4.7 USBBULK_SetMode()
Description
Sets the read and write mode of the driver for a specified device running emUSB-
Bulk.
Prototype
USBBULK_API unsigned WINAPI USBBULK_SetMode(USB_BULK_HANDLE hDevice,
unsigned Mode);
Return value
If the function succeeds, the return value is nonzero. The read and write mode for
the driver has been successfully set.
If the function fails, the return value is zero.
Additional information
USBBULK_MODE_BIT_ALLOW_SHORT_READ allows short read transfers. Short transfers
are transfers of less bytes than requested. If this bit is specified, the read function
USBBULK_Read() returns as soon as data is available, even if it is just a single byte.
USBBULK_MODE_BIT_ALLOW_SHORT_WRITE allows short write transfers.
USBBULK_Write() returns after writing the minimal amount of data (either NumBytes
or the maximal write transfer size, which can be read by using the function
USBBULK_GetWriteMaxTransferSize()).
Example
static void _TestMode(USB_BULK_HANDLE hDevice) {
unsigned Mode;
char * pText;
Mode = USBBULK_GetMode(hDevice);
if (Mode & USBBULK_MODE_BIT_ALLOW_SHORT_READ) {
pText = "USE_SHORT_MODE";
} else {
pText = "USE_NORMAL_MODE";
}
printf("USB-Bulk driver is in %s for device %d\n", pText, (int)hDevice);
printf("Set mode to USBBULK_MODE_BIT_ALLOW_SHORT_READ\n");
USBBULK_SetMode(hDevice, USBBULK_MODE_BIT_ALLOW_SHORT_READ);
Mode = USBBULK_GetMode(hDevice);
if (Mode & USBBULK_MODE_BIT_ALLOW_SHORT_READ) {
pText = "USE_SHORT_MODE";
} else {
pText = "USE_NORMAL_MODE";
}
printf("USB-Bulk driver is now in %s for device %d\n", pText,(int)hDevice);
}
Parameter Description
hDevice Handle to an opened device.
Mode
Read and write mode for the USB-Bulk driver.
This is a combination of the following flags, combined by binary or:
USBBULK_MODE_BIT_ALLOW_SHORT_READ
USBBULK_MODE_BIT_ALLOW_SHORT_WRITE
Table 6.19: USBBULK_SetMode() parameter list
166 CHAPTER 6 Bulk Host API V2
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
6.1.4.8 USBBULK_SetReadTimeout()
Description
Setups the default read timeout for an opened device.
Prototype
USBBULK_API void WINAPI USBBULK_SetReadTimeout(USB_BULK_HANDLE hDevice,
int Timeout);
Parameter Description
hDevice Handle to the opened device.
Timeout Timeout in milliseconds.
Table 6.20: USBBULK_SetReadTimeout() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
167
6.1.4.9 USBBULK_SetWriteTimeout()
Description
Sets a default write timeout for an opened device.
Prototype
USBBULK_API void WINAPI USBBULK_SetWriteTimeout (USB_BULK_HANDLE hDevice,
int Timeout);
Parameter Description
hDevice Handle to the opened device.
Timeout Timeout in milliseconds.
Table 6.21: USBBULK_SeWriteTimeout() parameter list
168 CHAPTER 6 Bulk Host API V2
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
6.1.4.10 USBBULK_GetEnumTickCount()
Description
Returns the time when the USB device was enumerated.
Prototype
USBBULK_API U32 WINAPI USBBULK_GetEnumTickCount(USB_BULK_HANDLE hDevice);
Return value
The time when the USB device was enumerated by the driver given in Windows timer
ticks (normally 1 ms. ticks).
Parameter Description
hDevice Handle to an opened device.
Table 6.22: USBBULK_GetEnumTickCount() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
169
6.1.4.11 USBBULK_GetReadMaxTransferSizeDown()
Description
Returns the maximum transfer size the driver supports when reading data from the
device. In normal cases the maximum transfer size will be 2048 bytes. As this is a
multiple of the maximum packet size, it is necessary that the device does not send a
NULL-packet in this case. The Windows USB stack will stop reading data from the
USB bus as soon as it reads all requested bytes.
Prototype
USBBULK_API U32 WINAPI USBBULK_GetReadMaxTransferSizeDown(USB_BULK_HANDLE
hDevice);
Return value
!= 0 - Max transfer size the driver will read from device.
== 0 - The transfer size cannot be read.
Parameter Description
hDevice Handle to an opened device.
Table 6.23: USBBULK_GetReadMaxTransferSizeDown() parameter list
170 CHAPTER 6 Bulk Host API V2
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
6.1.4.12 USBBULK_GetWriteMaxTransferSizeDown()
Description
Returns the maximum transfer size the driver will accept when writting data to the
device.
Prototype
USBBULK_API U32 WINAPI USBBULK_GetWriteMaxTransferSizeDown(USB_BULK_HANDLE
hDevice);
Return value
== 0 - Operation failed. Either an invalid handle was used or
the transfer size cannot be read.
!= 0 - The operation was successful.
Parameter Description
hDevice Handle to an opened device.
Table 6.24: USBBULK_GetWriteMaxtransferSizeDown() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
171
6.1.4.13 USBBULK_SetReadMaxTransferSizeDown()
Description
Sets the number of bytes the driver will write down to the device at once.
Prototype
USBBULK_API unsigned WINAPI USBBULK_SetReadMaxTransferSizeDown(
USB_BULK_HANDLE hDevice,
U32 TransferSize);
Return value
== 0 - Operation failed. Either an invalid handle was used or
the mode cannot be set.
!= 0 - The operation was successful.
Parameter Description
hDevice Handle to an opened device.
TransferSize The number of bytes the driver will set as maximum.
Table 6.25: USBBULK_SetReadMaxTransferSizeDown() parameter list
172 CHAPTER 6 Bulk Host API V2
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
6.1.4.14 USBBULK_SetWriteMaxTransferSizeDown()
Description
Sets the number of bytes the driver will write down to the device at once.
Prototype
USBBULK_API unsigned WINAPI USBBULK_SetWriteMaxTransferSizeDown(
USB_BULK_HANDLE hDevice,
U32 TransferSize);
Return value
== 0 - Operation failed. Either an invalid handle was used or
the mode cannot be set.
!= 0 - Max transfer size the driver will read from device.
Parameter Description
hDevice Handle to an opened device.
TransferSize The number of bytes the driver will set as maximum.
Table 6.26: USBBULK_SetWriteMaxTransferSizeDown() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
173
6.1.4.15 USBBULK_GetSN()
Description
Retrieves the USB serial number as a string which was sent by the device during the
enumeration.
Prototype
USBBULK_API unsigned WINAPI USBBULK_GetSN(USB_BULK_HANDLE hDevice,
U8 * pBuffer, unsigned NumBytes);
Return value
== 0 - Operation failed. Either an invalid handle was used or
the serial number cannot be read.
!= 0 - The operation was successful.
If the function succeeds, the return value is nonzero and the buffer pointed by
pBuffer contains the serial number of the device running emUSB-Bulk.
If the function fails, the return value is zero.
Parameter Description
hDevice Handle to an opened device.
pBuffer Pointer to a buffer which shall store the serial number of the device.
NumBytes Size of the buffer given in bytes.
Table 6.27: USBBULK_GetSN() parameter list
174 CHAPTER 6 Bulk Host API V2
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
6.1.4.16 USBBULK_GetDevInfo()
Description
Retrieves information about an opened USBBULK device.
Prototype
USBBULK_API void WINAPI USBBULK_GetDevInfo(USB_BULK_HANDLE hDevice,
USBBULK_DEV_INFO * pDevInfo);
Parameter Description
hDevice Handle to the opened device.
pDevInfo Pointer to a device info structure.
Table 6.28: USBBULK_GetDevInfo() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
175
6.1.4.17 USBBULK_GetProductName()
Description
Retrieves the product name of an opened USBBULK device.
Prototype
USBBULK_API void WINAPI USBBULK_GetProductName(USB_BULK_HANDLE hDevice,
char * sProductName,
unsigned BufferSize);
Parameter Description
hDevice Handle to the opened device.
sProductName Pointer to a buffer where the product name shall be saved.
BufferSize Size of the product name buffer.
Table 6.29: USBBULK_GetProductName() parameter list
176 CHAPTER 6 Bulk Host API V2
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
6.1.4.18 USBBULK_GetVendorName()
Description
Retrieves the vendor name of an opened USBBULK device.
Prototype
USBBULK_API int WINAPI USBBULK_GetVendorName(USB_BULK_HANDLE hDevice,
char * sVendorName,
unsigned BufferSize);
Parameter Description
hDevice Handle to the opened device.
sVendorName Pointer to a buffer where the vendor name shall be saved.
BufferSize Size of the vendor name buffer.
Table 6.30: USBBULK_GetVendorName() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
177
6.1.5 USB-Bulk general GET functions
6.1.5.1 USBBULK_GetDriverCompileDate()
Description
Gets the compile date and time of the emUSB bulk communication driver.
Prototype
USBBULK_API unsigned WINAPI USBBULK_GetDriverCompileDate(char * s,
unsigned Size);
Return value
== 0 - Operation failed. The buffer that shall store the string is too small.
!= 0 - The operation was successful.
If the function succeeds, the return value is nonzero and the buffer pointed by s con-
tains the compile date and time of the emUSB driver in the standard format:
mm dd yyyy hh:mm:ss
Parameter Description
sPointer to a buffer to store the compile date string.
Size Size, in bytes, of the buffer pointed to by s.
Table 6.31: USBBULK_GetDriverCompileDate() parameter list
178 CHAPTER 6 Bulk Host API V2
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
6.1.5.2 USBBULK_GetDriverVersion()
Description
Returns the driver version of the driver, if the driver is loaded. Otherwise the function
will return 0, as it can only determine the driver version when the driver is loaded.
Prototype
USBBULK_API unsigned WINAPI USBBULK_GetDriverVersion(void);
Return value
If the function succeeds, the return value is the driver version of the driver as deci-
mal value:
<Major Version><Minor Version><Subversion>. 24201 (Mmmrr) means 2.42a
If the function fails, the return value is zero; the version could not be retrieved.
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
179
6.1.5.3 USBBULK_GetVersion()
Description
Returns the USBBULK API version.
Prototype
USBBULK_API unsigned WINAPI USBBULK_GetVersion(void);
Return value
The version of the USBBULK API in the following format:
<Major Version><Minor Version><Subversion>. 24201 (Mmmrr) means 2.42a
180 CHAPTER 6 Bulk Host API V2
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
6.1.5.4 USBBULK_GetNumAvailableDevices()
Description
Returns the number of connected USB-Bulk devices.
Prototype
USBBULK_API unsigned WINAPI USBBULK_GetNumAvailableDevices(U32 * pMask);
Return value
The return value is the number of available devices running emUSB-Bulk. For each
emUSB device that is connected, a bit in pMask is set.
For example if device 0 and device 2 are connected to the host, the value pMask
points to will be 0x00000005.
Parameter Description
pMask Pointer to a U32 variable to receive the connected device mask. This
parameter can be NULL.
Table 6.32: USBBULK_GetNumAvailableDevices() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
181
6.1.5.5 USBBULK_GetUSBId()
Description
Returns the set Product and Vendor ID mask that is used with the USBBULK API.
Prototype
USBBULK_API void WINAPI USBBULK_GetUSBId(USB_BULK_HANDLE hDevice,
U16 * pVendorId,
U16 * pProductId);
Parameter Description
hDevice Handle to the opened device.
pVendorId Pointer to a U16 variable that will store the Vendor ID.
pProductId Pointer to a U16 variable that will store the Product ID.
Table 6.33: USBBULK_GetUSBId() parameter list
182 CHAPTER 6 Bulk Host API V2
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
6.1.6 Data structures
6.1.6.1 USBBULK_DEV_INFO
Description
A structure which can hold the relavant information about a device.
Prototype
typedef struct _USBBULK_DEV_INFO {
U16 VendorId;
U16 ProductId;
char acSN[256];
char acDevName[256];
} USBBULK_DEV_INFO;
Member Description
VendorId An U16 which holds the device Vendor ID.
ProductId An U16 which holds the device Product ID.
acSN Array of chars which holds the serial number of the device.
acDevName Array of chars which holds the device name.
Table 6.34: USBBULK_DEV_INFO elements
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
183
Chapter 7
Mass Storage Device Class
(MSD)
This chapter gives a general overview of the MSD class and describes how to get the
MSD component running on the target.
184 CHAPTER 7 Mass Storage Device Class (MSD)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
7.1 Overview
The Mass Storage Device (MSD) is a USB class protocol defined by USB Implementers
Forum. The class itself is used to access one or more storage devices such as flash
drives or memory sticks.
As the USB mass storage device class is well standardized, every major operating
system such as Microsoft Windows (Window ME, Windows 2000, Windows XP, Win-
dows 2003 and Windows Vista), Apple Mac OS X, Linux and many more support it. So
therefore an installation of a custom host USB driver is normally not necessary.
emUSB-MSD comes as a whole packet and contains the following:
Generic USB handling
MSD device class implementation, including support for direct disk and CD-ROM
mode (CD-ROM access is a separate component)
Several storage drivers for handling different devices
Example applications
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
185
7.2 Configuration
7.2.1 Initial configuration
To get emUSB-MSD up and running as well as doing an initial test, the configuration
as it is delivered should not be modified.
7.2.2 Final configuration
The configuration must only be modified, when emUSB is deployed in your final prod-
uct. Refer to Configuration on page 44 for detailed information about the generic
information functions which must be adapted.
In order to comply with the Mass Storage Device Bootability specification, the func-
tion USB_GetSerialNumber() must return a string with at least 12 characters, where
each character is a hexadecimal digit (’0’ though ’9’ or ’A’ through ’F’).
7.2.3 Class specific configuration functions
Beside the generic emUSB-MSD configuration functions, the following additional
functions can be adapted before the emUSB MSD component is used in a final prod-
uct. Example implementations of these functions are supplied in the MSD example
application MSD_FS_Start.c, located in the Application directory of emUSB.
Function Description
emUSB-MSD configuration functions
USB_MSD_GetVendorName() Returns the vendor name.
USB_MSD_GetProductName() Returns the MSD product name.
USB_MSD_GetProductVer() Returns the product version of the MSD device.
USB_MSD_GetSerialNo() Returns the serial number of the MSD device.
Table 7.1: List of MSD class specific configuration functions
186 CHAPTER 7 Mass Storage Device Class (MSD)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
7.2.3.1 USB_MSD_GetVendorName()
Description
Should return the vendor name of the mass storage device.
Prototype
const char * USB_MSD_GetVendorName(U8 Lun);
Example
const char * USB_MSD_GetVendorName(U8 Lun) {
return "Vendor";
}
Additional information
The vendor name is used during the enumeration phase. Together with the product
name and the serial number should it give a detailed information to the user about
which device is connected to the device. The string should be no longer than 8 bytes.
Parameter Description
Lun Specifies the logical unit number whose vendor name shall be
returned.
Table 7.2: USB_MSD_GetVendorName() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
187
7.2.3.2 USB_MSD_GetProductName()
Description
Should return the product name of the mass storage device.
Prototype
const char * USB_MSD_GetProductName(U8 Lun);
Example
const char * USB_GetProductName(U8 Lun) {
return "MSD device";
}
Additional information
The product name string should be no longer than 16 byte.
Parameter Description
Lun Specifies the logical unit number whose product name shall be
returned.
Table 7.3: USB_MSD_GetProductName() parameter list
188 CHAPTER 7 Mass Storage Device Class (MSD)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
7.2.3.3 USB_MSD_GetProductVer()
Description
Should return the product version number of the mass storage device.
Prototype
const char * USB_MSD_GetProductVer(U8 Lun);
Example
const char * USB_MSD_GetProductVer(U8 Lun) {
return "1.00";
}
Additional information
The product version string should be no longer than 8 bytes.
Parameter Description
Lun Specifies the logical unit number whose version shall be returned.
Table 7.4: USB_MSD_GetProductVer() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
189
7.2.3.4 USB_MSD_GetSerialNo()
Description
Should return the product serial number of the mass storage device.
Prototype
const char * USB_MSD_GetSerialNo(U8 Lun);
Example
const char * USB_MSD_GetSerialNo(U8 Lun) {
return "1234657890";
}
Additional information
The serial number string should be no longer than 10 bytes.
Parameter Description
Lun Specifies the logical unit number whose serial number shall be
returned.
Table 7.5: USB_MSD_GetSerialNo() parameter list
190 CHAPTER 7 Mass Storage Device Class (MSD)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
7.2.4 Running the example application
The directory Application contains example applications that can be used with
emUSB and the MSD component. To test the emUSB-MSD component, build and
download the application of choice into the target. Remove the USB connection and
reconnect the target to the host. The target will enumerate and can be accessed via
a file browser.
7.2.4.1 MSD_Start_StorageRAM.c in detail
The main part of the example application USB_MSD_Start_StorageRAM.c is imple-
mented in a single task called MainTask().
/* MainTask() - excerpt from USB_MSD_Start_StorageRAM.c */
void MainTask(void);
void MainTask(void) {
USB_Init();
_AddMSD();
USB_Start();
while (1) {
while ((USB_GetState() & (USB_STAT_CONFIGURED | USB_STAT_SUSPENDED))
!= USB_STAT_CONFIGURED) {
BSP_ToggleLED(0);
USB_OS_Delay(50);
}
BSP_SetLED(0);
USB_MSD_Task();
}
}
The first step is to initialize the USB core stack using USB_Init(). The function
_AddMSD() configures all required endpoints and assigns the used storage medium to
the MSD component.
/* _AddMSD() - excerpt from MSD_Start_StorageRAM.c */
static void _AddMSD(void) {
static U8 _abOutBuffer[USB_MAX_PACKET_SIZE];
USB_MSD_INIT_DATA InitData;
USB_MSD_INST_DATA InstData;
InitData.EPIn = USB_AddEP(1, USB_TRANSFER_TYPE_BULK,
USB_MAX_PACKET_SIZE, NULL, 0);
InitData.EPOut = USB_AddEP(0, USB_TRANSFER_TYPE_BULK, USB_MAX_PACKET_SIZE,
_abOutBuffer, USB_MAX_PACKET_SIZE);
USB_MSD_Add(&InitData);
//
// Add logical unit 0: RAM drive
//
memset(&InstData, 0, sizeof(InstData));
InstData.pAPI = &USB_MSD_StorageRAM;
InstData.DriverData.pStart = (void*)MSD_RAM_ADDR;
InstData.DriverData.NumSectors = MSD_RAM_NUM_SECTORS;
InstData.DriverData.SectorSize = MSD_RAM_SECTOR_SIZE;
USB_MSD_AddUnit(&InstData);
}
The example application uses a RAM disk as storage medium.
The example RAM disk has a size of 23 Kbytes (46 sectors with a sector size of 512
bytes). You can increase the size of the RAM disk by modifying the macros
MSD_RAM_NUM_SECTORS and MSD_RAM_SECTOR_SIZE (in multiples of 512), but the size
must be at least 23 Kbytes otherwise a Windows host cannot format the disk.
/* AddMSD() - excerpt from MSD_Start_StorageRAM.c */
#define MSD_RAM_NUM_SECTORS 46
#define MSD_RAM_SECTOR_SIZE 512
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
191
7.3 Target API
Function Description
API functions
USB_MSD_Add() Adds an MSD-class interface to the
USB stack.
USB_MSD_AddUnit() Adds a mass storage device to the
emUSB-MSD.
USB_MSD_AddCDRom() Adds a CD-ROM device to the emUSB-
MSD.
USB_MSD_SetPreventAllowRemovalHook() Sets a callback function to prevent/
allow removal of storage medium.
USB_MSD_SetPreventAllowRemovalHookEx(
)
Sets a callback function to prevent/
allow removal of storage medium.
USB_MSD_SetReadWriteHook()
Sets a callback function which is called
with every read or write access to the
storage medium.
USB_MSD_Task() Handles the MSD-specific protocol.
USB_MSD_SetStartStopUnitHook() Sets a callback function for the START
STOP UNIT command.
Extended API functions
USB_MSD_Connect() Connects the storage medium to the
MSD.
USB_MSD_Disconnect() Disconnects the storage medium from
the MSD.
USB_MSD_RequestDisconnect() Sets the DisconnectRequest flag.
USB_MSD_UpdateWriteProtect() Updates the IsWriteProtected flag for a
storage medium.
USB_MSD_WaitForDisconnection() Waits for disconnection while timeout
is not reached.
Data structures
USB_MSD_INIT_DATA
emUSB-MSD initialization structure
that is needed when adding an MSD
interface.
USB_MSD_INFO emUSB-MSD storage information.
USB_MSD_INST_DATA Structure that is used when adding a
device to emUSB-MSD.
PREVENT_ALLOW_REMOVAL_HOOK Callback invoked when the storage
medium is removed.
PREVENT_ALLOW_REMOVAL_HOOK_EX Callback invoked when the storage
medium is removed.
READ_WRITE_HOOK Callback invoked when accessing the
storage medium.
USB_MSD_INST_DATA_DRIVER Structure that is passed to the driver.
USB_MSD_STORAGE_API Structure that contains callbacks to
the storage driver.
START_STOP_UNIT_HOOK Callback invoked when the START
STOP UNIT command is received.
Table 7.6: List of emUSB MSD interface functions and data structures
192 CHAPTER 7 Mass Storage Device Class (MSD)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
7.3.1 API functions
7.3.1.1 USB_MSD_Add()
Description
Adds an MSD-class interface to the USB stack.
Prototype
void USB_MSD_Add (const USB_MSD_INIT_DATA * pInitData);
Additional information
After the initialization of general emUSB, this is the first function that needs to be
called when an MSD interface is used with emUSB. The structure USB_MSD_INIT_DATA
must be initialized before USB_MSD_Add() is called. Refer to USB_MSD_INIT_DATA on
page 205 for more information.
Parameter Description
pInitData Pointer to a USB_MSD_INIT_DATA structure.
Table 7.7: USB_MSD_Add() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
193
7.3.1.2 USB_MSD_AddUnit()
Description
Adds a mass storage device to emUSB-MSD.
Prototype
void USB_MSD_AddUnit (const USB_MSD_INST_DATA * pInstData);
Additional information
It is necessary to call this function immediately after USB_MSD_Add().
This function will then add an R/W storage device such as a hard drive, MMC/SD
cards or NAND flash etc., to emUSB-MSD, which then will be used to exchange data
with the host. The structure USB_MSD_INST_DATA must be initialized before
USB_MSD_AddUnit() is called. Refer to USB_MSD_INST_DATA on page 207 for more
information.
Parameter Description
pInstData Pointer to a USB_MSD_INST_DATA structure that is used to add the
desired drive to the USB-MSD stack.
Table 7.8: USB_MSD_AddUnit() parameter list
194 CHAPTER 7 Mass Storage Device Class (MSD)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
7.3.1.3 USB_MSD_AddCDRom()
Description
Adds a CD-ROM device to emUSB-MSD.
Prototype
void USB_MSD_AddCDRom(const USB_MSD_INST_DATA * pInstData);
Additional information
Similar to USB_MSD_AddUnit(), this function should be called after USB_MSD_Add().
The structure USB_MSD_INST_DATA must be initialized before USB_MSD_AddCDRom() is
called. Refer to USB_MSD_INST_DATA on page 207 for more information.
Parameter Description
pInstData Pointer to a USB_MSD_INST_DATA structure that is used to add the
desired drive to the USB-MSD stack.
Table 7.9: USB_MSD_AddCDRom() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
195
7.3.1.4 USB_MSD_SetPreventAllowRemovalHook()
Description
Sets a callback function to prevent/allow removal of storage medium.
Prototype
void USB_MSD_SetPreventAllowRemovalHook(U8 Lun,
PREVENT_ALLOW_REMOVAL_HOOK * pfOnPreventAllowRemoval)
Additional information
The callback is called within the MSD task context. The callback must not block.
Parameter Description
pfOnPreventAllowRemoval
Pointer to the callback function
PREVENT_ALLOW_REMOVAL_HOOK. For detailed information
about the function pointer, refer to
PREVENT_ALLOW_REMOVAL_HOOK on page 208.
Table 7.10: USB_MSD_SetPreventAllowRemovalHook() parameter list
196 CHAPTER 7 Mass Storage Device Class (MSD)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
7.3.1.5 USB_MSD_SetPreventAllowRemovalHookEx()
Description
Sets a callback function to prevent/allow removal of storage medium.
Prototype
void USB_MSD_SetPreventAllowRemovalHookEx(U8 Lun,
PREVENT_ALLOW_REMOVAL_HOOK_EX *
pfOnPreventAllowRemovalEx)
Additional information
The callback is called within the MSD task context. The callback must not block.
Parameter Description
pfOnPreventAllowRemoval
Ex
Pointer to the callback function
PREVENT_ALLOW_REMOVAL_HOOK_EX. For detailed infor-
mation about the function pointer, refer to
PREVENT_ALLOW_REMOVAL_HOOK_EX on page 209.
Table 7.11: USB_MSD_SetPreventAllowRemovalHookEx() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
197
7.3.1.6 USB_MSD_SetReadWriteHook()
Description
Sets a callback function which gives information about the read and write blockwise
operations to the storage medium.
Prototype
void USB_MSD_SetReadWriteHook(U8 Lun, READ_WRITE_HOOK * pfOnReadWrite)
Parameter Description
pfOnReadWrite
Pointer to the callback function READ_WRITE_HOOK. For
detailed information about the function pointer, refer to
READ_WRITE_HOOK on page 210.
Table 7.12: USB_MSD_SetReadWriteHook() parameter list
198 CHAPTER 7 Mass Storage Device Class (MSD)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
7.3.1.7 USB_MSD_Task()
Description
Task that handles the MSD-specific protocol.
Prototype
void USB_MSD_Task(void);
Additional information
After the USB device has been successfully enumerated and configured, the
USB_MSD_Task() should be called. When the device is detached or is suspended,
USB_MSD_Task() will return.
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
199
7.3.2 Extended API functions
7.3.2.1 USB_MSD_Connect()
Description
Connects the storage medium to the MSD module.
Prototype
void USB_MSD_Connect(U8 Lun);
Additional information
The storage medium is initially always connected to the MSD component. This func-
tion is normally used after the storage medium was disconnected via
USB_MSD_Disconnect() to perform file system operations on the device application
side.
Parameter Description
Lun Zero-based index for the unit number.
Using only one storage medium, this parameter is 0.
Table 7.13: USB_MSD_Connect() parameter list
200 CHAPTER 7 Mass Storage Device Class (MSD)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
7.3.2.2 USB_MSD_Disconnect()
Description
Disconnects the storage medium from the MSD module.
Prototype
void USB_MSD_Disconnect(U8 Lun);
Additional information
This function will force the storage medium to be disconnected. The host will be
informed that the medium is not present. In order to reconnect the device to the
host, the function USB_MSD_Connect() shall be used.
See USB_MSD_RequestDisconnect() and USB_MSD_WaitForDisconnection() for a
gracefull disconnection method.
Parameter Description
Lun Zero-based index for the unit number.
Using only one storage medium, this parameter is 0.
Table 7.14: USB_MSD_Disconnect() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
201
7.3.2.3 USB_MSD_RequestDisconnect()
Description
Sets the DisconnectRequest flag.
Prototype
void USB_MSD_RequestDisconnect(U8 Lun);
Additional information
This function sets the disconnect flag for the storage medium. As soon as the next
MSD command is sent to the device, the host will be informed that the device is cur-
rently not available. To reconnect the storage medium, USB_MSD_Connect() shall be
called.
Parameter Description
Lun Zero-based index for the unit number.
Using only one storage medium, this parameter is 0.
Table 7.15: USB_MSD_RequestDisconnect() parameter list
202 CHAPTER 7 Mass Storage Device Class (MSD)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
7.3.2.4 USB_MSD_UpdateWriteProtect()
Description
Updates the IsWriteProtected flag for a storage medium.
Prototype
void USB_MSD_UpdateWriteProtect(U8 Lun, U8 IsWriteProtected);
Additional information
This functions updates the write protect status of the storage medium. Please make
sure that this function is called when the LUN is disconnected from the host, other-
wise the WriteProtected flag is normally not recognized.
Parameter Description
Lun Zero-based index for the unit number.
Using only one storage medium, this parameter is 0.
IsWriteProtected 1 - Medium is write protected.
0 - Medium is not write protected.
Table 7.16: USB_MSD_UpdateWriteProtect() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
203
7.3.2.5 USB_MSD_WaitForDisconnection()
Description
Waits for disconnection while timeout is not reached.
Prototype
int USB_MSD_WaitForDisconnection(U8 Lun, U32 TimeOut);
Return value
0 - Error: timeout reached. Storage medium is not disconnected.
1 - Success: Storage medium is disconnected.
Additional information
After triggering the disconnection via USB_MSD_RequestDisconnect() the stack dis-
connects the storage medium next time the host requests the status of the storage
medium. Win2k does not periodically check the status of a USB MSD. Therefore, the
timeout is required to leave the loop. The return value can be used to decide if the
disconnection should be forced. In this case, USB_MSD_Disconnect() shall be called.
Parameter Description
Lun 0-based index for the unit number.
Using only one storage medium, this parameter is 0.
TimeOut timeout given in ms (timer ticks).
Table 7.17: USB_MSD_WaitForDisconnection() parameter list
204 CHAPTER 7 Mass Storage Device Class (MSD)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
7.3.2.6 USB_MSD_SetStartStopUnitHook()
Description
Sets a callback function to prevent/allow removal of storage medium.
Prototype
void USB_MSD_SetStartStopUnitHook(U8 Lun,
START_STOP_UNIT_HOOK * pfOnStartStopUnit)
Parameter Description
pfOnStartStopUnit
Pointer to the callback function
START_STOP_UNIT_HOOK. For detailed information
about the function pointer, refer to
PREVENT_ALLOW_REMOVAL_HOOK_EX on page 209.
Table 7.18: USB_MSD_SetStartStopUnitHook() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
205
7.3.3 Data structures
7.3.3.1 USB_MSD_INIT_DATA
Description
emUSB-MSD initialization structure that is required when adding an MSD interface.
Prototype
typedef struct {
U8 EPIn;
U8 EPOut;
U8 InterfaceNum;
} USB_MSD_INIT_DATA;
Additional Information
This structure holds the endpoints that should be used with the MSD interface. Refer
to USB_AddEP() on page 61 for more information about how to add an endpoint.
Member Description
EPIn Endpoint for sending data to the host.
EPOut Endpoint for receiving data from the host.
InterfaceNum Interface number. This member is normally internally used, so therefore
the value shall be set to 0.
Table 7.19: USB_MSD_INIT_DATA elements
206 CHAPTER 7 Mass Storage Device Class (MSD)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
7.3.3.2 USB_MSD_INFO
Description
emUSB-MSD storage interface.
Prototype
typedef struct {
U32 NumSectors;
U16 SectorSize;
} USB_MSD_INFO;
Member Description
NumSectors Number of available sectors.
SectorSize Size of one sector.
Table 7.20: USB_MSD_INFO elements
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
207
7.3.3.3 USB_MSD_INST_DATA
Description
Structure that is used when adding a device to emUSB-MSD.
Prototype
typedef struct {
const USB_MSD_STORAGE_API * pAPI;
USB_MSD_INST_DATA_DRIVER DriverData;
U8 DeviceType;
U8 IsPresent;
USB_MSD_HANDLE_CMD * pfHandleCmd;
U8 IsWriteProtected;
} USB_MSD_INST_DATA;
Additional Information
All non-optional members of this structure need to be initialized correctly, except
Device Type because it is done by the functions USB_MSD_AddUnit() or
USB_MSD_AddCDROM().
Member Description
pAPI Pointer to a structure that holds the storage device driver API.
DriverData
Driver data that are passed to the storage driver. Refer to
USB_MSD_INST_DATA_DRIVER on page 211 for detailed infor-
mation about how to initialize this structure.
DeviceType Determines the type of the device.
IsPresent Determines if the medium is storage is present. For non-
removable devices always 1.
pfHandleCmd
Optional pointer to a callback function which handles SCSI
commands.
typedef U8 (USB_MSD_HANDLE_CMD)(U8 Lun);
IsWriteProtected Specifies whether the storage medium shall be write-pro-
tected.
Table 7.21: USB_MSD_INST_DATA elements
208 CHAPTER 7 Mass Storage Device Class (MSD)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
7.3.3.4 PREVENT_ALLOW_REMOVAL_HOOK
Description
Callback function to prevent/allow removal of storage medium. See
USB_MSD_SetPreventAllowRemovalHook() on page 195 for further information.
Prototype
typedef void (PREVENT_ALLOW_REMOVAL_HOOK)(U8 PreventRemoval);
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
209
7.3.3.5 PREVENT_ALLOW_REMOVAL_HOOK_EX
Description
Ex variant of PREVENT_ALLOW_REMOVAL_HOOK, this function definition additionally
includes a parameter for the Lun index. See
USB_MSD_SetPreventAllowRemovalHookEx() on page 196 for further information.
Prototype
typedef void (PREVENT_ALLOW_REMOVAL_HOOK_EX)(U8 Lun, U8 PreventRemoval);
210 CHAPTER 7 Mass Storage Device Class (MSD)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
7.3.3.6 READ_WRITE_HOOK
Description
Callback function which is called with every read/write access to the storage medium.
Prototype
typedef void (READ_WRITE_HOOK)(U8 Lun,
U8 IsRead,
U8 OnOff,
U32 StartLBA,
U32 NumBlocks);
Member Description
Lun Specifies the logical unit number which was accessed through
read or write.
IsRead Specifies whether a read or a write access was used (1 for
read, 0 for write).
OnOff States whether the read or write request has been initialized
(1) or whether it is complete (0).
StartLBA The first Logical Block Address accessed by the transfer.
NumBlocks The number of blocks accessed by the transfer, starting from the
StartLBA.
Table 7.22: READ_WRITE_HOOK elements
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
211
7.3.3.7 USB_MSD_INST_DATA_DRIVER
Description
USB-MSD initialization structure that is required when adding an MSD interface.
Prototype
typedef struct {
void * pStart;
U32 StartSector;
U32 NumSectors;
U32 SectorSize;
void * pSectorBuffer;
unsigned NumBytes4Buffer;
} USB_MSD_INST_DATA_DRIVER;
Additional Information
This structure is passed to the storage driver. Therefore, the member of this struc-
ture can depend on the driver that is used.
For the storage driver that are shipped with this software the members of
USB_MSD_INST_DATA_DRIVER have the following meaning:
USB_MSD_StorageRAM:
USB_MSD_StorageByName:
Member Description
pStart A pointer defining the start address.
StartSector The start sector that is used for the driver.
NumSectors The available number of sectors available for the driver.
SectorSize The sector size that should be used by the driver.
pSectorBuffer Pointer to a application provided buffer to be used as tempo-
rary buffer for storing the sector data
NumBytes4Buffer Size of the application provided buffer.
Table 7.23: USB_MSD_INST_DATA_DRIVER
Member Description
pStart A pointer defining the start address of the RAM disk.
StartSector This member is ignored.
NumSectors The available number of sectors available for the RAM disk.
SectorSize The sector size that should be used by the driver.
Member Description
pStart Pointer to a string holding the name of the volumes that shall
be used, for example "nand:" "mmc:1:"
StartSector Specifies the start sector.
NumSectors Number of sector that shall be used.
SectorSize This member is ignored.
pSectorBuffer Pointer to a application provided buffer to be used as tempo-
rary buffer for storing the sector data
NumBytes4Buffer
Size of the application provided buffer. Please make sure that
the buffer can at least 3 sectors otherwise, pSectorBuffer and
NumBytes4Buffer are ignored and an internal sector buffer is
used. This sector-buffer is then allocated by using the FS-Stor-
age-Layer functions.
212 CHAPTER 7 Mass Storage Device Class (MSD)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
7.3.3.8 USB_MSD_STORAGE_API
Description
Structure that contains callbacks to the storage driver.
Prototype
typedef struct {
void (*pfInit) (U8 Lun,
const USB_MSD_INST_DATA_DRIVER * pDriverData);
void (*pfGetInfo) (U8 Lun,
USB_MSD_INFO * pInfo);
U32 (*pfGetReadBuffer) (U8 Lun,
U32 SectorIndex,
void ** ppData,
U32 NumSectors);
char (*pfRead) (U8 Lun,
U32 SectorIndex,
void * pData,
U32 NumSector);
U32 (*pfGetWriteBuffer) (U8 Lun,
U32 SectorIndex,
void ** ppData,
U32 NumSectors);
char (*pfWrite) (U8 Lun,
U32 SectorIndex,
const void * pData,
U32 NumSectors);
char (*pfMediumIsPresent) (U8 Lun);
void (*pfDeInit) (U8 Lun);
} USB_MSD_STORAGE_API;
Additional Information
USB_MSD_STORAGE_API is used to retrieve information from the storage device driver
or access data that need to be read or written. Detailed information can be found in
Storage Driver on page 214.
Member Description
pfInit Initializes the storage medium.
pfGetInfo Retrieves storage medium information such as sector size
and number of sectors available.
pfGetReadBuffer Prepares read function and returns a pointer to a buffer that
is used by the storage driver.
pfRead Reads one or multiple sectors from the storage medium.
pfGetWriteBuffer Prepares write function and returns a pointer to a buffer
that is used by the storage driver.
pfWrite Writes one or more sectors to the storage medium.
pfMediumIsPresent Checks if medium is present.
pfDeInit Deinitializes the storage medium.
Table 7.24: List of callback functions of USB_MSD_STORAGE_API
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
213
7.3.3.9 START_STOP_UNIT_HOOK
Description
Callback function which is called when a START STOP UNIT SCSI command is
received.
Prototype
typedef void (START_STOP_UNIT_HOOK)(U8 Lun,
U8 StartLoadEject);
Additional Information
The LOEJ (load eject) bit is located on bit position 1.
The START bit is located on bit position 0.
For fiurther information please refer to the START STOP UNIT command description in
the SCSI documentation.
Member Description
Lun Specifies the logical unit number which was accessed through
read or write.
StartLoadEject Binary OR of the SCSI LOEJ and START bits.
Table 7.25: START_STOP_UNIT_HOOK elements
214 CHAPTER 7 Mass Storage Device Class (MSD)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
7.4 Storage Driver
This section describes the storage interface in detail.
7.4.1 General information
The storage interface is handled through an API-table, which contains all relevant
functions necessary for read/write operations and initialization. Its implementation
handles the details of how data is actually read from or written to memory.
Additionally, MSD knows two different media types:
Direct media access, for example RAM-Disk, NAND flash, MMC/SD cards etc.
CD-ROM emulation.
7.4.1.1 Supported storage types
The supported storage types include:
RAM, directly connected to the processor via the address bus.
External flash memory, e.g. SD cards.
Mechanical drives, for example CD-ROM. This is essentially an ATA/SCSI to USB
bridge.
7.4.1.2 Storage drivers supplied with this release
This release comes with the following drivers:
USB_MSD_StorageRAM: A RAM driver which should work with almost any device.
USB_MSD_StorageByIndex: A storage driver that uses the storage layer (logical
block layer) of emFile to access the device.
USB_MSD_StorageByName: A storage driver that uses the storage layer (logical
block layer) of emFile to access the device.
7.4.2 Interface function list
As described above, access to a storage medium is realized through an API-function
table (USB_MSD_STORAGE_API). The storage functions are declared in
USB\MSD\USB_MSD.h. The structure is described in section Data structures on
page 205.
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
215
7.4.3 USB_MSD_STORAGE_API in detail
7.4.3.1 (*pfInit)()
Description
Initializes the storage medium.
Prototype
void (*pfInit)(U8 Lun, const USB_MSD_INST_DATA_DRIVER * pDriverData);
Parameter Description
Lun Logical unit number. Specifies for which drive the function is called.
pDriverData
Pointer to a USB_MSD_INST_DATA_DRIVER structure that contains all
information that are necessary for the driver initialization. For
detailed information about the USB_MSD_INST_DATA_DRIVER struc-
ture, refer to USB_MSD_INST_DATA_DRIVER on page 211.
Table 7.26: (*pfInit)() parameter list
216 CHAPTER 7 Mass Storage Device Class (MSD)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
7.4.3.2 (*pfGetInfo)()
Description
Retrieves storage medium information such as sector size and number of sectors
available.
Prototype
void (*pfGetInfo)(U8 Lun, USB_MSD_INFO * pInfo);
Parameter Description
Lun Logical unit number. Specifies for which drive the function is called.
pInfo Pointer to a USB_MSD_INFO structure. For detailed information about
the USB_MSD_INFO structure, refer to USB_MSD_INFO on page 206.
Table 7.27: (*pfGetInfo)() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
217
7.4.3.3 (*pfGetReadBuffer)()
Description
Prepares the read function and returns a pointer to a buffer that is used by the stor-
age driver.
Prototype
U32 (*pfGetReadBuffer)(U8 Lun, U32 SectorIndex,
void ** ppData, U32 NumSectors);
Return value
Maximum number of consecutive sectors that can be read at once by the driver.
Parameter Description
Lun Logical unit number. Specifies for which drive the function is called.
SectorIndex Specifies the start sector for the read operation.
ppData Pointer to a pointer to store the read buffer address of the driver.
NumSectors Number of sectors to read.
Table 7.28: (*pfGetReadBuffer)() parameter list
218 CHAPTER 7 Mass Storage Device Class (MSD)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
7.4.3.4 (*pfRead)()
Description
Reads one or multiple consecutive sectors from the storage medium.
Prototype
char (*pfRead)(U8 Lun, U32 SectorIndex, void * pData, U32 NumSector);
Return value
== 0 Success
!= 0 File System error code.
Parameter Description
Lun Logical unit number. Specifies for which drive the function is called.
SectorIndex Specifies the start sector from where the read operation is started.
pData Pointer to buffer to store the read data.
NumSectors Number of sectors to read.
Table 7.29: (*pfRead)() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
219
7.4.3.5 (*pfGetWriteBuffer)()
Description
Prepares the write function and returns a pointer to a buffer that is used by the stor-
age driver.
Prototype
U32 (*pfGetWriteBuffer)(U8 Lun, U32 SectorIndex,
void ** ppData, U32 NumSectors);
Return value
Maximum number of consecutive sectors that can be written into the buffer.
Parameter Description
Lun Logical unit number. Specifies for which drive the function is called.
SectorIndex Specifies the start sector for the write operation.
ppData Pointer to a pointer to store the write buffer address of the driver.
NumSectors Number of sectors to write.
Table 7.30: (*pfGetWriteBuffer)() parameter list
220 CHAPTER 7 Mass Storage Device Class (MSD)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
7.4.3.6 (*pfWrite)()
Description
Writes one or more consecutive sectors to the storage medium.
Prototype
char (*pfWrite)(U8 Lun, U32 SectorIndex,
const void * pData, U32 NumSectors);
Return value
0: Success
Any other value means error.
Parameter Description
Lun Logical unit number. Specifies for which drive the function is called.
SectorIndex Specifies the start sector for the write operation.
pData Pointer to data to be written to the storage medium.
NumSectors Number of sectors to write.
Table 7.31: (*pfWrite)() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
221
7.4.3.7 (*pfMediumIsPresent)()
Description
Checks if medium is present.
Prototype
char (*pfMediumIsPresent) (U8 Lun);
Return value
1: Medium is present.
0: Medium is not present.
Parameter Description
Lun Logical unit number. Specifies for which drive the function is called.
Table 7.32: (*pfMediumIsPresent)() parameter list
222 CHAPTER 7 Mass Storage Device Class (MSD)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
7.4.3.8 (*pfDeInit)()
Description
Deinitializes the storage medium.
Prototype
void (*pfDeInit) (U8 Lun);
Parameter Description
Lun Logical unit number. Specifies for which drive the function is called.
Table 7.33: (*pfDeInit)() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
223
Chapter 8
Media Transfer Protocol Class
(MTP)
This chapter gives a general overview of the MTP class and describes how to get the
MTP component running on the target.
224 CHAPTER 8 Media Transfer Protocol Class (MTP)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
8.1 Overview
The Media Transfer Protocol (MTP) is a USB class protocol which can be used to trans-
fer files to and from storage devices. MTP is an official extension of the Picture Trans-
fer Protocol (PTP) designed to allow digital cameras to exchange image files with a
computer. MTP extends this by adding support for audio and video files.
MTP is an alternative to Mass Storage Device (MSD) and it operates at the file level in
contrast to MSD which reads and writes sector data. This type of operation gives MTP
some advantages over MSD:
The cable can be safely removed during the data transfer without damaging the
file system.
The file system does not need to be FAT (can be the SEGGER EFS or any other
proprietary file system)
The application has full control over which files are visible to the user. Selected
files or directories can be hidden.
Virtual files can be presented.
Host and target can access storage simultaneously without conflicts.
MTP is supported by most operating systems "out of the box" and the installation of
additional drivers is not required.
emUSB-MTP supports the following capabilities:
•File read
•File write
•Format
•File delete
Directory create
Directory delete
The current implementation of emUSB-MTP has the following limitations:
The device does not notify the host when the data on the storage medium
changes (file added/removed, file size change, etc.)
Get in contact with us if you need this feature to be supported.
emUSB-MTP comes as a complete package and contains the following:
Generic USB handling
MTP device class implementation
Storage driver which uses emFile
Sample application showing how to work with MTP
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
225
8.1.1 Getting access to files
An MTP device will be displayed under the "Portable Devices" section in the "Com-
puter" window when connected to a PC running the Microsoft Windows 7 operating
system:
The file and directories stored on the device are accessed in the usual way using the
Windows Explorer:
226 CHAPTER 8 Media Transfer Protocol Class (MTP)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
On the Ubuntu Linux operating system a connected MTP device is shown in the "Com-
puter" window:
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
227
The files and directories present on the MTP device can be easily accessed via GUI:
On other operating systems the data stored on MTP devices can be accessed simi-
larly.
8.1.2 Additional information
For more technical details about MTP and PTP follow these links:
MTP specification
PTP specification
228 CHAPTER 8 Media Transfer Protocol Class (MTP)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
8.2 Configuration
8.2.1 Initial configuration
To get emUSB-MTP up and running as well as doing an initial test, the configuration
as it is delivered with the sample application should not be modified.
8.2.2 Final configuration
The configuration must only be modified when emUSB is integrated in your final
product. Refer to section Configuration on page 44 for detailed information about the
generic information functions which has to be adapted.
8.2.3 Class specific configuration
Beside the emUSB-MTP configuration functions which must be called by the applica-
tion, the callback functions described below can be adapted before the emUSB-MTP
component is used in a final product. A sample implementation of these functions can
be found in the USB_MTP_Start.c application, located in the Application directory
of emUSB shipment.
Function Description
emUSB-MTP configuration functions
USB_MTP_GetManufacturer() Returns the device manufacturer.
USB_MTP_GetModel() Returns the device model.
USB_MTP_GetDeviceVersion() Returns the firmware version of device.
USB_MTP_GetSerialNumber() Returns the serial number of device.
Table 8.1: List of class specific configuration functions
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
229
8.2.3.1 USB_MTP_GetManufacturer()
Description
Should return the name of the device manufacturer.
Prototype
const char * USB_MTP_GetManufacturer(void);
Example
const char * USB_MTP_GetManufacturer(void) {
return "SEGGER";
}
Additional information
It is a human-readable string identifying the manufacturer of this device. This string
is returned by the MTP device in the Manufacturer field of the Device Info dataset.
For more information, refer to MTP specification.
230 CHAPTER 8 Media Transfer Protocol Class (MTP)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
8.2.3.2 USB_MTP_GetModel()
Description
Should return the model of MTP device.
Prototype
const char * USB_MTP_GetModel(void);
Example
const char * USB_MTP_GetModel(void) {
return "Storage device";
}
Additional information
It is a human-readable string identifying the model of the device. This string is
returned by the MTP device in the Model field of the Device Info dataset. For more
information, refer to MTP specification.
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
231
8.2.3.3 USB_MTP_GetDeviceVersion()
Description
Should return the version of MTP device.
Prototype
const char * USB_MTP_GetDeviceVersion(void);
Example
const char * USB_MTP_GetDeviceVersion(void) {
return "1.0";
}
Additional information
The string identifies the version of the firmware running on the device. This string is
returned by the MTP device in the Device Version field of the Device Info dataset. For
more information, refer to MTP specification.
232 CHAPTER 8 Media Transfer Protocol Class (MTP)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
8.2.3.4 USB_MTP_GetSerialNumber()
Description
Should return the serial number of MTP device.
Prototype
const char * USB_MTP_GetSerialNumber(void);
Example
const char * USB_MTP_GetSerialNumber(void) {
return "0123456789ABCDEF0123456789ABCDEF";
}
Additional information
The serial number should contain exactly 32 hexadecimal characters. It must be
unique between the devices sharing the same model name and device version
strings. The MTP device returns this string in the Serial Number field of the Device-
Info dataset. For more information, refer to MTP specification.
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
233
8.2.4 Compile time configuration
The following macros can be added to USB_Conf.h file in order to configure the
behavior of the MTP component.
The following types of configuration macros exist:
Binary switches “B”
Switches can have a value of either 0 or 1, for deactivated and activated respectively.
Actually, anything other than 0 works, but 1 makes it easier to read a configuration
file. These switches can enable or disable a certain functionality or behavior.
Switches are the simplest form of configuration macros.
Numerical values “N”
Numerical values are used somewhere in the code in place of a numerical constant.
8.3 Running the sample application
The directory Application contains an sample application which can be used with
emUSB and the MTP component. To test the emUSB-MTP component, the application
should be built and then downloaded to target. Remove the USB connection and
reconnect the target to the host. The target will enumerate and will be accessible via
a file browser.
8.3.1 USB_MTP_Start.c in detail
The main part of the example application USB_MTP_Start.c is implemented in a sin-
gle task called MainTask().
// MainTask() - excerpt from USB_MTP_Start.c
Type Macro Default Description
N MTP_DEBUG_LEVEL 0
Sets the type of diagnostic messages
output at runtime. It can take one of
these values:
0 - no debug messages
1 - only error messages
2 - error and log messages
NMTP_MAX_NUM_STORAGES 4
Maximum number of storage units the
storage layer can handle. 4 additional
bytes are allocated for each storage
unit.
B MTP_SAVE_FILE_INFO 0
Specifies if the object properties (file
size, write protection, creation date,
modification date and file id) should be
stored in RAM for quick access to them.
50 additional bytes of RAM are required
for each object when the switch is set
to 1.
NMTP_MAX_FILE_PATH 256 Maximum number of characters in the
path to a file or directory.
B MTP_SUPPORT_UTF8 1
Names of the files and directories
which are exchanged between the MTP
component and the file system are
encoded in UTF-8 format.
Table 8.2: MTP configuration macros
234 CHAPTER 8 Media Transfer Protocol Class (MTP)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
void MainTask(void);
void MainTask(void) {
USB_Init();
_AddMTP();
USB_Start();
while (1) {
while ((USB_GetState() & (USB_STAT_CONFIGURED | USB_STAT_SUSPENDED))
!= USB_STAT_CONFIGURED) {
BSP_ToggleLED(0);
USB_OS_Delay(50);
}
BSP_SetLED(0);
USB_MTP_Task();
}
}
The first step is to initialize the USB core stack by calling USB_Init(). The function
_AddMTP() configures all required endpoints, adds the MTP component to emUSB and
assigns a storage medium to it. More than one storage medium can be added. The
access to storage medium is done using a storage driver. emUSB comes with a stor-
age driver for the SEGGER emFile file system.
// _AddMTP() - excerpt from USB_MTP_Start.c
static void _AddMTP(void) {
USB_MTP_INIT_DATA InitData;
USB_MTP_INST_DATA InstData;
//
// Add the MTP component to USB stack.
//
InitData.EPIn = USB_AddEP(1, USB_TRANSFER_TYPE_BULK,
USB_MAX_PACKET_SIZE, NULL, 0);
InitData.EPOut = USB_AddEP(0, USB_TRANSFER_TYPE_BULK,
USB_MAX_PACKET_SIZE, _acReceiveBuffer,
sizeof(_acReceiveBuffer));
InitData.EPInt = USB_AddEP(1, USB_TRANSFER_TYPE_INT, 10, NULL, 0);
InitData.pObjectList = _aObjectList;
InitData.NumBytesObjectList = sizeof(_aObjectList);
InitData.pDataBuffer = _aDataBuffer;
InitData.NumBytesDataBuffer = sizeof(_aDataBuffer);
USB_MTP_Add(&InitData);
//
// Add a storage driver to MTP component.
//
InstData.pAPI = &USB_MTP_StorageFS;
InstData.sDescription = "MTP volume";
InstData.sVolumeId = "0123456789";
InstData.DriverData.pRootDir = "";
USB_MTP_AddStorage(&InstData);
}
The size of _acReceiveBuffer and _aDataBuffer buffers must be a multiple of USB
maximum packet size. The sample uses the USB_MAX_PACKET_SIZE define which is
set to the correct value. The size of the buffer allocated for the object list,
_aObjectList must be chosen according to the number of files on the storage
medium. emUSB-MTP assigns an internal object to each file or directory requested by
the USB host. The USB host can request all the files and directories present at once
or it can request files and directories as user browses them. An object requires a
minimum of 54 bytes. The actual number of bytes allocated depends on the length of
the full path to file/directory.
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
235
8.4 Target API
8.4.1 API functions
8.4.1.1 USB_MTP_Add()
Description
Adds an MTP-class interface to the USB stack.
Prototype
void USB_MTP_Add(const USB_MTP_INIT_DATA * pInitData);
Additional information
After the initialization of USB core, this is the first function that needs to be called
when an MTP interface is used with emUSB. The structure USB_MTP_INIT_DATA has to
be initialized before USB_MTP_Add() is called. Refer to USB_MTP_INIT_DATA on
page 239 for more information.
Function Description
API functions
USB_MTP_Add() Adds an MTP interface to the USB stack.
USB_MTP_AddStorage() Adds a storage device to the emUSB-MTP.
USB_MTP_Task() Handles the MTP communication.
Data structures
USB_MTP_FILE_INFO Stores information about a file or directory.
USB_MTP_INIT_DATA Stores the MTP initialization parameters.
USB_MTP_INST_DATA Stores the initialization parameters of storage
driver.
USB_MTP_INST_DATA_DRIVER Stores parameters that are passed to storage
driver.
USB_MTP_STORAGE_API Stores callbacks to the functions of storage driver.
USB_MTP_STORAGE_INFO Stores information about the storage medium.
Table 8.3: List of emUSB MTP interface functions and data structures
Parameter Description
pInitData Pointer to a USB_MTP_INIT_DATA structure.
Table 8.4: USB_MTP_Add() parameter list
236 CHAPTER 8 Media Transfer Protocol Class (MTP)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
8.4.1.2 USB_MTP_AddStorage()
Description
Adds a storage device to emUSB-MTP.
Prototype
void USB_MTP_AddStorage(const USB_MTP_INST_DATA * pInstData);
Additional information
It is necessary to call this function immediately after USB_MTP_Add().
This function adds a storage device such as a hard drive, MMC/SD card or NAND flash
etc., to emUSB-MTP, which will be used as source/destination of data exchange with
the host. The structure USB_MTP_INST_DATA must be initialized before
USB_MTP_AddStorage() is called. Refer to USB_MTP_INST_DATA on page 240 for
more information.
Parameter Description
pInstData Pointer to a USB_MTP_INST_DATA structure which contains the
parameters of the added storage driver.
Table 8.5: USB_MTP_AddStorage() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
237
8.4.1.3 USB_MTP_Task()
Description
Task which handles the MTP communication.
Prototype
void USB_MTP_Task(void);
Additional information
The USB_MTP_Task() should be called after the USB device has been successfully
enumerated and configured. The function returns when the USB device is detached or
suspended.
238 CHAPTER 8 Media Transfer Protocol Class (MTP)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
8.4.2 Data structures
8.4.2.1 USB_MTP_FILE_INFO
Description
Structure which stores information about a file or directory.
Prototype
typedef struct {
char * pFilePath;
char * pFileName;
U32 FileSize;
U32 CreationTime;
U32 LastWriteTime;
U8 IsDirectory;
U8 Attributes;
U8 acId[MTP_NUM_BYTES_FILE_ID];
} USB_MTP_FILE_INFO;
Additional Information
The date and time is formatted as follows:
acId should unique for each file and directory on the file system and it should be per-
sistent between MTP sessions.
The following attributes are supported:
Member Description
pFilePath Pointer to full path to file.
pFileName Pointer to beginning of file/directory name in pFilePath
FileSize Size of the file in bytes.
CreationTime Time and date when the file was created.
LastWriteTime Time and data when the file was last modified.
IsDirectory Set to 1 if the path points to a directory.
Attributes Bitmask containing the file or directory attributes.
acId Unique file/directory identifier.
Table 8.6: USB_MTP_FILE_INFO elements
Bit
range
Value
range Description
0-4 0-29 2-second count
5-10 0-59 Minutes
11-15 0-23 Hours
16-20 1-31 Day of month
21-24 1-12 Month of year
25-31 0-127 Number of years since 1980
Bitmask Description
MTP_FILE_ATTR_WP File/directory can not be modified
MTP_FILE_ATTR_SYSTEM File/directory is required for the correct
functioning of the system.
MTP_FILE_ATTR_HIDDEN File/directory should not be shown to
user.
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
239
8.4.2.2 USB_MTP_INIT_DATA
Description
Structure which stores the parameters of the MTP interface.
Prototype
typedef struct {
U8 EPIn;
U8 EPOut;
U8 EPInt;
void * pObjectList;
U32 NumBytesObjectList;
void * pDataBuffer;
U32 NumBytesDataBuffer;
//
// The following fields are used internally by the MTP component.
//
U8 InterfaceNum;
U32 NumBytesAllocated;
U32 NumObjects;
} USB_MTP_INIT_DATA;
Additional Information
This structure holds the endpoints that should be used with the MTP interface. Refer
to USB_AddEP() on page 61 for more information about how to add an endpoint.
The number of bytes in the pDataBuffer should be a multiple of USB maximum
packet size. The number of bytes in the object list depends on the number of files/
directories on the storage medium. An object is assigned to each file/directory when
the USB host requests the object information for the first time.
Member Description
EPIn Endpoint for receiving data from host.
EPOut Endpoint for sending data to host.
EPInt Endpoint for sending events to host.
pObjectList Pointer to a memory region where the list of MTP objects is
stored.
NumBytesObjectList Number of bytes allocated for the object list.
pDataBuffer Pointer to a memory region to be used as communication buffer.
NumBytesDataBuffer Number of bytes allocated for the data buffer.
Table 8.7: USB_MTP_INIT_DATA elements
240 CHAPTER 8 Media Transfer Protocol Class (MTP)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
8.4.2.3 USB_MTP_INST_DATA
Description
Structure which stores the parameters of storage driver.
Prototype
typedef struct {
const USB_MTP_STORAGE_API * pAPI;
const char * sDescription;
const char * sVolumeId;
USB_MTP_INST_DATA_DRIVER DriverData;
} USB_MTP_INST_DATA;
Additional Information
The MTP device returns the sDescription string in the Storage Description param-
eter and the sVolumeId in the Volume Identifier of the StorageInfo dataset. For
more information, refer to MTP specification.
Member Description
pAPI Pointer to a structure that holds the storage device driver API.
sDescription Human-readable string which identifies the storage. This string is
displayed in Windows Explorer.
sVolumeId Unique volume identifier.
DriverData
Driver data that are passed to the storage driver. Refer to
USB_MTP_INST_DATA_DRIVER on page 241 for detailed infor-
mation about how to initialize this structure. This field must be
up to 256 characters long but only the first 128 are significant
and these must be unique for all storages of an MTP device.
Table 8.8: USB_MTP_INST_DATA elements
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
241
8.4.2.4 USB_MTP_INST_DATA_DRIVER
Description
Structure which stores the parameters passed to the storage driver.
Prototype
typedef struct {
const char * pRootDir;
} USB_MTP_INST_DATA_DRIVER;
Additional Information
pRootDir can specify the root of the file system or any other subdirectory.
Member Description
pRootDir Path to directory to be used as the root of the storage.
Table 8.9: USB_MTP_INST_DATA_DRIVER
242 CHAPTER 8 Media Transfer Protocol Class (MTP)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
8.4.2.5 USB_MTP_STORAGE_API
Description
Structure that contains callbacks to the storage driver.
Prototype
typedef struct {
void (*pfInit) (U8 Unit,
const USB_MTP_INST_DATA_DRIVER * pDriverData);
void (*pfGetInfo) (U8 Unit,
USB_MTP_STORAGE_INFO * pStorageInfo);
int (*pfFindFirstFile) (U8 Unit,
const char * pDirPath,
USB_MTP_FILE_INFO * pFileInfo);
int (*pfFindNextFile) (U8 Unit,
USB_MTP_FILE_INFO * pFileInfo);
int (*pfOpenFile) (U8 Unit,
const char * pFilePath);
int (*pfCreateFile) (U8 Unit,
const char * pDirPath,
USB_MTP_FILE_INFO * pFileInfo);
int (*pfReadFromFile) (U8 Unit,
U32 Off,
void * pData,
U32 NumBytes);
int (*pfWriteToFile) (U8 Unit,
U32 Off,
const void * pData,
U32 NumBytes);
int (*pfCloseFile) (U8 Unit);
int (*pfRemoveFile) (U8 Unit,
const char * pFilePath);
int (*pfCreateDir) (U8 Unit,
const char * pDirPath,
USB_MTP_FILE_INFO * pFileInfo);
int (*pfRemoveDir) (U8 Unit,
const char * pDirPath);
int (*pfFormat) (U8 Unit);
int (*pfRenameFile) (U8 Unit,
USB_MTP_FILE_INFO * pFileInfo);
void (*pfDeInit) (U8 Unit);
int (*pfGetFileAttributes) (U8 Unit
const char * pFilePath,
U8 * pMask);
int (*pfModifyFileAttributes)(U8 Unit,
const char * pFilePath,
U8 SetMask,
U8 ClrMask);
int (*pfGetFileCreationTime) (U8 Unit,
const char * pFilePath,
U32 * pTime);
int (*pfGetFileLastWriteTime)(U8 Unit,
const char * pFilePath,
U32 * pTime);
int (*pfGetFileId) (U8 Unit,
const char * pFilePath,
U8 * pId);
int (*pfGetFileSize) (U8 Unit,
const char * pFilePath,
U32 * pFileSize);
} USB_MTP_STORAGE_API;
Member Description
(*pfInit)() Initializes the storage medium.
(*pfGetInfo)()
Returns information about the storage medium
such as storage capacity and the available free
space.
(*pfFindFirstFile)() Returns information about the first file in a given
directory.
(*pfFindNextFile)() Moves to next file and returns information about
it.
Table 8.10: List of callback functions of USB_MTP_STORAGE_API
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
243
Additional Information
USB_MTP_STORAGE_API is used to retrieve information from the storage driver or to
access data that needs to be read or written. Detailed information can be found in
Storage Driver on page 245.
(*pfOpenFile)() Opens an existing file.
(*pfCreateFile)() Creates a new file.
(*pfReadFromFile)() Reads data from the current file.
(*pfWriteToFile)() Writes data to current file.
(*pfCloseFile)() Closes the current file.
(*pfRemoveFile)() Removes a file from storage medium.
(*pfCreateDir)() Creates a new directory.
(*pfRemoveDir)() Removes a directory from storage medium.
(*pfFormat)() Formats the storage.
(*pfRenameFile)() Changes the name of a file or directory
(*pfDeInit)() Deinitializes the storage medium.
(*pfGetFileAttributes)() Reads the attributes of a file or directory.
(*pfModifyFileAttributes)() Changes the attributes of a file or directory.
(*pfGetFileCreationTime)() Returns the creation time of a file or directory.
(*pfGetFileLastWriteTime)() Returns the time of the last modification made to
a file or directory.
(*pfGetFileId)() Returns the unique id of a file or directory.
(*pfGetFileSize)() Returns the size of a file in bytes.
Member Description
Table 8.10: List of callback functions of USB_MTP_STORAGE_API
244 CHAPTER 8 Media Transfer Protocol Class (MTP)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
8.4.2.6 USB_MTP_STORAGE_INFO
Description
Structure which stores information about the storage medium.
Prototype
typedef struct {
U32 NumKbytesTotal;
U32 NumKbytesFreeSpace;
U16 FSType;
U8 IsWriteProtected;
U8 IsRemovable;
} USB_MTP_STORAGE_INFO;
Member Description
NumKbytesTotal Capacity of storage medium in Kbytes.
NumKbytesFreeSpace Available free space on storage medium in Kbytes.
FSType Type of file system as specified in MTP.
IsWriteProtected Set to 1 if the storage medium canDone.not be modified.
IsRemovable Set to 1 if the storage medium can be removed from device.
Table 8.11: USB_MTP_STORAGE_INFO
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
245
8.5 Storage Driver
This section describes the storage interface in detail.
8.5.1 General information
The storage interface is handled through an API-table, which contains all relevant
functions necessary for read/write operations and initialization. Its implementation
handles the details of how data is actually read from or written to memory.
This release comes with USB_MTP_StorageFS driver which uses emFile to access the
storage medium.
8.5.2 Interface function list
As described above, access to a storage media is realized through an API-function
table of type USB_MTP_STORAGE_API. The structure is declared in USB_MTP.h and it is
described in section Data structures on page 238.
246 CHAPTER 8 Media Transfer Protocol Class (MTP)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
8.5.3 USB_MTP_STORAGE_API in detail
8.5.3.1 (*pfInit)()
Description
Initializes the storage medium.
Prototype
void (*pfInit)(U8 Unit, const USB_MTP_INST_DATA_DRIVER * pDriverData);
Additional information
This function is called when the storage driver is added to emUSB-MTP. It is the first
function of the storage driver to be called.
Parameter Description
Unit Logical unit number. Specifies for which storage medium the func-
tion is called.
pDriverData
Pointer to a USB_MTP_INST_DATA_DRIVER structure that contains all
information that are necessary for the driver initialization. For
detailed information about the USB_MTP_INST_DATA_DRIVER struc-
ture, refer to USB_MTP_INST_DATA_DRIVER on page 241.
Table 8.12: (*pfInit)() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
247
8.5.3.2 (*pfGetInfo)()
Description
Returns information about storage medium such as capacity and available free space.
Prototype
void (*pfGetInfo)(U8 Unit, USB_MTP_STORAGE_INFO * pStorageInfo);
Additional information
Typically, this function is called immediately after the device is connected to USB host
when the USB host requests information about the available storage mediums.
Parameter Description
Unit Logical unit number. Specifies for which storage medium the func-
tion is called.
pStorageInfo
Pointer to a USB_MTP_STORAGE_INFO structure. For detailed infor-
mation about the USB_MTP_STORAGE_INFO structure, refer to
USB_MTP_STORAGE_INFO on page 244.
Table 8.13: (*pfGetInfo)() parameter list
248 CHAPTER 8 Media Transfer Protocol Class (MTP)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
8.5.3.3 (*pfFindFirstFile)()
Description
Returns information about the first file in a specified directory.
Prototype
int (*pfFindFirstFile)(U8 Unit,
const char * pDirPath,
USB_MTP_FILE_INFO * pFileInfo);
Return value
==0 File/directory found
==1 No more files/directories found
<0 An error occurred
Additional information
The "." and ".." directory entries which are relevant only for the file system should
be skipped.
Parameter Description
Unit Logical unit number. Specifies for which storage medium the func-
tion is called.
pDirPath Full path to the directory to be searched.
pFileInfo IN: ---
OUT: Information about the file/directory found.
Table 8.14: (*pfFindFirstFile)() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
249
8.5.3.4 (*pfFindNextFile)()
Description
Moves to next file and returns information about it.
Prototype
int (*pfFindNextFile)(U8 Unit, USB_MTP_FILE_INFO * pFileInfo);
Return value
==0 File/directory found
==1 No more files/directories found
<0 An error occurred
Additional information
The "." and ".." directory entries which are relevant only for the file system should
be skipped.
Parameter Description
Unit Logical unit number. Specifies for which storage medium the func-
tion is called.
pFileInfo IN: ---
OUT: Information about the file/directory found.
Table 8.15: (*pfFindNextFile)() parameter list
250 CHAPTER 8 Media Transfer Protocol Class (MTP)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
8.5.3.5 (*pfOpenFile)()
Description
Opens a file for reading.
Prototype
int (*pfOpenFile)(U8 Unit,
const char * pFilePath);
Return value
==0 File opened
!=0 An error occurred
Additional information
This function is called at the beginning of a file read operation. It is followed by one
or more calls to (*pfReadFromFile)(). At the end of data transfer the MTP module
closes the file by calling (*pfCloseFile)(). If the file does not exists an error should
be returned. The MTP module opens only one file at a time.
Parameter Description
Unit Logical unit number. Specifies for which storage medium the func-
tion is called.
pFilePath IN: Full path to file.
OUT ---.
Table 8.16: (*pfOpenFile)() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
251
8.5.3.6 (*pfCreateFile)()
Description
Opens a file for writing.
Prototype
int (*pfCreateFile)(U8 Unit,
const char * pDirPath,
USB_MTP_FILE_INFO * pFileInfo);
Return value
==0 File created and opened
!=0 An error occurred
Additional information
This function is called at the beginning of a file write operation. The name of the file
is specified in the pFileName filed of pFileInfo. If the file exists it should be trun-
cated to zero length. When a file is created, the call to (*pfCreateFile)() is followed
by one or more calls to (*pfWriteToFile)(). If CreationTime and LastWriteTime
in pFileInfo are not zero, these should be used instead of the time stamps gener-
ated by the file system.
Parameter Description
Unit Logical unit number. Specifies for which storage medium the func-
tion is called.
pDirPath IN: Full path to directory where the file should be created.
OUT: ---
pFileInfo
IN: Information about the file to be created. pFileName points to
the name of the file.
OUT: pFilePath points to full path of created file, pFileName points
to the beginning of file name in pFilePath.
Table 8.17: (*pfCreateFile)() parameter list
252 CHAPTER 8 Media Transfer Protocol Class (MTP)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
8.5.3.7 (*pfReadFromFile)()
Description
Reads data from the current file.
Prototype
int (*pfReadFromFile)(U8 Unit,
U32 Off,
void * pData,
U32 NumBytes);
Return value
==0 Data read from file
!=0 An error occurred
Additional information
The function reads data from the file opened by (*pfOpenFile)().
Parameter Description
Unit Logical unit number. Specifies for which storage medium the func-
tion is called.
Off Byte offset where to read from.
pData IN: ---
OUT: Data read from file.
NumBytes Number of bytes to read from file.
Table 8.18: (*pfReadFromFile)() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
253
8.5.3.8 (*pfWriteToFile)()
Description
Writes data to current file.
Prototype
int (*pfWriteToFile)(U8 Unit,
U32 Off,
const void * pData,
U32 NumBytes);
Return value
==0 Data written to file
!=0 An error occurred
Additional information
The function writes data to file opened by (*pfCreateFile)().
Parameter Description
Unit Logical unit number. Specifies for which storage medium the func-
tion is called.
Off Byte offset where to write to.
pData IN: Data to write to file
OUT: ---
NumBytes Number of bytes to write to file.
Table 8.19: (*pfWriteToFile)() parameter list
254 CHAPTER 8 Media Transfer Protocol Class (MTP)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
8.5.3.9 (*pfCloseFile)()
Description
Closes the current file.
Prototype
int (*pfCloseFile)(U8 Unit);
Return value
==0 File closed
!=0 An error occurred
Additional information
The function closes the file opened by (*pfCreateFile)() or (*pfOpenFile)().
Parameter Description
Lun Logical unit number. Specifies for which storage medium the func-
tion is called.
Table 8.20: (*pfCloseFile)() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
255
8.5.3.10 (*pfRemoveFile)()
Description
Removes a file/directory from the storage medium.
Prototype
int (*pfRemoveFile)(U8 Unit,
const char * pFilePath);
Return value
==0 File removed
!=0 An error occurred
Parameter Description
Unit Logical unit number. Specifies for which drive the function is called.
pFilePath IN: Full path to file/directory to be removed
OUT: ---
Table 8.21: (*pfRemoveFile)() parameter list
256 CHAPTER 8 Media Transfer Protocol Class (MTP)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
8.5.3.11 (*pfCreateDir)()
Description
Creates a directory on the storage medium.
Prototype
int (*pfCreateDir)(U8 Unit,
const char * pDirPath,
USB_MTP_FILE_INFO * pFileInfo);
Return value
==0 Directory created
!=0 An error occurred
Additional information
If CreationTime and LastWriteTime in pFileInfo are not zero should be used
instead of the time stamps generated by the file system.
Parameter Description
Unit Logical unit number. Specifies for which storage medium the func-
tion is called.
pDirPath IN: Full path to directory where the directory should be created.
OUT: ---
pFileInfo
IN: Information about the directory to be created. pFileName points
to the directory name.
OUT: pFilePath points to full path of directory, pFileName points to
the beginning of directory name in pFilePath
Table 8.22: (*pfCreateDir)() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
257
8.5.3.12 (*pfRemoveDir)()
Description
Removes a directory and its contents from the storage medium.
Prototype
int (*pfRemoveDir)(U8 Unit,
const char * pDirPath);
Return value
==0 Directory removed
!=0 An error occurred
Additional information
The function should remove the directory and the entire file tree under it.
Parameter Description
Unit Logical unit number. Specifies for which storage medium the func-
tion is called.
pDirPath IN: Full path to directory to be removed.
OUT: ---
Table 8.23: (*pfRemoveDir)() parameter list
258 CHAPTER 8 Media Transfer Protocol Class (MTP)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
8.5.3.13 (*pfFormat)()
Description
Initializes the storage medium.
Prototype
int (*pfFormat)(U8 Unit);
Return value
==0 Storage medium initialized
!=0 An error occurred
Additional information
If pRootDir configured in the call to (*pfInit)() points to a subdirectory of the file
system, the storage medium should not be formatted. Instead, all the files and direc-
tories underneath pRootDir should be removed.
Parameter Description
Unit Logical unit number. Specifies for which storage medium the func-
tion is called.
Table 8.24: (*pfFormat)() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
259
8.5.3.14 (*pfRenameFile)()
Description
Changes the name of a file or directory.
Prototype
int (*pfRenameFile)(U8 Unit, USB_MTP_FILE_INFO * pFileInfo);
Return value
==0 File/directory renamed
!=0 An error occurred
Additional information
Only the name of the file/directory should be changed. The path to parent directory
should remain the same.
Parameter Description
Unit Logical unit number. Specifies for which storage medium the func-
tion is called.
pFileInfo
IN: Information about the file/directory to be renamed. pFilePath
points to the full path and pFileName points to the new name.
OUT: pFilePath points to full path of file/directory with the new
name, pFileName points to the beginning of file/directory name in
pFilePath. The other structure fields should also be filled.
Table 8.25: (*pfRenameFile)() parameter list
260 CHAPTER 8 Media Transfer Protocol Class (MTP)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
8.5.3.15 (*pfDeInit)()
Description
Deinitializes the storage medium.
Prototype
void (*pfDeInit)(U8 Unit);
Additional information
Typically called when the application calls USB_Stop() to de-initialize emUSB.
Parameter Description
Unit Logical unit number. Specifies for which storage medium the func-
tion is called.
Table 8.26: (*pfDeInit)() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
261
8.5.3.16 (*pfGetFileAttributes)()
Description
Returns the attributes of a file or directory.
Prototype
int (*pfGetFileAttributes)(U8 Unit, const char * pFilePath, U8 * pMask);
Return value
==0 Information returned
!=0 An error occurred
Additional information
This function is called only when the compile time switch MTP_SAVE_FILE_INFO is set
to 0. For the list of supported attributes refer to USB_MTP_FILE_INFO on page 238.
Parameter Description
Unit Logical unit number. Specifies for which storage medium the func-
tion is called.
pFilePath Full path to file or directory (0-terminated string).
pMask IN: ---
OUT: The bitmask of the attributes.
Table 8.27: (*pfGetFileAttributes)() parameter list
262 CHAPTER 8 Media Transfer Protocol Class (MTP)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
8.5.3.17 (*pfModifyFileAttributes)()
Description
Sets and clears file attributes.
Prototype
int (*pfModifyFileAttributes)(U8 Unit,
const char * pFilePath,
U8 SetMask,
U8 ClrMask);;
Return value
==0 Attributes modified
!=0 An error occurred
Additional information
This function is called only when the compile time switch MTP_SAVE_FILE_INFO is set
to 0. For the list of supported attributes refer to USB_MTP_FILE_INFO on page 238.
Parameter Description
Unit Logical unit number. Specifies for which storage medium the func-
tion is called.
pFilePath Full path to file or directory (0-terminated string).
SetMask The bitmask of the attributes which should be set.
ClrMask The bitmask of the attributes which should be cleared.
Table 8.28: (*pfModifyFileAttributes)() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
263
8.5.3.18 (*pfGetFileCreationTime)()
Description
Returns the creation time of file or directory.
Prototype
int (*pfGetFileCreationTime)(U8 Unit, const char * pFilePath, U32 * pTime);
Return value
==0 Creation time returned
!=0 An error occurred
Additional information
This function is called only when the compile time switch MTP_SAVE_FILE_INFO is set
to 0. For the encoding of the time value refer to USB_MTP_FILE_INFO on page 238.
Parameter Description
Unit Logical unit number. Specifies for which storage medium the func-
tion is called.
pFilePath Full path to file or directory (0-terminated string).
pTime IN: ---
OUT: The creation time.
Table 8.29: (*pfGetFileCreationTime)() parameter list
264 CHAPTER 8 Media Transfer Protocol Class (MTP)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
8.5.3.19 (*pfGetFileLastWriteTime)()
Description
Returns the time when the file or directory was last modified.
Prototype
int (*pfGetFileLastWriteTime)(U8 Unit,
const char * pFilePath,
U32 * pTime);;
Return value
==0 Modification time returned
!=0 An error occurred
Additional information
This function is called only when the compile time switch MTP_SAVE_FILE_INFO is set
to 0. For the encoding of the time value refer to USB_MTP_FILE_INFO on page 238.
Parameter Description
Unit Logical unit number. Specifies for which storage medium the func-
tion is called.
pFilePath Full path to file or directory (0-terminated string).
pTime IN: ---
OUT: The modification time.
Table 8.30: (*pfGetFileLastWriteTime)() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
265
8.5.3.20 (*pfGetFileId)()
Description
Returns an id which uniquely identifies the file or directory.
Prototype
int (*pfGetFileId)(U8 Unit, const char * pFilePath, U8 * pId);
Return value
==0 Id returned
!=0 An error occurred
Additional information
This function is called only when the compile time switch MTP_SAVE_FILE_INFO is set
to 0.
Parameter Description
Unit Logical unit number. Specifies for which storage medium the func-
tion is called.
pFilePath Full path to file or directory (0-terminated string).
pId
IN: ---
OUT: The unique id of file or directory. Should point to a byte array
MTP_NUM_BYTES_FILE_ID large.
Table 8.31: (*pfGetFileId)() parameter list
266 CHAPTER 8 Media Transfer Protocol Class (MTP)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
8.5.3.21 (*pfGetFileSize)()
Description
Returns the size of a file in bytes.
Prototype
int (*pfGetFileSize)(U8 Unit, const char * pFilePath, U32 * pFileSize);
Return value
==0 Size of file returned
!=0 An error occurred
Additional information
This function is called only when the compile time switch MTP_SAVE_FILE_INFO is set
to 0.
Parameter Description
Unit Logical unit number. Specifies for which storage medium the func-
tion is called.
pFilePath Full path to file or directory (0-terminated string).
pFileSize IN: ---
OUT: The size of file in bytes.
Table 8.32: (*pfGetFileSize)() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
267
Chapter 9
Communication Device Class
(CDC)
This chapter describes how to get emUSB up and running as a CDC device.
268 CHAPTER 9 Communication Device Class (CDC)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
9.1 Overview
The Communication Device Class (CDC) is an abstract USB class protocol defined by
the USB Implementers Forum. This protocol covers the handling of the following
communication flows:
VirtualCOM/Serial interface
Universal modem device
ISDN communication
Ethernet communication
This implementation of CDC currently supports the virtual COM/Serial interface, thus
the USB device will behave like a serial interface.
Normally, a custom USB driver is not necessary because a kernel mode driver for
USB-CDC serial communication is delivered by major Microsoft Windows operating
systems. For installing the USB-CDC serial device an .inf file is needed, which is
also delivered. Linux handles USB 2 virtual COM ports since Kernel Ver. 2.4. Further
information can be found in the Linux Kernel documentation.
9.1.1 Configuration
The configuration section should later be modified to match the real application. For
the purpose of getting emUSB up and running as well as doing an initial test, the
configuration as delivered should not be modified.
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
269
9.2 The example application
The start application (in the Application subfolder) is a simple echo server, which
can be used to test emUSB. The application receives data byte by byte and sends it
back to the host.
Source code excerpt from USB_CDC_Start.c:
/*********************************************************************
*
* MainTask
*
* USB handling task.
* Modify to implement the desired protocol
*/
void MainTask(void);
void MainTask(void) {
U32 i = 0;
USB_Init();
_AddCDC();
USB_Start();
while (1) {
char ac[64];
char acOut[30];
int NumBytesReceived;
int NumBytesToSend;
//
// Wait for configuration
//
while ((USB_GetState() & (USB_STAT_CONFIGURED | USB_STAT_SUSPENDED)) !=
USB_STAT_CONFIGURED) {
BSP_ToggleLED(0);
USB_OS_Delay(50);
}
BSP_SetLED(0);
//
// Receive at maximum of 64 Bytes
// If less data has been received,
// this should be OK.
//
NumBytesReceived = USB_CDC_Receive(&ac[0], sizeof(ac));
i++;
NumBytesToSend = sprintf(acOut, "%.3lu: Received %d byte(s) - \"", i,
NumBytesReceived);
if (NumBytesReceived > 0) {
USB_CDC_Write(&acOut[0], NumBytesToSend);
USB_CDC_Write(&ac[0], NumBytesReceived);
USB_CDC_Write("\"\n\r", 3);
}
}
}
270 CHAPTER 9 Communication Device Class (CDC)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
9.3 Installing the driver
When the emUSB-CDC sample application is up and running and the target device is
plugged into the computer's USB port Windows will detect the new hardware.
The wizard will ask you to help it find the correct driver files for the new device. First
select the Search for a suitable driver for my device (recommended) option,
then click the Next button.
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
271
In the next step, you need to select the Specify a location option and click the
Next button.
Click Browse to open the directory navigator.
Use the directory navigator to select C:\USBStack\CDC (or your chosen location) and
click the Open button to select usbser.inf.
272 CHAPTER 9 Communication Device Class (CDC)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
The wizard confirms your choice and starts to copy, when you click the Next button.
At this point, the installation is complete. Click the Finish button to dismiss the wiz-
ard.
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
273
9.3.1 The .inf file
The .inf file is required for installation.
It is as follows:
;
; Device installation file for
; USB 2 COM port emulation
;
;
;
[Version]
Signature="$CHICAGO$"
Class=Ports
ClassGuid={4D36E978-E325-11CE-BFC1-08002BE10318}
Provider=%MFGNAME%
DriverVer=01/08/2007,2.2.0.0
LayoutFile=Layout.inf
[Manufacturer]
%MFGNAME%=USB2SerialDeviceList
[USB2SerialDeviceList]
%USB2SERIAL%=USB2SerialInstall, USB\VID_8765&PID_0234
[DestinationDirs]
USB2SerialCopyFiles=12
DefaultDestDir=12
[USB2SerialInstall]
CopyFiles=USB2SerialCopyFiles
AddReg=USB2SerialAddReg
[USB2SerialCopyFiles]
usbser.sys,,,0x20
[USB2SerialAddReg]
HKR,,DevLoader,,*ntkern
HKR,,NTMPDriver,,usbser.sys
HKR,,EnumPropPages32,,"MsPorts.dll,SerialPortPropPageProvider"
[USB2SerialInstall.Services]
AddService = usbser,0x0002,USB2SerialService
[USB2SerialService]
DisplayName = %USB2SERIAL_DISPLAY_NAME%
ServiceType = 1 ; SERVICE_KERNEL_DRIVER
StartType = 3 ; SERVICE_DEMAND_START
ErrorControl = 1 ; SERVICE_ERROR_NORMAL
ServiceBinary = %12%\usbser.sys
LoadOrderGroup = Base
[Strings]
MFGNAME= "Manufacturer"
USB2SERIAL = "USB CDC serial port emulation"
USB2SERIAL_DISPLAY_NAME = "USB CDC serial port emulation"
red - required modifications
green - possible modifications
You have to personalize the .inf file on the red marked positions. Changes on the
green marked positions are optional and not necessary for the correct function of the
device.
Replace the red marked positions with your personal vendor Id (VID) and product Id
(PID). These changes have to be identical with the modifications in the configuration
file USB_Config.h to work correctly.
274 CHAPTER 9 Communication Device Class (CDC)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
The required modifications of the file USB_Conf.h are described in the configuration
chapter.
9.3.2 Installation verification
After the device has been installed, it can verify that the installation of the USB
device was successful. Hence, take a look in the device manager to check that the
USB device displayed.
The following steps perform:
•Open the Run dialog box from the start menu.
Type devicemgmt.msc and click OK:
•The Device Manager window is displayed and may look like this:
Click on the Ports (COM & LPT) branch to open the branch:
You should see the USB CDC serial port emulation (COMx), where x gives the
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
275
COM port number has Windows has assigned to the device.
9.3.3 Testing communication to the USB device
The start application is a simple echo server. This means each character that is
entered and sent through the virtual serial port will be sent back by the USB device
and will be shown by a terminal program. To test the communication to the device, a
terminal program such as HyperTerminal, should be used.
This section shows how to check the communication between host and USB host
using the HyperTerminal program.
This section is relevant for Windows XP and below, for newer Windows versions
please use a terminal program of your choice.
•Open the Run dialog box from the start menu.
Type hypertrm.exe and press Enter key to open the HyperTerminal.
HyperTerminal displays the Connection Description dialog.
Give this new connection a name as shown below and click OK.
276 CHAPTER 9 Communication Device Class (CDC)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
After creating the new connection, the Connect To dialog box is displayed and
will ask which COM port you want to use. Click on the arrow for the Connect
Using drop down box. Select COMx, where x is the port number that is assigned
to your device by Windows. To confirm your choice click OK.
•The COMx Property dialog box is displayed to setup the connection properties.
Setup the values as shown below:
To confirm your selection, click OK.
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
277
Now everything is configured and an empty terminal window is shown.
Type any characters, these characters will be send to target. The echo of the tar-
get is shown in the terminal window:
278 CHAPTER 9 Communication Device Class (CDC)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
9.4 Target API
This chapter describes the functions and data structures that can be used with the
target application.
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
279
9.4.1 Interface function list
Name Description
API functions
USB_CDC_Add() Adds CDC-class to the emUSB interface.
USB_CDC_CancelRead()
USB_CDC_CancelReadEx()
Cancels an asynchronous read operation that
is pending
USB_CDC_CancelWrite()
USB_CDC_CancelWriteEx()
Cancels an asynchronous read operation that
is pending
USB_CDC_Read()
USB_CDC_ReadEx() Reads data from host.
USB_CDC_ReadOverlapped()
USB_CDC_ReadOverlappedEx() Reads data from host asynchronously.
USB_CDC_ReadTimed()
USB_CDC_ReadTimedEx() Reads data from host with a given timeout.
USB_CDC_Receive()
USB_CDC_ReceiveEx() Reads data from host.
USB_CDC_ReceiveTimed()
USB_CDC_ReceiveTimedEx()
Read data from host with a given timeout. This
function returns immediately as soon as data
has been received or a timeout occurs.
USB_CDC_SetOnBreak()
USB_CDC_SetOnBreakEx()
Sets a callback for receiving a SEND_BREAK
by the host.
USB_CDC_SetOnLineCoding()
USB_CDC_SetOnLineCodingEx()
Sets a callback for registering changing of the
“line-coding” by the host.
USB_CDC_UpdateSerialState()
USB_CDC_UpdateSerialStateEx() Changes the current serial state.
USB_CDC_Write()
USB_CDC_WriteEx() Writes data to host.
USB_CDC_WriteOverlapped()
USB_CDC_WriteOverlappedEx() Write data to host asynchronously.
USB_CDC_WriteTimed()
USB_CDC_WriteTimedEx() Writes data to the host with a given timeout.
USB_CDC_WaitForRX()
USB_CDC_WaitForRXEx()
Waits for reading data transfer from the Host
to be ended.
USB_CDC_WaitForTX()
USB_CDC_WaitForTXEx()
Waits for writing data transfer to the Host to
be ended.
USB_CDC_WriteSerialState()
USB_CDC_WriteSerialStateEx() Sends the current serial state to the Host.
USB_CDC_GetNumBytesRemToReadEx
()
Returns the number of byte which still need to
be read.
USB_CDC_GetNumBytesToWriteEx() Returns the number of byte which still need to
be written.
USB_CDC_StartReadTransferEx() Initiate a read data transfer.
USB_CDC_GetNumBytesInBufferEx(
)
Retrives the amount of bytes in the internal
read buffer.
Data structures
USB_CDC_INIT_DATA Initialization structure that is needed when
adding an CDC interface.
USB_CDC_ON_SET_BREAK Callback function to receive a break condition
sent by the host.
USB_CDC_ON_SET_LINE_CODING Callback registering line-coding changes.
USB_CDC_LINE_CODING Structure that contains the new line-coding
sent by the host.
Table 9.1: USB-CDC API overview
280 CHAPTER 9 Communication Device Class (CDC)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
9.4.2 API functions
9.4.2.1 USB_CDC_Add()
Description
Adds CDC class to the USB interface.
Prototype
USB_CDC_HANDLE USB_CDC_Add(const USB_CDC_INIT_DATA * pInitData);
Return value
== 0xFFFFFFFF - New CDC Instance can not be created.
!= 0xFFFFFFFF - Handle to a valid CDC instance.
Additional information
After the initialization of general emUSB, this is the first function that needs to be
called when the USB-CDC interface is used with emUSB. The returned value can be
used with the CDC Ex-Function in order to talk to the right CDC instance.
For creating more more than one CDC-Instance please make sure the
USB_EnableIAD() is called before, otherwise the CDC instances other than the first
instance will not work correctly.
Parameter Description
pInitData
Pointer to a USB_CDC_INIT_DATA structure. For detailed information
about the USB_CDC_INIT_DATA structure, refer to
USB_CDC_INIT_DATA on page 301.
Table 9.2: USB_CDC_Add() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
281
9.4.2.2 USB_CDC_CancelRead()
USB_CDC_CancelReadEx()
Description
Cancels a non-blocking write operation that is pending.
Prototype
void USB_CDC_CancelRead(void);
void USB_CDC_CancelReadEx(USB_CDC_HANDLE hInst);
Additional information
This function shall be called when a pending asynchronous read operation (triggered
by USB_CDC_ReadOverlapped() USB_CDC_ReadOverlappedEx()) should be canceled.
The function can be called from any task.
Parameter Description
hInst Handle to a valid CDC instance, returned by USB_CDC_Add().
Table 9.3: USB_CDC_CancelReadEx() parameter list
282 CHAPTER 9 Communication Device Class (CDC)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
9.4.2.3 USB_CDC_CancelWrite()
USB_CDC_CancelWriteEx()
Description
Cancels a non-blocking write operation that is pending.
Prototype
void USB_CDC_CancelWrite(void);
void USB_CDC_CancelWriteEx(USB_CDC_HANDLE hInst);;
Additional information
This function shall be called when a pending asynchronously write operation (trig-
gered by USB_CDC_WriteOverlapped() USB_CDC_WriteOverlappedEx()) should be
canceled. It can be called from any task.
Parameter Description
hInst Handle to a valid CDC instance, returned by USB_CDC_Add().
Table 9.4: USB_CDC_CancelWriteEx() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
283
9.4.2.4 USB_CDC_Read()
USB_CDC_ReadEx()
Description
Reads data from the host. This function blocks until NumBytes have been read or until
the device is disconnected from the host.
Prototype
int USB_CDC_Read(void * pData, unsigned NumBytes);
int USB_CDC_ReadEx(USB_CDC_HANDLE hInst, void* pData, unsigned NumBytes);
Return value
== NumBytes - Number of bytes that have been read.
!= NumBytes - Returns a USB_STATUS_ERROR.
Additional information
This function blocks a task until all data have been read. In case of a reset or a dis-
connect USB_STATUS_ERROR is returned.
Parameter Description
hInst Handle to a valid CDC instance, returned by USB_CDC_Add().
pData Pointer to a buffer where the received data will be stored.
NumBytes Number of bytes to read.
Table 9.5: USB_CDC_Read()/USB_CDC_ReadEx()parameter list
284 CHAPTER 9 Communication Device Class (CDC)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
9.4.2.5 USB_CDC_ReadOverlapped()
USB_CDC_ReadOverlappedEx()
Description
Reads data from the host asynchronously.
Prototype
int USB_CDC_ReadOverlapped(void* pData, unsigned NumBytes);
int USB_CDC_ReadOverlappedEx(USB_CDC_HANDLE hInst,
void* pData,
unsigned NumBytes);
Return value
> 0 - Number of bytes that have been read from the internal buffer (success).
== 0 - No data was found in the internal buffer (success).
< 0 - Error.
Additional information
This function will not block the calling task. The read transfer will be initiated and the
function returns immediately. In order to synchronize, USB_CDC_WaitForRX()
USB_CDC_WaitForRXEx() needs to be called.
Another synchronisation method would be to periodically call
USB_CDC_GetNumBytesRemToReadEx() in order to see how many bytes still need to be
received (this method is preferred when a non-blocking solution is necessary).
Example:
See USB_CDC_GetNumBytesRemToReadEx().
Parameter Description
hInst Handle to a valid CDC instance, returned by USB_CDC_Add().
pData Pointer to a buffer where the received data will be stored.
NumBytes Number of bytes to read.
Table 9.6: USB_CDC_ReadOverlapped()/USB_CDC_ReadOverlappedEx() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
285
9.4.2.6 USB_CDC_ReadTimed()
USB_CDC_ReadTimedEx()
Description
Reads data from the host with a given timeout.
Prototype
int USB_CDC_ReadTimed(void* pData, unsigned NumBytes, unsigned ms);
int USB_CDC_ReadTimedEx(USB_CDC_HANDLE hInst, void* pData, unsigned
NumBytes, unsigned ms);
Return value
== NumBytes - Number of bytes that have been read within the given timeout.
!= NumBytes - Returns a USB_STATUS_ERROR or USB_STATUS_TIMEOUT.
Additional information
This function blocks a task until all data have been read or a timeout occurs. In case
of a reset or a disconnect USB_STATUS_ERROR is returned.
Parameter Description
hInst Handle to a valid CDC instance, returned by USB_CDC_Add().
pData Pointer to a buffer where the received data will be stored.
NumBytes Number of bytes to read.
ms timeout given in milliseconds. A zero value results in an infinite tim-
eout.
Table 9.7: USB_CDC_ReadTimed()/USB_CDC_ReadTimedEx() parameter list
286 CHAPTER 9 Communication Device Class (CDC)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
9.4.2.7 USB_CDC_Receive()
USB_CDC_ReceiveEx()
Description
Reads data from host. The function blocks until any data has been received. In con-
trast to USB_CDC_Read() USB_CDC_ReadEx() this function does not wait for all of
NumBytes to be received, but returns after the first packet has been received.
Prototype
int USB_CDC_Receive(void * pBuffer, unsigned NumBytes);
int USB_CDC_ReceiveEx(USB_CDC_HANDLE hInst, void * pBuffer, unsigned
NumBytes);
Return value
> 0 - Number of bytes that have been read.
== 0 - Zero packet received (not every controller supports this!) or the target was
disconnected during the function call.
< 0 - Returns a USB_STATUS_ERROR.
Additional information
If no error occurs, this function returns the number of bytes received. Calling
USB_CDC_Receive() will return as much data as is currently available up to the size
of the buffer specified. This function also returns when target is disconnected from
host or when a USB reset occurred, but it will still return the number of bytes read.
Parameter Description
hInst Handle to a valid CDC instance, returned by USB_CDC_Add().
pBuffer Pointer to a buffer where the received data will be stored.
NumBytes Number of bytes to read.
Table 9.8: USB_CDC_Receive()/USB_CDC_ReceiveEx() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
287
9.4.2.8 USB_CDC_ReceiveTimed()
USB_CDC_ReceiveTimedEx()
Description
Reads data from host. The function blocks until any data has been received. In con-
trast to USB_CDC_Read() USB_CDC_ReadEx() this function does not wait for all of
NumBytes to be received, but returns after the first packet has been received or after
the timeout has been reached.
Prototype
int USB_CDC_ReceiveTimed(void * pBuffer, unsigned NumBytes, unsigned ms);
int USB_CDC_ReceiveTimedEx(USB_CDC_HANDLE hInst, void * pBuffer, unsigned
NumBytes, unsigned ms);
Return value
> 0 - Number of bytes that have been read within the given timeout.
== 0 - Zero packet received (not every controller supports this!) or the target was
disconnected during the function call.
< 0 - Returns a USB_STATUS_ERROR or USB_STATUS_TIMEOUT.
Additional information
If no error occurs, this function returns the number of bytes received.
Calling USB_CDC_ReceiveTimed() will return as much data as is currently available
up to the size of the buffer specified within the specified timeout. This function also
returns when target is disconnected from host or when a USB reset occurred, but it
will still return the number of bytes read.
Parameter Description
hInst Handle to a valid CDC instance, returned by USB_CDC_Add().
pBuffer Pointer to a buffer where the received data will be stored.
NumBytes Number of bytes to read.
ms timeout given in milliseconds. A zero value results in an infinite tim-
eout.
Table 9.9: USB_CDC_ReceiveTimed()/USB_CDC_ReceiveTimedEx() parameter list
288 CHAPTER 9 Communication Device Class (CDC)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
9.4.2.9 USB_CDC_SetOnBreak()
USB_CDC_SetOnBreakEx()
Description
Sets a callback for receiving a SEND_BREAK by the host.
Prototype
void USB_CDC_SetOnBreak (USB_CDC_ON_SET_BREAK * pfOnBreak);
void USB_CDC_SetOnBreakEx(USB_CDC_HANDLE hInst,
USB_CDC_ON_SET_BREAK * pfOnBreak);
Additional information
This function is used to register a user callback which should notify the application
when a break condition was sent by the host. Refer to USB_CDC_ON_SET_BREAK on
page 302 for detailed information. The callback is called in an ISR context, therefore
it should should execute quickly.
Parameter Description
hInst Handle to a valid CDC instance, returned by USB_CDC_Add().
pf
Pointer to the callback function USB_CDC_ON_SET_BREAK. For
detailed information about the USB_CDC_ON_SET_BREAK function
pointer, refer to USB_CDC_ON_SET_BREAK on page 302.
Table 9.10: USB_CDC_SeOnBreak()/USB_CDC_SeOnBreakEx() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
289
9.4.2.10 USB_CDC_SetOnLineCoding()
USB_CDC_SetOnLineCodingEx()
Description
Sets a callback for registering changing of the “line-coding” by the host.
Prototype
void USB_CDC_SetOnLineCoding(USB_CDC_ON_SET_LINE_CODING * pf);
void USB_CDC_SetOnLineCodingEx(USB_CDC_HANDLE hInst,
USB_CDC_ON_SET_LINE_CODING * pf);
Additional information
This function is used to register a user callback which notifies the application that the
host has changed the line coding refer to USB_CDC_ON_SET_LINE_CODING on
page 303 for detailed information. The callback is called in an ISR context, therefore
it should execute quickly.
Parameter Description
hInst Handle to a valid CDC instance, returned by USB_CDC_Add().
pf
Pointer to the callback function USB_CDC_ON_SET_LINE_CODING. For
detailed information about the USB_CDC_ON_SET_LINE_CODING func-
tion pointer, refer to USB_CDC_ON_SET_LINE_CODING on
page 303.
Table 9.11: USB_CDC_SetLineCoding()/USB_CDC_SetLineCodingEx() parameter list
290 CHAPTER 9 Communication Device Class (CDC)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
9.4.2.11 USB_CDC_UpdateSerialState()
USB_CDC_UpdateSerialStateEx()
Description
Updates the control line state of the.
Prototype
void USB_CDC_UpdateSerialState(USB_CDC_SERIAL_STATE * pSerialState);
void USB_CDC_UpdateSerialStateEx(USB_CDC_HANDLE hInst, USB_CDC_SERIAL_STATE
* pSerialState);
Additional information
This function updates the control line state internally. In order to inform the host
about the serial state change, refer to the function USB_CDC_WriteSerialState()
USB_CDC_WriteSerialStateEx() on page 296.
Parameter Description
hInst Handle to a valid CDC instance, returned by USB_CDC_Add().
pSerialState Pointer to the USB_CDC_SERIAL_STATE structure, refer to
USB_CDC_SERIAL_STATE on page 305.
Table 9.12: USB_CDC_UpdateSerialState()/USB_CDC_UpdateSerialStateEx() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
291
9.4.2.12 USB_CDC_Write()
USB_CDC_WriteEx()
Description
Write data to the host.
Prototype
void USB_CDC_Write(const void* pData, unsigned NumBytes);
void USB_CDC_WriteEx(USB_CDC_HANDLE hInst, const void* pData, unsigned
NumBytes);
Additional information
This function is blocking.
Parameter Description
hInst Handle to a valid CDC instance, returned by USB_CDC_Add().
pData Pointer to data that should be sent to the host.
NumBytes Number of bytes to write.
Table 9.13: USB_CDC_Write()/USB_CDC_WriteEx() parameter list
292 CHAPTER 9 Communication Device Class (CDC)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
9.4.2.13 USB_CDC_WriteOverlapped()
USB_CDC_WriteOverlappedEx()
Description
Write data to the host asynchronously.
Prototype
void USB_CDC_WriteOverlapped(const void* pData, unsigned NumBytes);
void USB_CDC_WriteOverlappedEx(USB_CDC_HANDLE hInst, const void* pData,
unsigned NumBytes);
Return value
> 0 - Number of bytes that have been written from the internal buffer (success).
== 0 - No data was found in the internal buffer (success).
< 0 - Error.
Additional information
This function will not block the calling task. The write transfer will be initiated and
the function returns immediately. In order to synchronize, USB_CDC_WaitForTX()
USB_CDC_WaitForTXEx()() needs to be called.
Another synchronisation method would be to periodically call
USB_CDC_GetNumBytesToWriteEx() in order to see how many bytes still need to be
written (this method is preferred when a non-blocking solution is necessary).
Example:
See USB_CDC_GetNumBytesToWriteEx().
Parameter Description
hInst Handle to a valid CDC instance, returned by USB_CDC_Add().
pData Pointer to data that should be sent to the host.
NumBytes Number of bytes to write.
Table 9.14: USB_CDC_WriteOverlapped()/USB_CDC_WriteOverlappedEx() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
293
9.4.2.14 USB_CDC_WriteTimed()
USB_CDC_WriteTimedEx()
Description
Writes data to the host with a given timeout.
Prototype
int USB_CDC_WriteTimed(const void * pData, unsigned NumBytes, unsigned ms)
int USB_CDC_WriteTimedEx(USB_CDC_HANDLE hInst, const void * pData, unsigned
NumBytes, unsigned ms);
Return value
>= 0 - Number of bytes that have been written within the given timeout.
< 0 - Returns a USB_STATUS_ERROR or USB_STATUS_TIMEOUT.
Additional information
This function blocks a task until all data have been written or a timeout occurs. This
function also returns when target is disconnected from host or when a USB reset
occurred.
Parameter Description
hInst Handle to a valid CDC instance, returned by USB_CDC_Add().
pData Pointer to a buffer where the data to send is stored.
NumBytes Number of bytes to write.
ms timeout given in milliseconds. A zero value results in an infinite tim-
eout.
Table 9.15: USB_CDC_WriteTimed()/USB_CDC_WriteTimedEx() parameter list
294 CHAPTER 9 Communication Device Class (CDC)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
9.4.2.15 USB_CDC_WaitForRX()
USB_CDC_WaitForRXEx()
Description
This function is to be used in combination with USB_CDC_ReadOverlapped()
USB_CDC_ReadOverlappedEx(). This function waits for the reading data transfer from
the host to complete.
Prototype
void USB_CDC_WaitForRX(void);
void USB_CDC_WaitForRXEx(USB_CDC_HANDLE hInst);
Additional information
This function shall be called in order to synchronize task with the read data transfer
that previously initiated.
This function blocks until the number of bytes specified by
USB_CDC_ReadOverlapped() USB_CDC_ReadOverlappedEx() has been read from the
host.
Parameter Description
hInst Handle to a valid CDC instance, returned by USB_CDC_Add().
Table 9.16: USB_CDC_WaitForRX()/USB_CDC_WaitForRXEx() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
295
9.4.2.16 USB_CDC_WaitForTX()
USB_CDC_WaitForTXEx()
Description
This function is to be used in combination with USB_CDC_WriteOverlapped()
USB_CDC_WriteOverlappedEx(). This function waits for the writing data transfer to
the host to complete.
Prototype
void USB_CDC_WaitForTX(void);
void USB_CDC_WaitForTXEx(USB_CDC_HANDLE hInst);
Additional information
This function shall be called in order to synchronize task with the write data transfer
that previously initiated.
This function blocks until the number of bytes specified by
USB_CDC_WriteOverlapped() USB_CDC_WriteOverlappedEx() has been written to
the host.
Parameter Description
hInst Handle to a valid CDC instance, returned by USB_CDC_Add().
Table 9.17: USB_CDC_WaitForTX()/USB_CDC_WaitForTXEx() parameter list
296 CHAPTER 9 Communication Device Class (CDC)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
9.4.2.17 USB_CDC_WriteSerialState()
USB_CDC_WriteSerialStateEx()
Description
Sends the current control line serial state to the host.
Prototype
void USB_CDC_WriteSerialState(void);
void USB_CDC_WriteSerialStateEx(USB_CDC_HANDLE hInst);
Additional information
This function shall be called in order to inform the host about the control serial state
of the CDC instance. It may be called within the same function or in another task
dedicated for sending the serial state.
This function blocks until the host has received the serial state.
Parameter Description
hInst Handle to a valid CDC instance, returned by USB_CDC_Add().
Table 9.18: USB_CDC_WriteSerialState()/USB_CDC_WriteSerialStateEx parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
297
9.4.2.18 USB_CDC_GetNumBytesRemToReadEx()
Description
This function is to be used in combination with USB_CDC_ReadOverlapped()
USB_CDC_ReadOverlappedEx(). It returns the number of bytes which still have to be
read during the transaction.
Prototype
unsigned USB_CDC_GetNumBytesRemToReadEx(USB_CDC_HANDLE hInst);
Return value
>= 0 - Number of bytes which still have to be read.
< 0 - Error.
Additional information
Note that this function does not return the number of bytes that have been read, but
the number of bytes which still have to be read.
This function does not block.
Example:
NumBytesReceived = USB_CDC_ReadOverlappedEx(hInst, &ac[0], 50);
if (NumBytesReceived > 0) {
// Already had some data in the internal buffer.
<...process remaining bytes...>
} else {
// Wait until we get all 50 bytes
NumBytesToRead = USB_CDC_GetNumBytesRemToReadEx(hInst);
while (NumBytesToRead > 0) {
USB_OS_Delay(50);
NumBytesToRead = USB_CDC_GetNumBytesRemToReadEx(hInst);
}
}
Parameter Description
hInst Handle to a valid CDC instance, returned by USB_CDC_Add().
Table 9.19: USB_CDC_GetNumBytesRemToReadEx() parameter list
298 CHAPTER 9 Communication Device Class (CDC)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
9.4.2.19 USB_CDC_GetNumBytesToWriteEx()
Description
This function is to be used in combination with USB_CDC_WriteOverlapped()
USB_CDC_WriteOverlappedEx(). It returns the number of bytes which still have to be
written during the transaction.
Prototype
unsigned USB_CDC_GetNumBytesToWriteEx(USB_CDC_HANDLE hInst);
Return value
>= 0 - Number of bytes which still have to be written.
< 0 - Error.
Additional information
Note that this function does not return the number of bytes that have been read, but
the number of bytes which still have to be read.
This function does not block.
Example:
// NumBytesWritten will contain > 0 values if we had anything in the write buffer.
NumBytesWritten = USB_CDC_WriteOverlappedEx(hInst, &ac[0], TRANSFER_SIZE);
// NumBytesToWrite shows how many bytes still have to be written.
NumBytesToWrite = USB_CDC_GetNumBytesToWriteEx(hInst);
while (NumBytesToWrite > 0) {
USB_OS_Delay(50);
NumBytesToWrite = USB_CDC_GetNumBytesToWriteEx(hInst);
}
Parameter Description
hInst Handle to a valid CDC instance, returned by USB_CDC_Add().
Table 9.20: USB_CDC_GetNumBytesToWriteEx() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
299
9.4.2.20 USB_CDC_StartReadTransferEx()
Description
Initiate a read data transfer. Data will be stored in the internal buffer.
Prototype
void USB_CDC_StartReadTransferEx(USB_CDC_HANDLE hInst);
Additional information
To check how many bytes have been stored, the fucntion
USB_CDC_GetNumBytesInBufferEx() has to be called.
In order to read the data the function USB_CDC_Read() USB_CDC_ReadEx() needs to
be called.
This function does not block.
Example:
//
// Trigger the read transfer.
//
USB_CDC_StartReadTransferEx(hInst);
while (1) {
//
// Check whether we received some bytes.
//
NumBytesReceived = USB_CDC_GetNumBytesInBufferEx(hInst);
if (NumBytesReceived) {
//
// If we received something - use the normal Read function
//
USB_CDC_ReadEx(hInst, &ac[0], NumBytesReceived);
} else {
<.. Nothing received yet, do application processing..>
}
}
Parameter Description
hInst Handle to a valid CDC instance, returned by USB_CDC_Add().
Table 9.21: USB_CDC_StartReadTransferEx() parameter list
300 CHAPTER 9 Communication Device Class (CDC)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
9.4.2.21 USB_CDC_GetNumBytesInBufferEx()
Description
This function is to be used in combination with USB_CDC_StartReadTransferEx().
This functions retrives the number of bytes which have been store in the internal
read buffer after USB_CDC_StartReadTransferEx() has been called.
Prototype
unsigned USB_CDC_GetNumBytesInBufferEx(USB_CDC_HANDLE hInst);
Return value
> 0 - Number of bytes which have been stored in the internal buffer.
== 0 - Nothing stored yet.
Parameter Description
hInst Handle to a valid CDC instance, returned by USB_CDC_Add().
Table 9.22: USB_CDC_GetNumBytesInBufferEx() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
301
9.4.3 Data structures
9.4.3.1 USB_CDC_INIT_DATA
Description
Initialization structure that is needed when adding an CDC interface to emUSB.
Prototype
typedef struct {
U8 EPIn;
U8 EPOut;
U8 EPInt;
} USB_CDC_INIT_DATA;
Additional Information
This structure is used when the CDC interface is added to emUSB. EPInt is not used
in this version of the emUSB CDC component, status information are not sent to the
host.
Member Description
EPIn Endpoint for sending data to the host
EPOut Endpoint for receiving data from the host
EPInt Endpoint for sending status information.
Table 9.23: USB_CDC_INIT_DATA elements
302 CHAPTER 9 Communication Device Class (CDC)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
9.4.3.2 USB_CDC_ON_SET_BREAK
Description
Callback function to receive a break condition sent by the host.
Prototype
typedef void USB_CDC_ON_SET_BREAK(unsigned BreakDuration);
Additional Information
This type of callback is used to notify the application that the host has sent a break
condition. If BreakDuration is 0xFFFF, then the host will send a break until another
SendBreak request is received with BreakDuration of 0x0000. Since the callback is
called within an interrupt service routine it should execute quickly.
Member Description
BreakDura-
tion
The BreakDuration gives the length of time, in milliseconds, of the break
signal.
Table 9.24: USB_CDC_ON_SET_LINE_CODING elements
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
303
9.4.3.3 USB_CDC_ON_SET_LINE_CODING
Description
Callback function to register line-coding changes.
Prototype
typedef void USB_CDC_ON_SET_LINE_CODING(USB_CDC_LINE_CODING * pLineCoding);
Additional Information
This type of callback is used to notify the application that the host has changed the
line coding. For example the baud rate has been changed. The new “line-coding” are
passed through the structure USB_CD_LINE_CODING. Refer to USB_CDC_LINE_CODING
on page 304 for more information about the elements of these structure. Since the
callback is called within an interrupt service routine it should execute quickly.
Member Description
pLineCoding Pointer to USB_CDC_LINE_CODING structure
Table 9.25: USB_CDC_ON_SET_LINE_CODING elements
304 CHAPTER 9 Communication Device Class (CDC)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
9.4.3.4 USB_CDC_LINE_CODING
Description
Structure that contains the new line-coding sent by the host.
Prototype
typedef struct {
U32 DTERate;
U8 CharFormat;
U8 ParityType;
U8 DataBits;
} USB_CDC_LINE_CODING;
Member Description
DTERate The data transfer rate for the device in bits per second.
CharFormat
Contain the stop bits:
0 - 1 Stop bit
1 - 1.5 Stop bits
2 - 2 Stop bits
ParityType
Specifies the parity type:
0 - None
1 - Odd
2 - Even
3 - Mark
4 - Space
DataBits Specifies the bits per byte: (5, 6, 7, 8, 16)
Table 9.26: USB_CDC_LINE_CODING elements
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
305
9.4.3.5 USB_CDC_SERIAL_STATE
Description
Structure that contains the new line-coding sent by the host.
Prototype
typedef struct {
U8 DCD;
U8 DSR;
U8 Break;
U8 Ring;
U8 FramingError;
U8 ParityError;
U8 OverRunError;
U8 CTS;
} USB_CDC_SERIAL_STATE;
Member Description
DCD Data Carrier Detect: Tells that the device is connected to the telephone
line.
DSR Data Set Read: Device is ready to receive data.
Break 1 - Break condition signaled.
Ring Device indicates that it has detected a ring signal on the telephone
line.
FramingError When set to 1, the device indicates a framing error.
ParityError When set to 1, the device indicates a parity error.
OverRunError When set to 1, the device indicates an over-run error.
CTS Clear to send: Acknowledges RTS and allows the host to transmit.
Table 9.27: USB_CDC_LINE_CODING elements
306 CHAPTER 9 Communication Device Class (CDC)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
307
Chapter 10
Human Interface Device Class
(HID)
This chapter gives a general overview of the HID class and describes how to get the
HID component running on the target.
308 CHAPTER 10 Human Interface De vice Class (HID)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
10.1 Overview
The Human Interface Device class (HID) is an abstract USB class protocol defined by
the USB Implementers Forum. This protocol was defined for the handling of devices
which are used by humans to control the operation of computer systems.
An installation of a custom-host USB driver is not necessary, because the USB human
interface device class is standardized and every major OS already provides host driv-
ers for it.
Method of communication
HID always uses interrupt end points. Since interrupt endpoints are limited to at
most one packet of at most 64 bytes per frame (on full speed devices), the transfer
rate is limited to 64000 bytes/sec, in reality much less than that.
10.1.1 Further reading
The following documents define the HID class and have been used to implement and
verify the HID component:
•[HID1]
Device Class Definition for Human Interface Devices (HID), Firmware Specifica-
tion—6/27/01 Version 1.11
•[HID2]
HID Usage Tables, 1/21/2005 Version 1.12
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
309
10.1.2 Categories
Devices which are in the HID class generally fall into one of two categories:
True HIDs and vendor specific HIDs, explained in the following. One ore more exam-
ples for both categories are provided.
10.1.2.1 True HIDs
HID devices communicating with the host operating system. Devices which are used
by a human to enter data, but do not directly exchange data with an application pro-
gram running on the host.
Typical examples
•Keyboard
Mouse and similar pointing devices
•Joystick
•Game pad
Front-panel controls - for example, switches and buttons.
10.1.2.2 Vendor specific HIDs
These are HID devices communicating with an application program. The host OS
loads the same driver it loads for any “true HID” and will automatically enumerate
the device, but it cannot communicate with the device. When analyzing the report
descriptor, the host finds that it cannot exchange information with the device; the
device uses a protocol which is meaningless to the HID driver of the host. The host
will therefore not exchange information with the device. A host recognizes a vendor
specific HID by its vendor-defined usage page in the report descriptor: the numerical
value of the usage page lies between 0xFF00 and 0xFFFF.
An application has the chance to communicate with the particular device using API
functions offered by the host. This enables an application program to communicate
with the device without having to load a driver. HID does not take advantage of the
full USB bus bandwidth; bulk communication can be much faster, but requires a
driver. Therefore it can be a good choice to select HID as a device class, especially if
ease of use is important and high communication speed is not a requirement.
Typical examples
•Bar-code reader
Thermometer
Voltmeter
Low-speed JTAG emulator
UPS (Uninterruptible power supply)
310 CHAPTER 10 Human Interface De vice Class (HID)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
10.2 Background information
10.2.1 HID descriptors
This section presents an overview of the HID class-specific descriptors. The HID
descriptors are defined in the Device Class Definition for Human Interface Devices
(HID) of the USB Implementers Forum. Refer to the USB Implementers Forum web-
site, www.usb.org, for detailed information about the USB HID standard.
10.2.1.1 HID descriptor
A HID descriptor contains the report and optional the physical descriptors. It speci-
fies the number, type, and size of report and physical descriptors.
10.2.1.2 Report descriptor
The data exchanged between host and device is exchanged in so called “reports”. The
report descriptor defines the format of a report. In general, HIDs require a report
descriptor as defined in the Device Class Definition for Human Interface Devices
(HID). The only exception to this are very basic HIDs such as mice or keyboards. This
implementation of HID always requires a report descriptor.
Device
descriptor
Interface
descriptor
Configuration
descriptor
Endpoint
descriptor
HID
descriptor
Report
descriptor
Physical
descriptor
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
311
The USB Implementers Forum provides an application which helps to build and mod-
ify HID report descriptors. The HID Descriptor Tool can be downloaded from:
http://www.usb.org/developers/hidpage/
10.2.1.3 Physical descriptor
Physical descriptor sets are optional descriptors which provide information about the
part or parts of the human body used to activate the controls on a device. Physical
descriptors are not currently supported.
312 CHAPTER 10 Human Interface De vice Class (HID)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
10.3 Configuration
10.3.1 Initial configuration
To get emUSB up and running as well as doing an initial test, the configuration as it is
delivered should not be modified. The configuration must only be modified if emUSB
should be used in your final product. Refer to the section Configuration on page 44
for detailed information about the functions which must be adapted before you can
release a final product version.
10.3.2 Final configuration
Generating a report descriptor
This step is only required if your product is a vendor-specific human interface device.
The report descriptor provided in the example application can typically be used with-
out any modification. The vendor-defined usage page should be adapted in a final
product. Vendor defined usage pages can be in the range from 0xFF00 through
0xFFFF. The low byte can be selected by the application programmer. It needs to be
identical on both target and host and should be unique (as unique as an 8-bit value
can be). The example(s) use the value 0x12; this value is defined at the top of the
application program with the macro USB_HID_DEFAULT_VENDOR_PAGE.
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
313
10.4 Example application
Example applications are supplied. These can be used for testing the correct installa-
tion and proper function of the device running emUSB.
The following start application files are provided:
10.4.1 HID_Mouse.c
HID_Mouse.c is a typical example for a “true HID” implementation. The host identi-
fies the device which is programmed with this example as a mouse. After the device
is enumerated moves the mouse cursor in an endless loop to the left and after a
short delay back to the right.
10.4.1.1 Running the example
1. Add HID_Mouse.c to your project and build and download the application into the tar-
get.
2. When you connect your target to the host via USB, Windows will detect the new
HID device.
3. If a connection can be established moves the mouse cursor in an endless loop to
the left and after a short delay back to the right as long as you do not disconnect
your target.
File Description
HID_Mouse.c Simple mouse example. (“True HID” example)
HID_Echo1.c Modified echo server. (“vendor specific” example)
Table 10.1: Supplied example HID applications
314 CHAPTER 10 Human Interface De vice Class (HID)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
10.4.2 HID_Echo1.c
HID_Echo1.c is a typical example for a “vendor-specific HID” implementation. The
HID start application (HID_Echo1.c located in the Application subfolder) is a modi-
fied echo server; the application receives data byte by byte, increments every single
byte and sends them back to the host.
To use this application, include the source code file HID_Echo1.c into your project
and compile and download it into your target. Run HIDEcho1.exe after the target is
connected to host and the enumeration process has been completed. The PC applica-
tion is supplied as executable in the HID\SampleApp\Exe directory. The source code
of the PC example is also supplied. Refer to section Compiling the PC example appli-
cation on page 315 for more information to the PC example project.
10.4.2.1 Running the example
1. Add HID_Echo1.c to your project and build and download the application into the tar-
get.
2. Connect your target to the host via USB while the example application is running,
Windows will detect the new HID device.
3. If a connection can be established, it exchanges data with the target, testing the
USB connection. If the host example application can communicate with the
emUSB device, the example application outputs the product name, vendor and
product ID and the report size which will be used to communicate with the tar-
get. The target will be in interactive mode.
Host (PC)
Target
USB HID
example
application
Target programmed
with the example
application consistent
with the application
running on host side:
HID_Echo1.c
USB connection
HIDEcho1.exe
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
315
Example output of HID_Echo1.exe:
4. Enter the number of reports that should be transmitted, when the device is con-
nect. Every dot in the terminal window indicates a transmission.
10.4.2.2 Compiling the PC example application
To compile the example application you need a Microsoft compiler. The compiler is
part of Microsoft Visual C++ 6.0 or Microsoft Visual Studio .Net. The source code of
the example application is located in the subfolder HID\SampleApp. Open the file
USBHID_Start.dsw and compile the source choose Build | Build SampleApp.exe
(Shortcut: F7). To run the executable choose Build | Execute SampleApp.exe
(Shortcut: CTRL-F5).
Note: The Microsoft Windows Driver Development Kit (DDK) is required to com-
pile the HID host example application. Refer to http://www.microsoft.com/whdc/dev-
tools/ddk/default.mspx for more information.
316 CHAPTER 10 Human Interface De vice Class (HID)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
10.5 Target API
This section describes the functions that can be used on the target system.
General information
To communicate with the host, the example application project includes USB-specific
header and source files.These files contain API functions to communicate with the
USB host.
Purpose of the USB Device API functions
To have an easy start up when writing an application on the device side, these API
functions have a simple interface and handle all operations that need to be done to
communicate with the host.
Therefore, all operations that need to write to or read from the emUSB are handled
internally by the provided API functions.
10.5.1 Target interface function list
Function Description
API functions
USB_HID_Add() Adds HID-class to the emUSB interface.
USB_HID_GetNumBytesInBuffer() /
USB_HID_GetNumBytesInBufferEx()
Returns the number of bytes in the inter-
nal read buffer.
USB_HID_GetNumBytesRemToRead() /
USB_HID_GetNumBytesRemToReadEx()
Returns the number of bytes which still
have to be read.
USB_HID_GetNumBytesToWrite() /
USB_HID_GetNumBytesToWriteEx()
Returns the number of bytes which still
have to be written.
USB_HID_Read() / USB_HID_ReadEx() Read data from the host.
USB_HID_ReadEPOverlapped() /
USB_HID_ReadEPOverlappedEx() Non-blocking version of USB_HID_Read()
USB_HID_ReadTimed() /
USB_HID_ReadExTimed()
Starts a read operation that shall be done
within a given timeout.
USB_HID_StartReadTransfer() /
USB_HID_StartReadTransferEx() Initiate a read data transfer.
USB_HID_WaitForRX() /
USB_HID_WaitForRXEx()
Waits for a non-blocking write operation
that is pending.
USB_HID_WaitForTX() /
USB_HID_WaitForTXEx()
Waits for a non-blocking write operation
that is pending.
USB_HID_Write() / USB_HID_WriteEx() Write data to the host.
USB_HID_WriteEPOverlapped() /
USB_HID_WriteEPOverlappedEx()
Non-blocking version of
USB_HID_Write()
USB_HID_WriteTimed() /
USB_HID_WriteExTimed()
Starts a write operation that shall be
done within a given timeout.
Data structures
USB_HID_INIT_DATA Initialization structure that is required
when adding a HID interface.
Table 10.2: USB-HID target interface function list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
317
10.5.2 USB-HID functions
10.5.2.1 USB_HID_Add()
Description
Adds HID class device to the USB interface.
Prototype
USB_HID_HANDLE USB_HID_Add(const USB_HID_INIT_DATA * pInitData);
Return value
USB_HID_HANDLE - Handle to the HID instance (can be zero).
Additional information
After the initialization of general emUSB, this is the first function that needs to be
called when the USB-HID interface is used with emUSB.
Parameter Description
pInitData
Pointer to a USB_HID_INIT_DATA structure. For detailed information
about the USB_HID_INIT_DATA structure, refer to
USB_HID_INIT_DATA on page 330.
Table 10.3: USB_HID_Add() parameter list
318 CHAPTER 10 Human Interface De vice Class (HID)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
10.5.2.2 USB_HID_GetNumBytesInBuffer() /
USB_HID_GetNumBytesInBufferEx()
Description
This function is to be used in combination with USB_HID_StartReadTransfer() /
USB_HID_StartReadTransferEx() on page 324.
The function will return the number of bytes available in the internal read buffer.
Prototype
unsigned USB_HID_GetNumBytesInBuffer (void);
unsigned USB_HID_GetNumBytesInBufferEx (USB_HID_HANDLE hInterface);
Return value
>= 0 Number of bytes in the internal read buffer.
Parameter Description
hInterface Handle to a HID instance.
Table 10.4: USB_HID_GetNumBytesInBuffer() / USB_HID_GetNumBytesInBufferEx() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
319
10.5.2.3 USB_HID_GetNumBytesRemToRead() /
USB_HID_GetNumBytesRemToReadEx()
Description
This function is to be used in combination with USB_HID_ReadEPOverlapped() /
USB_HID_ReadEPOverlappedEx() on page 322.
After starting the read operation this function can be used to periodically check how
many bytes still have to be read.
Prototype
unsigned USB_HID_GetNumBytesRemToRead (void);
unsigned USB_HID_GetNumBytesRemToReadEx (USB_HID_HANDLE hInterface);
Return value
>= 0 Number of bytes which have not yet been read.
Additional information
Alternatively the blocking function USB_HID_WaitForRX() / USB_HID_WaitForRXEx()
on page 325 can be used.
Parameter Description
hInterface Handle to a HID instance.
Table 10.5: USB_HID_GetNumBytesRemToRead() / USB_HID_GetNumBytesRemToReadEx() param-
eter list
320 CHAPTER 10 Human Interface De vice Class (HID)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
10.5.2.4 USB_HID_GetNumBytesToWrite() /
USB_HID_GetNumBytesToWriteEx()
Description
This function is to be used in combination with USB_HID_WriteEPOverlapped() /
USB_HID_WriteEPOverlappedEx() on page 328.
After starting the write operation this function can be used to periodically check how
many bytes still have to be written.
Prototype
unsigned USB_HID_GetNumBytesToWrite (void);
unsigned USB_HID_GetNumBytesToWriteEx (USB_HID_HANDLE hInterface);
Return value
>= 0 Number of bytes which have not yet been written.
Additional information
Alternatively the blocking function USB_HID_WaitForTX() / USB_HID_WaitForTXEx()
on page 326 can be used.
Parameter Description
hInterface Handle to a HID instance.
Table 10.6: USB_HID_GetNumBytesToWrite() / USB_HID_GetNumBytesToWriteEx() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
321
10.5.2.5 USB_HID_Read() / USB_HID_ReadEx()
Description
Reads data from the host. This function blocks until it has received NumBytes or until
the device is disconnected from the host.
Prototype
int USB_HID_Read (void* pData, unsigned NumBytes);
int USB_HID_ReadEx (USB_HID_HANDLE hInterface,
void* pData,
unsigned NumBytes);
Return value
>= 0 Number of bytes that have been received.
USB_STATUS_ERROR In case of an error.
Parameter Description
hInterface Handle to a HID instance.
pData Pointer to a buffer where the received data will be stored.
NumBytes Number of bytes to read.
Table 10.7: USB_HID_Read() / USB_HID_ReadEx() parameter list
322 CHAPTER 10 Human Interface De vice Class (HID)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
10.5.2.6 USB_HID_ReadEPOverlapped() /
USB_HID_ReadEPOverlappedEx()
Description
Reads data from the host asynchronously.
Prototype
int USB_HID_ReadEPOverlapped (void* pData, unsigned NumBytes);
int USB_HID_ReadEPOverlappedEx (USB_HID_HANDLE hInterface,
void* pData,
unsigned NumBytes);
Return value
Number of bytes that have already been received or have been copied from internal
buffer. The value can be less or equal to NumBytes.
Additional information
This function will not block the calling task. The read transfer will be initiated and the
function returns immediately. In order to synchronize, USB_BULK_WaitForRX() needs
to be called. Alternatively the function USB_HID_GetNumBytesToWrite() /
USB_HID_GetNumBytesToWriteEx() on page 320 can be called periodically to check
whether all bytes have been written or not.
Parameter Description
pData Pointer to a buffer where the received data will be stored.
NumBytes Number of bytes to read.
Table 10.8: USB_HID_ReadEPOverlapped() / USB_HID_ReadEPOverlappedEx() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
323
10.5.2.7 USB_HID_ReadTimed() / USB_HID_ReadExTimed()
Description
Reads data from the host with a given timeout. This function blocks until the timeout
has been reached, it has received NumBytes or until the device is disconnected from
the host.
Prototype
int USB_HID_ReadTimed (void* pData, unsigned NumBytes, unsigned ms);
int USB_HID_ReadExTimed (USB_HID_HANDLE hInterface,
void* pData,
unsigned NumBytes,
unsigned ms);
Return value
>= 0 Number of bytes that have been received.
USB_STATUS_ERROR In case of an error.
USB_STATUS_TIMEOUT In case of a timeout.
Parameter Description
hInterface Handle to a HID instance.
pData Pointer to a buffer where the received data will be stored.
NumBytes Number of bytes to read.
ms Timeout in milliseconds.
Table 10.9: USB_HID_ReadTimed() / USB_HID_ReadExTimed() parameter list
324 CHAPTER 10 Human Interface De vice Class (HID)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
10.5.2.8 USB_HID_StartReadTransfer() /
USB_HID_StartReadTransferEx()
Description
Initiates a read data transfer. Data will be stored in the internal buffer.
Prototype
void USB_HID_StartReadTransfer (void);
void USB_HID_StartReadTransferEx (USB_HID_HANDLE hInst);
Additional information
After this function has been called the function USB_HID_GetNumBytesInBuffer() /
USB_HID_GetNumBytesInBufferEx() on page 318 can be used to check how many
bytes haben been read. To actually receive the data on the application level
USB_HID_Read() / USB_HID_ReadEx() on page 321 has to be called. By calling the
read function with the previously received number of bytes it is possible to make sure
the read function does not block.
Parameter Description
hInterface Handle to a HID instance.
Table 10.10: USB_HID_StartReadTransfer() / USB_HID_StartReadTransferEx() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
325
10.5.2.9 USB_HID_WaitForRX() / USB_HID_WaitForRXEx()
Description
This function is to be used in combination with USB_HID_ReadEPOverlapped() /
USB_HID_ReadEPOverlappedEx() on page 322.
After the read function has been called this function can be used to synchronise. It
will block until the transfer is completed.
Prototype
void USB_HID_WaitForRX (void);
void USB_HID_WaitForRXEx (USB_HID_HANDLE hInterface);
Parameter Description
hInterface Handle to a HID instance.
Table 10.11: USB_HID_WaitForRX() / USB_HID_WaitForRXEx() parameter list
326 CHAPTER 10 Human Interface De vice Class (HID)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
10.5.2.10 USB_HID_WaitForTX() / USB_HID_WaitForTXEx()
Description
This function is to be used in combination with USB_HID_WriteEPOverlapped() /
USB_HID_WriteEPOverlappedEx() on page 328.
After the write function has been called this function can be used to synchronise. It
will block until the transfer is completed.
Prototype
void USB_HID_WaitForTX (void);
void USB_HID_WaitForTXEx (USB_HID_HANDLE hInterface);
Parameter Description
hInterface Handle to a HID instance.
Table 10.12: USB_HID_WaitForTX() / USB_HID_WaitForTXEx() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
327
10.5.2.11 USB_HID_Write() / USB_HID_WriteEx()
Description
Writes data to the host. This function blocks until it has written NumBytes or until the
device is disconnected from the host.
Prototype
void USB_HID_Write (const void* pData, unsigned NumBytes);
void USB_HID_WriteEx (USB_HID_HANDLE hInterface,
const void* pData,
unsigned NumBytes);
Parameter Description
hInterface Handle to a HID instance.
pData Pointer to data that should be sent to the host.
NumBytes Number of bytes to write.
Table 10.13: USB_HID_Write() / USB_HID_WriteEx() parameter list
328 CHAPTER 10 Human Interface De vice Class (HID)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
10.5.2.12 USB_HID_WriteEPOverlapped() /
USB_HID_WriteEPOverlappedEx()
Description
Write data to the host asynchronously.
Prototype
int USB_HID_WriteEPOverlapped (const void* pData, unsigned NumBytes);
int USB_HID_WriteEPOverlappedEx (USB_HID_HANDLE hInterface,
const void* pData,
unsigned NumBytes);
Return value
Number of bytes that have already been sent to the host. The value can be less or
equal to NumBytes.
Additional information
This function will not block the calling task. The write transfer will be initiated and
the function returns immediately. In order to synchronize, USB_BULK_WaitForTX()
needs to be called. Alternatively the function USB_HID_GetNumBytesToWrite() /
USB_HID_GetNumBytesToWriteEx() on page 320 can be called periodically to check
whether all bytes have been written or not.
Parameter Description
hInterface Handle to a HID instance.
pData Pointer to data that should be sent to the host.
NumBytes Number of bytes to write.
Table 10.14: USB_HID_WriteEPOverlapped() / USB_HID_WriteEPOverlappedEx() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
329
10.5.2.13 USB_HID_WriteTimed() / USB_HID_WriteExTimed()
Description
Write data to the host with a given timeout. This function blocks until the timeout has
been reached, it has written NumBytes or until the device is disconnected from the
host.
Prototype
void USB_HID_WriteTimed (const void* pData, unsigned NumBytes, unsigned ms);
void USB_HID_WriteExTimed (USB_HID_HANDLE hInterface,
const void* pData,
unsigned NumBytes,
unsigned ms);
Parameter Description
hInterface Handle to a HID instance.
pData Pointer to data that should be sent to the host.
NumBytes Number of bytes to write.
ms Timeout in milliseconds.
Table 10.15: USB_HID_WriteTimed() / USB_HID_WriteExTimed() parameter list
330 CHAPTER 10 Human Interface De vice Class (HID)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
10.5.3 Data structures
10.5.3.1 USB_HID_INIT_DATA
Description
Initialization structure that is needed when adding a CDC interface to emUSB.
Prototype
typedef struct {
U8 EPIn;
U8 EPOut;
const U8 * pReport;
U16 NumBytesReport;
} USB_HID_INIT_DATA;
Additional Information
This structure is used when the HID interface is added to emUSB. EPOut is not
required.
pReport points to a report descriptor. A report descriptor is a structure which is used
to transmit HID control data to and from a human interface device. A report descrip-
tor defines the format of a report and is composed of report items that define one or
more top-level collections. Each collection defines one or more HID reports.
Refer to Universal Serial Bus Specification, 1.0 Version and the latest version of the
HID Usage Tables guide for detailed information about HID input, output and feature
reports.
The USB Implementers Forum provide an application that helps to build and modify
HID report descriptors. The HID Descriptor Tool can be downloaded from:
http://www.usb.org/developers/hidpage/.
The report descriptor used in the supplied example application HID_Echo1.c should
match to the requirements of most “vendor specific HID” applications. The report size
is defined to 64 bytes. As mentioned before, interrupt endpoints are limited to at
most one packet of at most 64 bytes per frame (on full speed devices).
Example
Example excerpt from HID_Mouse.c:
static void _AddHID(void) {
USB_HID_INIT_DATA InitData;
U8 Interval = 10;
static U8 acBuffer[64];
memset(&InitData, 0, sizeof(InitData));
InitData.EPIn = USB_AddEP(USB_DIR_IN, USB_TRANSFER_TYPE_INT, Interval, NULL, 0);
// Note: Next line is optional. EPOut is not required!
InitData.EPOut = USB_AddEP(USB_DIR_OUT, USB_TRANSFER_TYPE_INT, Interval, /
&acBuffer[0], sizeof(acBuffer));
InitData.pReport = _aHIDReport;
InitData.NumBytesReport = sizeof(_aHIDReport);
USB_HID_Add(&InitData);
}
Member Description
EPIn Endpoint for sending data to the host.
EPOut Endpoint for receiving data from the host.
pReport Pointer to a report descriptor.
NumBytesReport Size of the HID report.
Table 10.16: USB_HID_INIT_DATA elements
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
331
10.6 Host API
This chapter describes the functions that can be used with the Windows host system.
This functions are only required if the emUSB-HID component is used to design a
vendor specific HID.
General information
To communicate with the target USB-HID stack, the example application project
includes a USB-HID specific source and header file (USBHID.c, USBHID.h). These files
contain API functions to communicate with the USB-HID target through the USB-Bulk
driver.
Purpose of the USB Host API functions
To have an easy start-up when writing an application on the host side, these API
functions have simple interfaces and handle all operations that need to be done to
communicate with the target USB-HID stack.
332 CHAPTER 10 Human Interface De vice Class (HID)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
10.6.1 Host API function list
Function Description
API functions
USBHID_Close() Closes the connection an open device.
USBHID_Open() Opens a handle to the device.
USBHID_Init() Initializes the USB human interface
device.
USBHID_Exit() Closes the connection an open device.
USBHID_GetNumAvailableDevices() Returns the number of available devices.
USBHID_GetProductName() Returns the product name.
USBHID_GetInputReportSize() Returns the input report size of the
device.
USBHID_GetOutputReportSize() Returns the output report size of the
device.
USBHID_GetProductId() Returns the product Id of the device.
USBHID_GetVendorId() Returns the vendor id of the device.
USBHID_RefreshList() Refreshes connection info list.
USBHID_SetVendorPage() Sets the vendor page.
Table 10.17: USB-HID host interface function list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
333
10.6.2 USB-HID functions
10.6.2.1 USBHID_Close()
Description
Closes the connection an open device.
Prototype
void USBHID_Close (unsigned Id);
Parameter Description
DeviceIndex Index of the HID device. This is the bit number of the mask
returned by USBHID_GetNumDevices()
Table 10.18: USBHID_Close() parameter list
334 CHAPTER 10 Human Interface De vice Class (HID)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
10.6.2.2 USBHID_Open()
Description
Opens a handle to the device that shall be opened.
Prototype
int USBHID_Open (unsigned Id)
Return value
== 0: Opening was successful or already opened.
== 1: Error. Handle to the device could not opened.
Parameter Description
DeviceIndex Index of the HID device. This is the bit number of the mask
returned by USBHID_GetNumDevices().
Table 10.19: USBHID_Open() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
335
10.6.2.3 USBHID_Init()
Description
Sets the specific vendor page, initialize the USB HID User API and retrieve the infor-
mation of the HID device.
Prototype
void USBHID_Init(U8 VendorPage);
Parameter Description
VendorPage This parameter specifies the lower 8 bits of the vendor specific
usage page number. It must be identical on both device and host.
Table 10.20: USBHID_Init() parameter list
336 CHAPTER 10 Human Interface De vice Class (HID)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
10.6.2.4 USBHID_Exit()
Description
Closes the connection to all opened devices and deinitializes the HID module.
Prototype
void USBHID_Exit(void);
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
337
10.6.2.5 USBHID_GetNumAvailableDevices()
Description
Returns the number of the available devices.
Prototype
unsigned USBHID_GetNumAvailableDevices(U32 * pMask);
Return value
Returns the number of available devices.
Additional information
pMask will be filled by this routine. It shall be interpreted as bit mask where a bit set
means this device is available. For example, Device 0 and device 2 are available, if
pMask has the value 0x00000005.
Parameter Description
pMask Pointer to unsigned integer value which is used to store the bit
mask of available devices. This parameter may be NULL.
Table 10.21: USBHID_GetNumAvailableDevices() parameter list
338 CHAPTER 10 Human Interface De vice Class (HID)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
10.6.2.6 USBHID_GetProductName()
Description
Stores the name of the device into pBuffer.
Prototype
int USBHID_GetProductName(unsigned Id, char * pBuffer, unsigned NumBytes);
Return value
== 0: An error occured.
== 1: On success.
Parameter Description
DeviceIndex Index of the HID device. This is the bit number of the mask
returned by USBHID_GetNumDevices().
pBuffer Pointer to a buffer for the product name.
NumBytes Size of the pBuffer in bytes.
Table 10.22: USBHID_GetProductName() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
339
10.6.2.7 USBHID_GetInputReportSize()
Description
Returns the input report size of the device.
Prototype
int USBHID_GetInputReportSize(unsigned Id);
Return value
== 0: An error occured.
!= 0: Size of the report in bytes.
Parameter Description
DeviceIndex Index of the HID device. This is the bit number of the mask
returned by USBHID_GetNumDevices().
Table 10.23: USBHID_GetInputReportSize() parameter list
340 CHAPTER 10 Human Interface De vice Class (HID)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
10.6.2.8 USBHID_GetOutputReportSize()
Description
Returns the output report size of the device.
Prototype
int USBHID_GetOutputReportSize(unsigned Id);
Return value
== 0: An error occured.
!= 0: Size of the report in bytes.
Parameter Description
DeviceIndex Index of the HID device. This is the bit number of the mask
returned by USBHID_GetNumDevices().
Table 10.24: USBHID_GetOutputReportSize() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
341
10.6.2.9 USBHID_GetProductId()
Description
Returns the product Id of the device.
Prototype
U16 USBHID_GetProductId(unsigned Id);
Return value
== 0: An error occured.
!= 0: Product Id.
Parameter Description
DeviceIndex Index of the HID device. This is the bit number of the mask
returned by USBHID_GetNumDevices().
Table 10.25: USBHID_GetProductId() parameter list
342 CHAPTER 10 Human Interface De vice Class (HID)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
10.6.2.10USBHID_GetVendorId()
Description
Returns the vendor Id of the device.
Prototype
U16 USBHID_GetVendorId(unsigned Id);
Return value
== 0: An error occured.
!= 0: Vendor Id.
Parameter Description
DeviceIndex Index of the HID device. This is the bit number of the mask
returned by USBHID_GetNumDevices().
Table 10.26: USBHID_GetVendorId() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
343
10.6.2.11USBHID_RefreshList()
Description
Refreshes the connection list.
Prototype
void USBHID_RefreshList(void);
Additional information
Note that any open handle to the device will be closed while refreshing the connec-
tion list.
344 CHAPTER 10 Human Interface De vice Class (HID)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
10.6.2.12USBHID_SetVendorPage()
Description
Sets the vendor page so that all HID device with the specified page will be found.
Prototype
void USBHID_SetVendorPage(U8 VendorPage);
Parameter Description
VendorPage This parameter specifies the lower 8 bits of the vendor specific
usage page number. It must be identical on both device and host.
Table 10.27: USBHID_SetVendorPage() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
345
Chapter 11
Printer Class
This chapter describes how to get emUSB up and running as a printer device.
346 CHAPTER 11 Printer Class
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
11.1 Overview
The Printer Class is an abstract USB class protocol defined by the USB Implementers
Forum. This protocol delivers the existing printing command-sets to a printer over
USB.
11.1.1 Configuration
The configuration section will later on be modified to match the real application. For
the purpose of getting emUSB up and running as well as doing an initial test, the
configuration as delivered should not be modified.
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
347
11.2 The example application
The start application (in the Application subfolder) is a simple data sink, which can
be used to test emUSB. The application receives data bytes from the host which it
displays in the terminal I/O window of the debugger.
Source code of USB_Printer.c:
/*********************************************************************
* SEGGER MICROCONTROLLER GmbH & Co. KG *
* Solutions for real time microcontroller applications *
**********************************************************************
* *
* (c) 2003-2011 SEGGER Microcontroller GmbH & Co KG *
* *
* Internet: www.segger.com Support: support@segger.com *
* *
**********************************************************************
* *
* USB device stack for embedded applications *
* *
**********************************************************************
----------------------------------------------------------------------
File : USB_Printer.c
Purpose : Sample implementation of USB printer device class
----------Literature--------------------------------------------------
Universal Serial Bus Device Class Definition for Printing Devices
Version 1.1 January 2000
-------- END-OF-HEADER ---------------------------------------------
*/
#include <stdio.h>
#include <string.h>
#include "USB_PrinterClass.h"
#include "BSP.h"
/*********************************************************************
*
* static data
*
**********************************************************************
*/
static U8 _acData[512];
/*********************************************************************
*
* static code
*
**********************************************************************
*/
/*********************************************************************
*
* _GetDeviceIdString
*
*/
static const char * _GetDeviceIdString(void) {
const char * s = "CLASS:PRINTER;MODEL:HP LaserJet 6MP;"
"MANUFACTURER:Hewlett-Packard;"
"DESCRIPTION:Hewlett-Packard LaserJet 6MP Printer;"
"COMMAND SET:PJL,MLC,PCLXL,PCL,POSTSCRIPT;";
return s;
}
/*********************************************************************
*
* _GetHasNoError
*
*/
static U8 _GetHasNoError(void) {
return 1;
}
/*********************************************************************
*
* _GetIsSelected
*
*/
static U8 _GetIsSelected(void) {
return 1;
348 CHAPTER 11 Printer Class
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
}
/*********************************************************************
*
* _GetIsPaperEmpty
*
*/
static U8 _GetIsPaperEmpty(void) {
return 0;
}
/*********************************************************************
*
* _OnDataReceived
*
*/
static int _OnDataReceived(const U8 * pData, unsigned NumBytes) {
USB_MEMCPY(_acData, pData, NumBytes);
_acData[NumBytes] = 0;
printf(_acData);
return 0;
}
/*********************************************************************
*
* _OnReset
*
*/
static void _OnReset(void) {
}
static USB_PRINTER_API _PrinterAPI = {
_GetDeviceIdString,
_OnDataReceived,
_GetHasNoError,
_GetIsSelected,
_GetIsPaperEmpty,
_OnReset
};
/*********************************************************************
*
* Public code
*
**********************************************************************
*/
/*********************************************************************
*
* USB_GetVendorId
*
* Function description
* Returns vendor Id
*/
U16 USB_GetVendorId(void) {
return 0x8765;
}
/*********************************************************************
*
* USB_GetProductId
*
* Function description
* Returns product Id
*/
U16 USB_GetProductId(void) {
return 0x2114; // Should be unique for this sample
}
/*********************************************************************
*
* USB_GetVendorName
*
* Function description
* Returns vendor name
*/
const char * USB_GetVendorName(void) {
return "Vendor";
}
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
349
/*********************************************************************
*
* USB_GetProductName
*
* Function description
* Returns product name
*/
const char * USB_GetProductName(void) {
return "Printer";
}
/*********************************************************************
*
* USB_GetSerialNumber
*
* Function description
* Returns serial number
*/
const char * USB_GetSerialNumber(void) {
return "12345678901234567890";
}
/*********************************************************************
*
* MainTask
*
* Function description
* USB handling task.
* Modify to implement the desired protocol
*/
void MainTask(void);
void MainTask(void) {
USB_Init();
USB_PRINTER_Init(&_PrinterAPI);
USB_Start();
//
// Loop: Receive data byte by byte, send back (data + 1)
//
while (1) {
//
// Wait for configuration
//
while ((USB_GetState() & (USB_STAT_CONFIGURED | USB_STAT_SUSPENDED))
!= USB_STAT_CONFIGURED) {
BSP_ToggleLED(0);
USB_OS_Delay(50);
}
USB_PRINTER_Task();
}
}
/**************************** end of file ***************************/
350 CHAPTER 11 Printer Class
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
11.3 Target API
This chapter describes the functions and data structures that can be used with the
target application.
11.3.1 Interface function list
Function Description
API functions
USB_PRINTER_Init() Initializes the printer class.
USB_PRINTER_Task() Processes the request from USB Host.
Data structures
USB_PRINTER_API
List of callback functions the library
should invoke when processing a request
from the USB Host.
Table 11.1: USB-Printer interface API
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
351
11.3.2 API functions
11.3.2.1 USB_PRINTER_Init()
Description
Initializes the printer class.
Prototype
void USB_PRINTER_Init(USB_PRINTER_API * pAPI);
Additional information
After the initialization of general emUSB, this is the first function that needs to be
called when the printer class is used with emUSB.
Parameter Description
pAPI Pointer to an API table that contains all callback functions that are
necessary for handling the functionality of a printer.
Table 11.2: USB_PRINTER_Init() parameter list
352 CHAPTER 11 Printer Class
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
11.3.2.2 USB_PRINTER_Task()
Description
Processes the request received from the USB Host.
Prototype
void USB_PRINTER_Task(void);
Additional information
This function blocks as long as the USB device is connected to USB host. It handles
the requests by calling the function registered in the call to USB_PRINTER_Init().
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
353
11.3.3 Data structures
11.3.3.1 USB_PRINTER_API
Description
Initialization structure that is needed when adding an printer interface to emUSB. It
holds pointer to callback functions the interface invokes when it processes request
from USB host.
Prototype
typedef struct {
const char * (*pfGetDeviceIdString)(void);
int (*pfOnDataReceived)(const U8 * pData, unsigned NumBytes);
U8 (*pfGetHasNoError)(void);
U8 (*pfGetIsSelected)(void);
U8 (*pfGetIsPaperEmpty)(void);
void (*pfOnReset)(void);
} USB_PRINTER_API;
Member Description
pfGetDeviceIdString
The library calls this function when the USB host
requests the printer’s identification string.
This string shall confirm to the IEEE 1284 Device ID
Syntax:
Example:
"CLASS:PRINTER;MODEL:HP LaserJet 6MP;MANUFAC-
TURER:Hewlett-Packard;DESCRIPTION:Hewlett-Pack-
ard LaserJet 6MP Printer;COMMAND
SET:PJL,MLC,PCLXL,PCL,POSTSCRIPT;"
pfOnDataReceived This function is called when data arrives from USB
host.
pfGetHasNoError This function should return a non-zero value if the
printer has no error.
pfGetIsSelected This function should return a non-zero value if the
printer is selected.
pfGetIsPaperEmpty This function should return a non-zero value if the
printer is out of paper.
pfOnReset The library calls this function if the USB host sends
a soft reset command.
Table 11.3: USB_PRINTER_API elements
354 CHAPTER 11 Printer Class
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
355
Chapter 12
Remote NDIS (RNDIS)
This chapter gives a general overview of the Remote Network Driver Interface Speci-
fication class and describes how to get the RNDIS component running on the target.
356 CHAPTER 12 Remote NDIS (RNDIS)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
12.1 Overview
The Remote Network Driver Interface Specification (RNDIS) is a Microsoft proprietary
USB class protocol which can be used to create a virtual Ethernet connection between
a USB device and a host PC. A TCP/IP stack like embOS/IP is required on the USB
device side to handle the actual IP communication. Any available IP protocol (UDP,
TPC, FTP, HTTP, etc.) can be used to exchange data. On a typical Cortex-M CPU run-
ning at 120MHz a transfer speed of about 5 MByte/sec can be achieved when using a
high-speed USB connection.
USB RNDIS is supported by all Windows operating systems starting with Windows XP,
as well as by Linux with kernel versions newer than 2.6.34. An .inf file is required for
the installation on Microsoft Windows systems older than Windows 7. The emUSB-
RNDIS package includes .inf files for Windows versions older than Windows 7. OS X
will require a third-party driver to work with RNDIS, which can be downloaded from
here: http://joshuawise.com/horndis
emUSB-RNDIS contains the following components:
Generic USB handling
RNDIS device class implementation
Network interface driver which uses embOS/IP as TCP/IP stack.
A sample application demonstrating how to work with RNDIS.
12.1.1 Working with RNDIS
Any USB RNDIS device connected to a PC running the Windows operating system is
listed as a separate network interface in the "Network Connections" window as shown
in this screenshot:
The ping command line utility can be used to test the connection to target as shown
below. If the connection is correctly established the number of the lost packets
should be 0.
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
357
12.1.2 Additional information
More technical details about RNDIS can be found here:
http://msdn.microsoft.com/en-us/library/windows/hardware/
ff570660%28v=vs.85%29.aspx
358 CHAPTER 12 Remote NDIS (RNDIS)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
12.2 Configuration
12.2.1 Initial configuration
To get emUSB-RNDIS up and running as well as doing an initial test, the configura-
tion as it is delivered should not be modified.
12.2.2 Final configuration
The configuration must only be modified, when emUSB should be used in your final
product. Refer to section Configuration on page 44 to get detailed information about
the general emUSB-Device configuration functions which have to be adapted.
12.2.3 Class specific configuration
emUSB-RNDIS calls the functions below to get the information required at initializa-
tion. The functions should be implemented in the application. A sample implementa-
tion of these functions can be found in the IP_Config_RNDIS.c. The file is located in
the Sample\RNDIS directory of the emUSB shipment. The IP_Config_RNDIS.c pro-
vides a ready to use layer and configuration file to be used with embOS
and embOS/IP..
Function Description
emUSB-RNDIS configuration functions
USB_RNDIS_GetVendorId() Returns IEEE-registered vendor code.
USB_RNDIS_GetDescription() Returns the device description.
USB_RNDIS_GetDriverVersion() Returns the firmware version.
Table 12.1: List of class specific configuration functions
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
359
12.2.3.1 USB_RNDIS_GetVendorId()
Description
Returns the IEEE-registered vendor code.
Prototype
U32 USB_RNDIS_GetVendorId(void);
Example
U32 USB_RNDIS_GetVendorId(void) {
return 0x0022C7;
}
Additional information
The function is called when the RDNIS device is initialized. It returns a 24-bit Organi-
zationally Unique Identifier (OUI) of the vendor. This is the same value as the one
stored in the first 3 bytes of a HW (MAC) address. Only the least significant 24 bits of
the retuned value are used.
360 CHAPTER 12 Remote NDIS (RNDIS)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
12.2.3.2 USB_RNDIS_GetDescription()
Description
Returns the device description.
Prototype
const char * USB_RNDIS_GetDescription(void);
Example
const char * USB_RNDIS_GetDescription(void) {
return "SEGGER RNDIS device";
}
Additional information
Called when the RNDIS device is initialized. Returns a 0-terminated ASCII string
describing the device. The string is then sent to the host system.
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
361
12.2.3.3 USB_RNDIS_GetDriverVersion()
Description
Returns the firmware version.
Prototype
U16 USB_RNDIS_GetDriverVersion(void);
Example
U16 USB_RNDIS_GetDriverVersion(void) {
return 0x0100;
}
Additional information
Called when the RNDIS device is initialized. Returns a 16-bit value representing the
firmware version. The high-order byte specifies the major version and the low-order
byte the minor version.
362 CHAPTER 12 Remote NDIS (RNDIS)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
12.2.4 Compile time configuration
The following macros can be added to USB_Conf.h file in order to configure the
behavior of the RNDIS component.
The following types of configuration macros exist:
Binary switches “B”
Switches can have a value of either 0 or 1, for deactivated and activated respectively.
Actually, anything other than 0 works, but 1 makes it easier to read a configuration
file. These switches can enable or disable a certain functionality or behavior.
Switches are the simplest form of configuration macros.
Numerical values “N”
Numerical values are used somewhere in the code in place of a numerical constant.
Type Macro Default Description
N RNDIS_DEBUG_LEVEL 0
Sets the type of diagnostic messages
output at runtime. It can take one of
these values:
0 - no debug messages
1 - only error messages
2 - error and log messages
Table 12.2: RNDIS configuration macros
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
363
12.3 Running the sample application
The sample application can be found in the Sample\RNDIS\IP_Config_RNDIS.c file of
the emUSB shipment. In order to use the sample application the SEGGER embOS/IP
middleware component is required. To test the emUSB-RNDIS component any of the
embOS/IP sample applications can be used in combination with IP_Config_RNDIS.c.
After the sample application is started the USB cable should be connected to the PC
and the choosen embOS/IP sample can be tested using the appropriate methods.
12.3.0.1 IP_Config_RNDIS.c in detail
The main part of the sample application is implemented in the function MainTask()
which runs as an independent task.
// _Connect() - excerpt from IP_Config_RNDIS.c
static int _Connect(unsigned IFaceId) {
U32 Server = IP_BYTES2ADDR(10, 0, 0, 10);
IP_DHCPS_ConfigPool(IFaceId, IP_BYTES2ADDR(10, 0, 0, 11), 0xFF000000, 20);
IP_DHCPS_ConfigDNSAddr(IFaceId, &Server, 1);
IP_DHCPS_Init(IFaceId);
IP_DHCPS_Start(IFaceId);
USB_Init();
_AddRNDIS();
OS_CREATETASK(&_RNDISTCB,"USB RNDISTask",
_RndisTask, TASK_PRIO_RNDIS_TASK, _aRNDISStack);
USB_Start();
return 0; // Successfully connected.
}
The first step is to initialize the DHCP server component which assigns the IP address
for the PC side. The target is configured with the IP address 10.0.0.10. The DHCP
server is configured to distribute IP addresses starting from 10.0.0.11, therefore the
PC will receive the IP address 10.0.0.11. Then the USB stack is initialized and the
RNDIS interface is added to it. The function _AddRNDIS() configures all required end-
points and configures the HW address of the PC network interface.
// _AddRNDIS() - excerpt from IP_Config_RNDIS.c
static void _AddRNDIS(void) { USB_RNDIS_INIT_DATA InitData;
InitData.EPOut = USB_AddEP(USB_DIR_OUT,
USB_TRANSFER_TYPE_BULK,
0,
_abReceiveBuffer,
USB_MAX_PACKET_SIZE);
InitData.EPIn = USB_AddEP(USB_DIR_IN, USB_TRANSFER_TYPE_BULK, 0, NULL, 0);
InitData.EPInt = USB_AddEP(USB_DIR_IN, USB_TRANSFER_TYPE_INT, 5, NULL, 0);
InitData.pEventAPI = &_EventAPI;
InitData.pDriverAPI = &USB_RNDIS_Driver_IP_NI;
InitData.DriverData.pHWAddr = "\x00\x22\xC7\xFF\xFF\xF3";
InitData.DriverData.NumBytesHWAddr = 6;
USB_RNDIS_Add(&InitData);
}
The size of _acReceiveBuffer buffer must be a multiple of USB max packet size. The
USB_MAX_PACKET_SIZE define is set to the correct max packet size value for the cor-
responding speed (full or high) and is used in the samples to declare buffer sizes.
_EventAPI is a table with functions which manipulate OS events. The events are used
by the RNDIS component to synchronize with the USB interrupt.
USB_RNDIS_Driver_IP_NI is the network interface driver which implements the con-
nection to the IP stack. The HW address configured here is assigned to the PC net-
work interface. The HW address of the IP stack is configured in the IP_X_Config()
function of embOS/IP as described below.
364 CHAPTER 12 Remote NDIS (RNDIS)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
// Excerpt from IP_Config.c
static OS_EVENT _Event;
static void * _cbCreateEvent(void) {
OS_EVENT_Create(&_Event);
return &_Event;
}
static void _cbSignalEvent(void * pEvent) {
OS_EVENT_Pulse((OS_EVENT * )pEvent);
}
static int _cbWaitEventTimed(void * pEvent, unsigned ms) {
return OS_EVENT_WaitTimed((OS_EVENT *)pEvent, ms);
}
static USB_RNDIS_EVENT_API _EventAPI = {
_cbCreateEvent,
_cbSignalEvent,
_cbWaitEventTimed
};
The IP stack is configured to use the network interface driver of emUSB-RNDIS. For
more information about the configuration of the IP stack refer to embOS/IP manual.
// IP_X_Config() - excerpt from IP_Config.c
#include "USB_RNDIS_Driver_IP_NI.h"
void IP_X_Config(void) {
<...>
//
// Add and configure the RNDIS driver.
// The local IP address is 10.0.0.10/8.
//
IP_AddEtherInterface(&USB_RNDIS_IP_Driver);
IP_SetHWAddr("\x00\x22\xC7\xFF\xFF\xFF");
IP_SetAddrMask(0x0A00000A, 0xFF000000);
IP_SetIFaceConnectHook(IFaceId, _Connect);
IP_SetIFaceDisconnectHook(IFaceId, _Disconnect);
<...>
}
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
365
12.4 RNDIS + embOS/IP as a "USB Webserver"
This method of using RNDIS provides a unique customer experience where a USB
device can provide a custom web page or any other service through which a cus-
tomer can interact with the device.
Initially the PC recognizes a RNDIS device. In case of Windows XP and Vista a driver
will be necessary, Windows 7 and above as well as Linux recognize RNDIS automati-
cally. RNDIS from the viewpoint of the PC is a normal Network Interface Controller
(NIC) and the PC handles it as such. The default behavior is to request an IP address
from a DHCP server. The PC retrieves an IP address from the DHCP-Server in the
device. In our standard sample code the device has the local IP 10.0.0.10 and the PC
will get 10.0.0.11 from the DHCP server. With this the configuration is complete and
the user can access the web-interface located on the USB device via 10.0.0.10. To
improve the ease-of-use NetBIOS can be used to give the device an easily readable
name.
366 CHAPTER 12 Remote NDIS (RNDIS)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
12.5 Target API
Function Description
API functions
USB_RNDIS_Add() Adds a RNDIS-class interface to the USB stack.
USB_RNDIS_Task() Handles the RNDIS protocol.
Data structures
USB_RNDIS_INIT_DATA Initialization data for RNDIS interface.
USB_RNDIS_EVENT_API API functions for OS event handling.
USB_RNDIS_DRIVER_API Network interface driver API functions.
USB_RNDIS_DRIVER_DATA Configuration data for the network interface driver.
Table 12.3: List of emUSB RNDIS module functions and data structures
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
367
12.5.1 API functions
12.5.1.1 USB_RNDIS_Add()
Description
Adds an RNDIS-class interface to the USB stack.
Prototype
void USB_RNDIS_Add(const USB_RNDIS_INIT_DATA * pInitData);
Additional information
This function should be called after the initialization of the USB core to add an RNDIS
interface to emUSB. The initialization data is passed to the function in the structure
pointed to by pInitData. Refer to USB_RNDIS_INIT_DATA on page 369 for more
information.
Parameter Description
pInitData IN: Pointer to a USB_RNDIS_INIT_DATA structure.
OUT: ---
Table 12.4: USB_RNDIS_Add() parameter list
368 CHAPTER 12 Remote NDIS (RNDIS)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
12.5.1.2 USB_RNDIS_Task()
Description
Handles the RNDIS protocol.
Prototype
void USB_RNDIS_Task(void);
Additional information
The function should be called periodically after the USB device has been successfully
enumerated and configured. The function returns when the USB device is detached or
suspended. For a sample usage refer to IP_Config_RNDIS.c in detail on page 363.
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
369
12.5.2 Data structures
12.5.2.1 USB_RNDIS_INIT_DATA
Description
Initialization data for RNDIS interface.
Prototype
typedef struct USB_RNDIS_INIT_DATA {
U8 EPIn;
U8 EPOut;
U8 EPInt;
const USB_RNDIS_EVENT_API * pEventAPI;
const USB_RNDIS_DRIVER_API * pDriverAPI;
USB_RNDIS_DRIVER_DATA DriverData;
} USB_RNDIS_INIT_DATA;
Additional information
This structure holds the endpoints that should be used by the RNDIS interface (EPin,
EPOut and EPInt). Refer to USB_AddEP() on page 61 for more information about how
to add an endpoint.
Member Description
EPIn Endpoint for sending data to the host.
EPOut Endpoint for receiving data from the host.
EPInt Endpoint for sending status information.
pEventAPI Pointer to the API for OS event handling.
(See USB_RNDIS_EVENT_API on page 370)
pDriverAPI Pointer to the Network interface driver API.
(See USB_RNDIS_DRIVER_API on page 371)
DriverData Configuration data for the network interface driver.
(See USB_RNDIS_DRIVER_DATA on page 377)
Table 12.5: USB_RNDIS_INIT_DATA elements
370 CHAPTER 12 Remote NDIS (RNDIS)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
12.5.2.2 USB_RNDIS_EVENT_API
Description
API for OS event handling.
Prototype
typedef struct USB_RNDIS_EVENT_API {
void * (*pfCreate) (void);
void (*pfSignal) (void * pEvent);
int (*pfWaitTimed) (void * pEvent, unsigned Timeout);
} USB_RNDIS_EVENT_API;
Additional information
The functions of this API are used by the emUSB-RNDIS component to wait efficiently
in USB_RNDIS_Task() for events generated in the USB interrupt. For a detailed
description of the API functions refer to USB_RNDIS_EVENT_API in detail on
page 378.
Member Description
(*pfCreate)() Creates an OS event.
(*pfSignal)() Signals an OS event.
(*pfWaitTimed)() Wait for an OS event to be signaled.
Table 12.6: USB_RNDIS_EVENT_API elements
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
371
12.5.2.3 USB_RNDIS_DRIVER_API
Description
This structure contains the callback functions for the network interface driver.
Prototype
typedef struct USB_RNDIS_DRIVER_API {
void (*pfInit) (const USB_RNDIS_DRIVER_DATA * pDriverData);
void * (*pfGetPacketBuffer) (unsigned NumBytes);
void (*pfWritePacket) (const void * pData, unsigned NumBytes);
void (*pfSetPacketFilter) (U32 Mask);
int (*pfGetLinkStatus) (void);
U32 (*pfGetLinkSpeed) (void);
void (*pfGetHWAddr) (U8 * pAddr, unsigned NumBytes);
U32 (*pfGetStats) (int Type);
U32 (*pfGetMTU) (void);
void (*pfReset) (void);
} USB_RNDIS_DRIVER_API;
Additional information
The emUSB-RNDIS component calls the functions of this API to exchange data and
status information with the IP stack running on the target.
Member Description
(*pfInit)() Initializes the driver.
(*pfGetPacketBuffer)() Returns a buffer for a data packet.
(*pfWritePacket)() Delivers a data packet to target IP stack.
(*pfSetPacketFilter)() Configures the type of accepted data packets.
(*pfGetLinkStatus)() Returns the status of the connection to target IP stack.
(*pfGetLinkSpeed)() Returns the connection speed.
(*pfGetHWAddr)() Returns the HW address of the PC.
(*pfGetStats)() Returns statistical counters.
(*pfGetMTU)() Returns the size of the largest data packet which can
be transferred.
(*pfReset)() Resets the driver.
Table 12.7: USB_RNDIS_DRIVER_API elements
372 CHAPTER 12 Remote NDIS (RNDIS)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
(*pfInit)()
Description
Initializes the driver.
Prototype
void (*pfInit)(const USB_RNDIS_DRIVER_DATA * pDriverData);
Additional information
This function is called when the RNDIS interface is added to USB stack. Typically the
function makes a local copy of the HW address passed in the pDriverData structure.
For more information this structure refer to USB_RNDIS_DRIVER_DATA on page 377.
(*pfGetPacketBuffer)()
Description
Returns a buffer for a data packet.
Prototype
void * (*pfGetPacketBuffer)(unsigned NumBytes);
Return value
!=NULL Pointer to allocated buffer
==NULL No buffer available
Additional information
The function should allocate a buffer of the requested size. If the buffer can not be
allocated a NULL pointer should be returned. The function is called when a data
packet is received from PC. The packet data is stored in the returned buffer.
(*pfWritePacket)()
Description
Delivers a data packet to target IP stack
Prototype
void (*pfWritePacket)(const void * pData, unsigned NumBytes);
Additional information
The function is called after a data packet has been received from USB. pData points
to the buffer returned by the (*pfGetPacketBuffer)() function.
Parameter Description
pDriverData IN: Pointer to driver configuration data.
OUT: ---
Table 12.8: (*pfInit)() parameter list
Parameter Description
NumBytes Size of the requested buffer in bytes.
Table 12.9: (*pfGetPacketBuffer)() parameter list
Parameter Description
pData IN: Data of the received packet.
OUT: ---
NumBytes Number of bytes stored in the buffer.
Table 12.10: (*pfWriteBuffer)() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
373
(*pfSetPacketFilter)()
Description
Configures the type of accepted data packets
Prototype
void (*pfSetPacketFilter)(U32 Mask);
Additional information
The Mask parameter should be interpreted as a boolean value. A value different than
0 indicates that the connection to target IP stack should be established. When the
function is called with the Mask parameter set to 0 the connection to target IP stack
should be interrupted.
(*pfGetLinkStatus)()
Description
Returns the status of the connection to target IP stack.
Prototype
int (*pfGetLinkStatus)(void);
Return value
==USB_RNDIS_LINK_STATUS_CONNECTED Connected to target IP stack
==USB_RNDIS_LINK_STATUS_DISCONNECTED Not connected to target IP stack
(*pfGetLinkSpeed)()
Description
Returns the connection speed.
Prototype
U32 (*pfGetLinkSpeed)(void);
Return value
The connection speed in units of 100 bits/sec or 0 if not connected.
Parameter Description
Mask Type of accepted data packets
Table 12.11: (*pfSetPacketFilter)() parameter list
374 CHAPTER 12 Remote NDIS (RNDIS)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
(*pfGetHWAddr)()
Description
Returns the HW address of PC
Prototype
void (*pfGetHWAddr)(U8 * pAddr, unsigned NumBytes);
Additional information
The returned HW address is the one passed to the driver in the call to (*pfInit)().
Typically the HW address is 6 bytes large.
Parameter Description
pAddr IN: ---
OUT: The HW address
NumBytes Maximum number of bytes to store to pAddr
Table 12.12: (*pfGetHWAddr)() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
375
(*pfGetStats)()
Description
Returns statistical counters.
Prototype
U32 (*pfGetStats)(int Type);
Return value
Value of requested statistical counter.
Additional information
The counters should be set to 0 when the (*pfReset)() function is called.
Parameter Description
Type The type of information requested. Can be one of these defines:
Table 12.13: (*pfGetStats)() parameter list
Permitted values for parameter Type
USB_RNDIS_STATS_WRITE_PACKET_OK
Number of packets sent
without errors to target
IP stack
USB_RNDIS_STATS_WRITE_PACKET_ERROR
Number of packets sent
with errors to target IP
stack
USB_RNDIS_STATS_READ_PACKET_OK
Number of packets
received without errors
from target IP stack
USB_RNDIS_STATS_READ_PACKET_ERROR
Number of packets
received with errors
from target IP stack
USB_RNDIS_STATS_READ_NO_BUFFER
Number of packets
received from target IP
stack but dropped.
USB_RNDIS_STATS_READ_ALIGN_ERROR
Number of packets
received from target IP
stack with alignment
errors.
USB_RNDIS_STATS_WRITE_ONE_COLLISION
Number of packets
which were not sent to
target IP stack due to
the occurrence of one
collision.
USB_RNDIS_STATS_WRITE_MORE_COLLISIONS
Number of packets
which were not sent to
target IP stack due to
the occurrence of one or
more collisions.
376 CHAPTER 12 Remote NDIS (RNDIS)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
(*pfGetMTU)()
Description
Returns the size of the largest data packet which can be transferred.
Prototype
U32 (*pfGetMTU)(void);
Return value
The MTU size in bytes. Typically 1500 bytes.
(*pfReset)()
Description
Resets the driver.
Prototype
void (*pfReset)(void);
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
377
12.5.2.4 USB_RNDIS_DRIVER_DATA
Description
Configuration data passed to network interface driver at initialization.
Prototype
typedef struct USB_RNDIS_DRIVER_DATA {
const U8 * pHWAddr;
unsigned NumBytesHWAddr;
} USB_RNDIS_DRIVER_DATA;
Member Description
pHWAddr HW address (or MAC address) of the host network interface.
NumBytesHWAddr Number of bytes in the HW address. Typically 6 bytes.
Table 12.14: USB_RNDIS_DRIVER_DATA elements
378 CHAPTER 12 Remote NDIS (RNDIS)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
12.5.2.5 USB_RNDIS_EVENT_API in detail
This section describes the functions of the API which are used to handle OS events.
Description
This structure contains function pointers which are required by the RNDIS module to
handle events, this can be used to map the functions to any RTOS.
Prototype
typedef struct USB_RNDIS_EVENT_API {
void * (*pfCreate) (void);
void (*pfSignal) (void * pEvent);
int (*pfWaitTimed) (void * pEvent, unsigned Timeout);
} USB_RNDIS_EVENT_API;
(*pfCreate)()
Description
Creates a new OS event.
Prototype
void * (*pfCreate)(void);
Return value
!=0 Event has been created, the return value is the pointer to the event.
==0 An error occurred
Example
For a sample implementation refer to IP_Config_RNDIS.c in detail on page 363.
(*pfSignal)()
Description
Indicates that the event occurred.
Prototype
void (*pfSignal)(void * pEvent);
Example
For a sample implementation refer to IP_Config_RNDIS.c in detail on page 363.
Member Description
(*pfCreate) Initializes the driver.
(*pfSignal) Returns a buffer for a data packet.
(*pfWaitTimed) Delivers a data packet to target IP stack.
Table 12.15: USB_RNDIS_EVENT_API elements
Parameter Description
pEvent IN: Pointer to the OS event to be signaled.
OUT: ---
Table 12.16: (*pfSignal)() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
379
(*pfWaitTimed)()
Description
Waits for the event to occur with a timeout.
Prototype
int (*pfWaitTimed)(void * pEvent, unsigned Timeout);
Return value
==0 Success, the event was signaled within the specified time.
!=0 The event was not signaled within the specified timeout.
Additional information
The function blocks the execution of the calling task until the event is signaled or the
timeout expired.
Example
For a sample implementation refer to IP_Config_RNDIS.c in detail on page 363.
Parameter Description
pEvent IN: Pointer to the OS event to wait for.
OUT: ---
Timeout Number of milliseconds to wait for the event to be signaled.
Table 12.17: (*pfWaitTimed)() parameter list
380 CHAPTER 12 Remote NDIS (RNDIS)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
381
Chapter 13
Combining different USB compo-
nents (Multi-Interface)
In some cases, it is necessary to combine different USB components in one device.
This chapter will describe how to do this and which steps are necessary.
382 CHAPTER 13 Combining different USB components (Multi-Inter-
face)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
13.1 Overview
The USB specification allows implementation of more than one component (function)
in a single device. This is achieved by combining two or more components. These
devices will be recognized by the USB host as composite device and each component
will be recognized as an independent device.
One device for example, a data logger can have two components:
This device can show log data files that were stored on a NAND flash through the
MSD component. The configuration of the data logger can be changed by using a
BULK component, CDC component or even HID component.
USB
HOST
USB
Device
Interface 0
MSD
Interface 1
HID
Endpoint OUT
Endpoint IN
Endpoint OUT
Endpoint IN
Control EP0
IN/OUT
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
383
13.1.1 Single interface device classes
Components can be combined because most USB device classes are based on one
interface. This means that those components describe themselves at the interface
descriptor level and thus makes it easy to combine different or even the same device
classes into one device. Such devices classes are MSD, HID and generic bulk.
Function 1
Function 0
Device descriptor
Interface descriptor 0:
BULK
Config descriptor
EPEP
Interface descriptor 1:
MSD
EPEP
384 CHAPTER 13 Combining different USB components (Multi-Inter-
face)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
13.1.2 Multiple interface device classes
In contrast to the single interfaces classes there are classes with multiple interfaces
such as CDC and AUDIO or VIDEO class. These classes define their class identifier in
the device descriptor. All interface descriptors are recognized as part of the compo-
nent that is defined in the device descriptor. This prevents the combination of multi-
ple interface device classes (for example, CDC) with any other component.
13.1.3 IAD class
To remove this limitation the USB organization defines a descriptor type that allows
the combination of single interface device classes with multiple interface device
classes. This descriptor is called an Interface Association Descriptor (IAD). It decou-
ples the multi-interface class from other interfaces.
Since IAD is an extension to the original USB specification, it is not supported by all
hosts, especially older host software. If IAD is not supported, the device may not be
enumerated correctly.
Supported HOST
At the time of writing, IAD is supported by:
Windows XP with Service pack 2
Windows 2003 with Service pack 1
Windows Vista and higher
Linux Kernel 2.6.22 and higher
Function 1
Function 0
Device descriptor:
IAD class
IA descriptor (IAD):
CDC
Interface
desc. 1:
Data
Interface
desc 0:
Control
Config descriptor
EP EPEP EPEP
Interface desc. 2:
MSD
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
385
13.2 Configuration
In general, no configuration is required. By default, emUSB supports up to four inter-
faces. If more interfaces are needed the following macro must be modified:
Type Macro Default Description
Numeric USB_MAX_NUM_IF 4Defines the maximum number of
interfaces emUSB shall handle.
Numeric USB_MAX_NUM_IAD 1
Defines the maximum number of
Interface Association Descriptors
emUSB shall handle.
386 CHAPTER 13 Combining different USB components (Multi-Inter-
face)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
13.3 How to combine
Combining different single interface emUSB components (Bulk, HID, MSD) is an easy
step, all that needs to be done is calling appropriate USB_xxx_Add() function. For
adding the CDC component additional steps needs to be done. For detailed informa-
tion, refer to emUSB component specific modification on page 388 and check the fol-
lowing sample.
Requirements
RTOS, every component requires a separate task.
Sufficient endpoints for all used device classes. Make sure that your USB device
controller has enough endpoints available to handle all the interfaces that shall
be integrated.
Sample application
The following sample application uses embOS as the RTOS. This listing is taken from
USB_CompositeDevice_MSD_CDC.c.
#include "RTOS.H"
#include "USB.h"
#include "USB_MSD.h"
#include "USB_CDC.h"
static OS_STACKPTR int Stack0[512]; /* Task stacks for MSD task */
static OS_STACKPTR int Stack1[512]; /* Task stacks for CDC task */
static OS_TASK TCB0; /* Task-control-block for MSD task*/
static OS_TASK TCB1; /* Task-control-block for CDC task*/
/*********************************************************************
*
* _CDCTask
*/
static void _CDCTask(void) {
while (1) {
char ac[64];
int NumBytesReceived;
//
// Wait for configuration
//
while ((USB_GetState() & (USB_STAT_CONFIGURED | USB_STAT_SUSPENDED))
!= USB_STAT_CONFIGURED) {
USB_OS_Delay(50* Task stacks for MSD task */
static OS_STACKPTR int Stack1[512]; /* Task stacks for);
}
NumBytesReceived = USB_CDC_Receive(&ac[0], sizeof(ac));
if (NumBytesReceived > 0) {
USB_CDC_Write(&ac[0], NumBytesReceived);
}
}
}
/*********************************************************************
*
* _MSDTask
*/
static void _MSDTask(void) {
while (1) {
while ((USB_GetState() & (USB_STAT_CONFIGURED | USB_STAT_SUSPENDED))
!= USB_STAT_CONFIGURED) {
USB_OS_Delay(50);
}
USB_MSD_Task();
}
}
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
387
/*********************************************************************
*
* _AddCDC
*/
static void _AddCDC(void) {
static U8 _abOutBuffer[USB_MAX_PACKET_SIZE];
USB_CDC_INIT_DATA InitData;
InitData.EPIn = USB_AddEP(USB_DIR_IN, USB_TRANSFER_TYPE_BULK, 0, NULL, 0);
InitData.EPOut = USB_AddEP(USB_DIR_OUT, USB_TRANSFER_TYPE_BULK, 0,
_abOutBuffer, USB_MAX_PACKET_SIZE);
InitData.EPInt = USB_AddEP(USB_DIR_IN, USB_TRANSFER_TYPE_INT, 8, NULL, 0);
USB_CDC_Add(&InitData);
}
/*********************************************************************
*
* _AddMSD
*/
static void _AddMSD(void) {
static U8 _abOutBuffer[USB_MAX_PACKET_SIZE];
USB_MSD_INIT_DATA InitData;
USB_MSD_INST_DATA InstData;
InitData.EPIn = USB_AddEP(1, USB_TRANSFER_TYPE_BULK, USB_MAX_PACKET_SIZE,
NULL, 0);
InitData.EPOut = USB_AddEP(0, USB_TRANSFER_TYPE_BULK, USB_MAX_PACKET_SIZE,
_abOutBuffer, USB_MAX_PACKET_SIZE);
USB_MSD_Add(&InitData);
memset(&InstData, 0, sizeof(InstData));
InstData.pAPI = &USB_MSD_StorageByName;
InstData.DriverData.pStart = "";
USB_MSD_AddUnit(&InstData);
}
/*********************************************************************
*
* main
*/
void main(void) {
OS_IncDI();
OS_InitKern();
OS_InitHW();
USB_Init();
USB_EnableIAD();
_AddMSD();
_AddCDC();
USB_Start();
OS_CREATETASK(&TCB0, "MSDTask", _MSDTask, 100, Stack0);
OS_CREATETASK(&TCB1, "CDCTask", _CDCTask, 50, Stack1);
OS_Start()
}
388 CHAPTER 13 Combining different USB components (Multi-Inter-
face)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
13.4 emUSB component specific modification
There are different steps for each emUSB component. The next section shows what
needs to be done on both sides: device and host-side.
13.4.1 BULK communication component
13.4.1.1 Device side
No modification on device side needs to be made.
13.4.1.2 Host side
Windows will recognize the device as a composite device. It will load the drivers for
each interface.
In order to recognize the bulk interface in the composite device, the .inf file of the
device needs to be modified.
Windows will extend the device identification string with the interface number. This
has to be added to the device identification string in the .inf file.
The provided .inf file:
;
; Generic USBBulk driver setup information file
; Copyright (c) 2006-2008 by SEGGER Microcontroller GmbH & Co. KG
;
; This file supports:
; Windows 2000
; Windows XP
; Windows Server 2003 x86
; Windows Vista x86
; Windows Server 2008 x86
;
[Version]
Signature="$Windows NT$"
Provider=%MfgName%
Class=USB
ClassGUID={36FC9E60-C465-11CF-8056-444553540000}
DriverVer=03/19/2008,2.6.6.0
CatalogFile=USBBulk.cat
[Manufacturer]
%MfgName%=DeviceList
[DeviceList]
%USB\VID_8765&PID_1234.DeviceDesc%=USBBulkInstall, USB\VID_8765&PID_1234&Mi_xx
[USBBulkInstall.ntx86]
CopyFiles=USBBulkCopyFiles
[USBBulkInstall.ntx86.Services]
Addservice = usbbulk, 0x00000002, USBBulkAddService, USBBulkEventLog
[USBBulkAddService]
DisplayName = %USBBulk.SvcDesc%
ServiceType = 1 ; SERVICE_KERNEL_DRIVER
StartType = 3 ; SERVICE_DEMAND_START
ErrorControl = 1 ; SERVICE_ERROR_NORMAL
ServiceBinary = %10%\System32\Drivers\USBBulk.sys
[USBBulkEventLog]
AddReg=USBBulkEventLogAddReg
[USBBulkEventLogAddReg]
HKR,,EventMessageFile,%REG_EXPAND_SZ%,"%%SystemRoot%%\System32\IoLogMsg.dll;%%System
Root%%\System32\drivers\USBBulk.sys"
HKR,,TypesSupported, %REG_DWORD%,7
[USBBulkCopyFiles]
USBBulk.sys
[DestinationDirs]
DefaultDestDir = 10,System32\Drivers
USBBulkCopyFiles = 10,System32\Drivers
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
389
[SourceDisksNames.x86]
1=%USBBulk.DiskName%,,
[SourceDisksFiles.x86]
USBBulk.sys = 1
;---------------------------------------------------------------;
[Strings]
MfgName="Segger"
USB\VID_8765&PID_1234.DeviceDesc="USB Bulk driver"
USBBulk.SvcDesc="USBBulk driver"
USBBulk.DiskName="USBBulk Installation Disk"
; Non-Localizable Strings, DO NOT MODIFY!
REG_SZ = 0x00000000
REG_MULTI_SZ = 0x00010000
REG_EXPAND_SZ = 0x00020000
REG_BINARY = 0x00000001
REG_DWORD = 0x00010001
; *** EOF ***
Please add the red colored text to your .inf file and change xx with the interface
number of the bulk component.
The interface number is a zero-based index and is assigned by the emUSB stack
when calling the USB_BULK_Add() function. If you have called USB_BULK_Add()
prior to any other USB_xxx_Add() functions then the interface number will be 00.
Please note that when USB_CDC_Add() is called prior USB_BULK_Add(), the interface
number for the BULK component will be 02 since the CDC component uses two inter-
faces (in the example, 00 and 01).
390 CHAPTER 13 Combining different USB components (Multi-Inter-
face)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
13.4.2 MSD component
13.4.2.1 Device side
No modification on device side needs to be made.
13.4.2.2 Host side
No modification on host side needs to be made.
13.4.3 CDC component
13.4.3.1 Device side
In order to combine the CDC component with other components, the function
USB_EnableIAD() needs to be called, otherwise the device will not enumerate correctly.
Refer to section How to combine on page 386 and check the listing of the sample
application.
13.4.3.2 Host side
Due to a limitation of the internal CDC serial driver of Windows, a composite device
with CDC component and another device component(s) is only properly recognized
by Windows XP SP3 and Windows Vista and above. Linux kernel supports IAD with
version 2.6.22.
For Windows the .inf file needs to be modified.
As in the Bulk communication component, Windows will extends the device identifica-
tion strings. Therefore the device identification string must be modified.
The provided .inf file:
;
; Device installation file for
; USB 2 COM port emulation
;
;
;
[Version]
Signature="$Windows NT$"
Class=Ports
ClassGuid={4D36E978-E325-11CE-BFC1-08002BE10318}
Provider=%MFGNAME%
LayoutFile=layout.inf
DriverVer=03/26/2007,6.0.2600.1
CatalogFile=usbser.cat
[Manufacturer]
%MFGNAME%=CDCDevice,NT,NTamd64
[DestinationDirs]
DefaultDestDir = 12
[CDCDevice.NT]
%DESCRIPTION%=DriverInstall,USB\VID_8765&PID_1111&Mi_xx
[CDCDevice.NTamd64]
%DESCRIPTION%=DriverInstall,USB\VID_8765&PID_0234&Mi_xx
%DESCRIPTION%=DriverInstall,USB\VID_8765&PID_1111&Mi_xx
[DriverInstall.NT]
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
391
Include=mdmcpq.inf
CopyFiles=FakeModemCopyFileSection
AddReg=DriverInstall.NT.AddReg
[DriverInstall.NT.AddReg]
HKR,,DevLoader,,*ntkern
HKR,,NTMPDriver,,usbser.sys
HKR,,EnumPropPages32,,"MsPorts.dll,SerialPortPropPageProvider"
[DriverInstall.NT.Services]
AddService=usbser, 0x00000002, DriverServiceInst
[DriverServiceInst]
DisplayName=%SERVICE%
ServiceType=1
StartType=3
ErrorControl=1
ServiceBinary=%12%\usbser.sys
[Strings]
MFGNAME = "Manufacturer"
DESCRIPTION = "USB CDC serial port emulation"
SERVICE = "USB CDC serial port emulation"
Please add the red colored text to your .inf file and change xx with the interface
number of the CDC component.
The interface number is a zero based index and is assigned by the emUSB stack
when calling USB_CDC_Add() function.
392 CHAPTER 13 Combining different USB components (Multi-Inter-
face)
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
13.4.4 HID component
13.4.4.1 Device side
No modification on device side needs to be made.
13.4.4.2 Host side
No modification on host device side needs to be made.
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
393
Chapter 14
Target OS Interface
This chapter describes the functions of the operating system abstraction layer.
394 CHAPTER 14 Target OS Interface
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
14.1 General information
emUSB includes an OS abstraction layer which should make it possible to use an
arbitrary operating system together with emUSB. To adapt emUSB to a new OS one
has only to map the functions listed below in section Interface function list on
page 395 to the native OS functions.
SEGGER took great care when designing this abstraction layer, to make it easy to
understand and to adapt to different operating systems.
14.1.1 Operating system support supplied with this release
In the current version, abstraction layers for embOS and µC/OS-II are available.
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
395
14.2 Interface function list
Routine Explanation
USB_OS_Delay() Delays for a given number of ms.
USB_OS_DecRI() Decrement interrupt disable count and enable interrupts if
counter reaches 0.
USB_OS_GetTickCnt() Returns the current system time in ticks.
USB_OS_IncDI() Increment interrupt disable count and disable interrupts.
USB_OS_Init() Initializes OS.
USB_OS_Panic() Called if fatal error is detected.
USB_OS_Signal() Wake the task waiting for signal.
USB_OS_Wait() Block the task until USB_OS_Signal() is called.
USB_OS_WaitTimed() Block the task until USB_OS_Signal() is called or a timeout
occurs.
Table 14.1: Target OS interface function list
396 CHAPTER 14 Target OS Interface
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
14.2.1 USB_OS_Delay()
Description
Delays for a given number of ms.
Prototype
void USB_OS_Delay(int ms);
Parameter Description
ms Number of ms.
Table 14.2: USB_OS_Delay() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
397
14.2.2 USB_OS_DecRI()
Description
Decrements interrupt disable count and enable interrupts if counter reaches 0.
Prototype
void USB_OS_DecRI(void);
398 CHAPTER 14 Target OS Interface
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
14.2.3 USB_OS_GetTickCnt()
Description
Returns the current system time in ticks.
Prototype
U32 USB_OS_GetTickCnt(void);
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
399
14.2.4 USB_OS_IncDI()
Description
Increments interrupt disable count and disables interrupts.
Prototype
void USB_OS_IncDI(void);
400 CHAPTER 14 Target OS Interface
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
14.2.5 USB_OS_Init()
Description
Initializes OS.
Prototype
void USB_OS_Init(void);
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
401
14.2.6 USB_OS_Panic()
Description
Halts emUSB.
Prototype
void USB_OS_Panic(unsigned ErrCode);
Add. information
Parameter Description
ErrCode Error code.
Table 14.3: USB_OS_Panic() parameter list
Errorcode Explanation
1USB_ERROR_RX_OVERFLOW
2USB_ERROR_ILLEGAL_MAX_PACKET_SIZE
3USB_ERROR_ILLEGAL_EPADDR
4USB_ERROR_IBUFFER_SIZE_TOO_SMALL
5USB_ERROR_DRIVER_ERROR
6USB_ERROR_IAD_DESCRIPTORS_EXCEED
7USB_ERROR_INVALID_INTERFACE_NO
Table 14.4: USB_OS_Panic(): Errorcodes
402 CHAPTER 14 Target OS Interface
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
14.2.7 USB_OS_Signal()
Description
Wakes the task waiting for signal.
Prototype
void USB_OS_Signal(unsigned EPIndex);
Add. information
This routine is typically called from within an interrupt service routine.
Parameter Description
EPIndex Endpoint index.
Table 14.5: USB_OS_Signal() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
403
14.2.8 USB_OS_Wait()
Description
Blocks the task until USB_OS_Signal() is called.
Prototype
void USB_OS_Wait(unsigned EPIndex);
Add. information
This routine is called from a task.
Parameter Description
EPIndex Endpoint index.
Table 14.6: USB_OS_Wait() parameter list
404 CHAPTER 14 Target OS Interface
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
14.2.9 USB_OS_WaitTimed()
Description
Blocks the task until USB_OS_Signal() is called or a timeout occurs.
Prototype
int USB_OS_WaitTimed(unsigned EPIndex, unsigned ms);
Return value
== 0: Task was signaled within the given timeout.
== 1: timeout occurred.
Add. information
USB_OS_WaitTimed is called from a task. This function is used by all available timed
routines.
Parameter Description
EPIndex Endpoint index.
ms timeout time given in ms.
Table 14.7: USB_OS_WaitTimed() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
405
14.3 Example
A configuration to use USB with embOS might look like the sample below. This exam-
ple is also supplied in the subdirectory OS\embOS\.
/*********************************************************************
* SEGGER MICROCONTROLLER GmbH & Co. KG *
* Solutions for real time microcontroller applications *
**********************************************************************
* *
* (c) 2003-2010 SEGGER Microcontroller GmbH & Co KG *
* *
* Internet: www.segger.com Support: support@segger.com *
* *
**********************************************************************
* *
* USB device stack for embedded applications *
* *
**********************************************************************
----------------------------------------------------------------------
File : USB_OS_embOS.c
Purpose : Kernel abstraction for embOS
Do not modify to allow easy updates !
-------- END-OF-HEADER ---------------------------------------------
*/
#include "USB_Private.h"
#include "RTOS.h"
/*********************************************************************
*
* Static data
*
**********************************************************************
*/
#if OS_VERSION < 33200
static OS_TASK * _apTask[USB_NUM_EPS];
#else
static OS_EVENT _aEvent[USB_NUM_EPS];
#endif
/*********************************************************************
*
* Public code
*
**********************************************************************
*/
/*********************************************************************
*
* Depending on the version of embOS, either event objects or
* task events. Event object were in version V3.32 introduced.
*
**********************************************************************
*/
#if OS_VERSION < 33200
/*********************************************************************
*
* USB_OS_Init
*
406 CHAPTER 14 Target OS Interface
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
* Function description:
* This function shall initialize all event objects that are necessary.
*
*/
void USB_OS_Init(void) {
}
/**********************************************************
*
* USB_OS_Signal
*
* Function description
* Wake the task waiting for reception
* This routine is typically called from within an interrupt
* service routine
*
*/
void USB_OS_Signal(unsigned EPIndex) {
if (_apTask[EPIndex] != NULL) {
OS_SignalEvent(1 << EPIndex, _apTask[EPIndex]);
_apTask[EPIndex] = NULL;
}
}
/**********************************************************
*
* USB_OS_Wait
*
* Function description
* Block the task until USB_OS_SignalRx is called
* This routine is called from a task.
*
*/
void USB_OS_Wait(unsigned EPIndex) {
_apTask[EPIndex] = OS_pCurrentTask;
OS_WaitEvent(1 << EPIndex);
}
/**********************************************************
*
* USB_OS_WaitTimed
*
* Function description
* Block the task until USB_OS_Signal is called
* or a timeout occurs
* This routine is called from a task.
*
*/
int USB_OS_WaitTimed(unsigned EPIndex, unsigned ms) {
int r;
_apTask[EPIndex] = OS_pCurrentTask;
r = (int)OS_WaitEventTimed(1 << EPIndex, ms + 1);
return r;
}
#else
/*********************************************************************
*
* USB_OS_Init
*
* Function description:
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
407
* This function shall initialize all event objects that are necessary.
*
*/
void USB_OS_Init(void) {
unsigned i;
for (i = 0; i < COUNTOF(_aEvent); i++) {
OS_EVENT_Create(&_aEvent[i]);
}
}
/**********************************************************
*
* USB_OS_Signal
*
* Function description
* Wake the task waiting for reception
* This routine is typically called from within an interrupt
* service routine
*
*/
void USB_OS_Signal(unsigned EPIndex) {
OS_EVENT_Pulse(&_aEvent[EPIndex]);
}
/**********************************************************
*
* USB_OS_Wait
*
* Function description
* Block the task until USB_OS_SignalRx is called
* This routine is called from a task.
*
*/
void USB_OS_Wait(unsigned EPIndex) {
OS_EVENT_Wait(&_aEvent[EPIndex]);
}
/**********************************************************
*
* USB_OS_WaitTimed
*
* Function description
* Block the task until USB_OS_Signal is called
* or a timeout occurs
* This routine is called from a task.
*
*/
int USB_OS_WaitTimed(unsigned EPIndex, unsigned ms) {
int r;
r = (int)OS_EVENT_WaitTimed(&_aEvent[EPIndex], ms + 1);
return r;
}
#endif
/**********************************************************
*
* USB_OS_Delay
*
* Function description
* Delays for a given number of ms.
*
408 CHAPTER 14 Target OS Interface
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
*/
void USB_OS_Delay(int ms) {
OS_Delay(ms);
}
/**********************************************************
*
* USB_OS_DecRI
*
* Function description
* Decrement interrupt disable count and enable interrupts
* if counter reaches 0.
*
*/
void USB_OS_DecRI(void) {
OS_DecRI();
}
/**********************************************************
*
* USB_OS_IncDI
*
* Function description
* Increment interrupt disable count and disable interrupts
*
*/
void USB_OS_IncDI(void) {
OS_IncDI();
}
/**********************************************************
*
* USB_OS_Panic
*
* Function description
* Called if fatal error is detected.
*
* Add. info
* Error codes:
* 1 USB_ERROR_RX_OVERFLOW
* 2 USB_ERROR_ILLEGAL_MAX_PACKET_SIZE
* 3 USB_ERROR_ILLEGAL_EPADDR
* 4 USB_ERROR_IBUFFER_SIZE_TOO_SMALL
*/
void USB_OS_Panic(unsigned ErrCode) {
while (ErrCode);
}
/**********************************************************
*
* USB_OS_GetTickCnt
*
* Function description
* Returns the current system time in ticks.
*/
U32 USB_OS_GetTickCnt(void) {
return OS_Time;
}
/*************************** End of file ****************************/
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
409
Chapter 15
Target USB Driver
This chapter describes emUSB hardware interface functions in detail.
410 CHAPTER 15 Target USB Driver
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
15.1 General information
Purpose of the USB hardware interface
emUSB does not contain any hardware dependencies. These are encapsulated
through a hardware abstraction layer, which consists of the interface functions
described in this chapter. All of these functions for a particular USB controller are
typically located in a single file, the USB driver. Drivers for hardware which has
already been tested with emUSB are available.
Range of supported USB hardware
The interface has been designed in such a way that it should be possible to use the
most common USB device controllers. This includes USB 1.1 controllers and USB 2.0
controllers, both as external chips and as part of microcontrollers.
15.1.1 Available USB drivers
An always up to date list can be found at:
http://www.segger.com/pricelist-emusb.html
The following device drivers are available for emUSB:
Driver (Device) Identifier
ATMEL AV32 UC3x USB_Driver_Atmel_AT32UC3x
ATMEL AT91CAP9x USB_Driver_Atmel_CAP9
ATMEL AT91SAM3S/AT91SAM4S USB_Driver_Atmel_SAM3S
ATMEL AT91SAM3Uxx USB_Driver_Atmel_SAM3US
ATMEL AT91SAM3x8 USB_Driver_Atmel_AT91SAM3X
ATMEL AT91RM9200 USB_Driver_Atmel_RM9200
ATMEL AT91SAM7A3 USB_Driver_Atmel_SAM7A3
ATMEL AT91SAM7S64 USB_Driver_Atmel_SAM7S
ATMEL AT91SAM7S128 USB_Driver_Atmel_SAM7S
ATMEL AT91SAM7S256 USB_Driver_Atmel_SAM7S
ATMEL AT91SAM7SE USB_Driver_Atmel_SAM7SE
ATMEL AT91SAM7X128 USB_Driver_Atmel_SAM7X
ATMEL AT91SAM7X256 USB_Driver_Atmel_SAM7X
ATMEL AT91SAM9260 USB_Driver_Atmel_SAM9260
ATMEL AT91SAM9261 USB_Driver_Atmel_SAM9261
ATMEL AT91SAM9263 USB_Driver_Atmel_SAM9263
ATMEL AT91SAM9R64
ATMEL AT91SAM9RL64 USB_Driver_Atmel_SAMRx64
ATMEL AT91SAM9G20 USB_Driver_Atmel_SAM9G20
ATMEL AT91SAM9G45 USB_Driver_Atmel_SAM9G45
ATMEL AT91SAM9XE USB_Driver_Atmel_SAM9XE
EnergyMicro EFM32GG USB_Driver_EM_EFM32GG990
Freescale iMX25x USB_Driver_Freescale_iMX25x
Freescale iMX28x USB_Driver_Freescale_iMX28x
Freescale Kinetis K40 USB_Driver_Freescale_K40
Freescale Kinetis K60 USB_Driver_Freescale_K60
Freescale MCF227x USB_Driver_Freescale_MCF227x
Freescale MCF225x USB_Driver_Freescale_MCF225x
Freescale MCF51JMx USB_Driver_Freescale_MCF51JMx
Freescale Vybrid USB_Driver_Freescale_Vybrid
Fujitsu MB9BF50x USB_Driver_Fujitsu_MB9BF50x
NXP LPC13xx USB_Driver_NXP_LPC13xx
Table 15.1: List of included USB device drivers
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
411
NXP LPC17xx USB_Driver_NXP_LPC17xx
NXP LPC18xx USB_Driver_NXP_LPC18xx
NXP LPC214x USB_Driver_NXP_LPC214x
NXP LPC23xx USB_Driver_NXP_LPC23xx
NXP LPC24xx USB_Driver_NXP_LPC24xx
NXP LPC313x USB_Driver_NXP_LPC313x
NXP LPC318x USB_Driver_NXP_LPC318x
NXP LPC43xx USB_Driver_NXP_LPC43xx
NXP (formerly Sharp) LH79524/5 USB_Driver_Sharp_LH79524
NXP (formerly Sharp) LH7A40x USB_Driver_Sharp_LH7A40x
OKI 69Q62 USB_Driver_OKI_69Q62
Renesas H8S2472 USB_Driver_Renesas_H8S2472
Renesas H8SX1668R USB_Driver_Renesas_H8SX1668R
Renesas RX62N USB_Driver_Renesas_RX62N
Renesas RX63N/RX631 USB_Driver_Renesas_RX62N
Renesas SH7203 USB_Driver_Renesas_SH7203
Renesas SH7216 USB_Driver_Renesas_SH7216
Renesas SH7286 USB_Driver_Renesas_SH7286
Renesas (NEC) 78K0R-KE3L USB_Driver_NEC_78F102x
Renesas (NEC) µPD720150 USB_Driver_NEC_uPD720150
Renesas (NEC) V850ESJG3H USB_Driver_NEC_70F376x
ST STM32 USB_Driver_ST_STM32
ST STM32F105/107 USB_Driver_ST_STM32F107
ST STR71x USB_Driver_ST_STR71x
ST STR750 USB_Driver_ST_STR750
ST STR912 USB_Driver_ST_STR91x
Toshi ba T MPA900 USB_Driver_Toshiba_TMPA900
Toshiba TMPA910 USB_Driver_Toshiba_TMPA910
Texas Intruments MSP430X5529 USB_Driver_TI_MSP430
Texas Intruments (Luminary) LM3S9B9x USB_Driver_TI_LM3S9B9x
Driver (Device) Identifier
Table 15.1: List of included USB device drivers
412 CHAPTER 15 Target USB Driver
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
15.2 Adding a driver to emUSB
You have to specify the USB device driver which should be used with emUSB. To
specify the driver USB_X_AddDriver() is called from USB_Init(). This function
should be used to add a USB driver to your project.
USB_Init() initializes the internal of the USB stack and is always the first function
which that USB application has to call. USB_X_HWAttach() should be used to perform
hardware-specific actions which are not part of the USB controller logic (for example,
enabling the peripheral clock for USB port).
This function is called from every device driver, but can be empty if your hardware
does not need to perform such actions. Modify USB_X_AddDriver() and if required,
USB_X_HWAttach(). In USB_X_AddDriver(), USB_AddDriver() should be called with
the identifier of the driver which is compatible to your hardware as parameter. Refer
to the section Available USB drivers on page 410 for a list of all supported devices
and their valid identifiers.
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
413
15.2.1 USB_X_HWAttach()
Description
Should be used to perform hardware specific actions which are not part of the USB
controller logic.
Prototype
void USB_X_HWAttach(void)
Additional Information
This function can be empty, if no hardware-specific actions are required.
Example
/* Example excerpt from USB_Config_SAM7A3.c */#
#define _AT91C_PIOA_BASE (0xFFFFF400)
#define _AT91C_PIOB_BASE (0xFFFFF600)
#define _AT91C_PMC_BASE (0xFFFFFC00)
#define _PIO_PER_OFFS (0x00)
#define _PIO_OER_OFFS (0x10)
#define _PIO_CODR_OFFS (0x34) /* Clear output data register */
#define _PMC (*(volatile unsigned int*) _AT91C_PMC_BASE)
#define _USB_ID (_PIOB_ID)
#define _USB_OER (*(volatile unsigned int*) (_AT91C_PIOB_BASE + _PIO_OER_OFFS))
#define _USB_CODR (*(volatile unsigned int*) (_AT91C_PIOB_BASE + _PIO_CODR_OFFS))
#define _USB_DP_PUP_BIT (1)
void USB_X_HWAttach(void) {
_PMC = (1 << _USB_ID); /* Enable peripheral clock for USB-Port */
_USB_OER = (1 << _USB_DP_PUP_BIT); /* set USB_DP_PUP to output */
_USB_CODR = (1 << _USB_DP_PUP_BIT); /* set _USB_DP_PUP_BIT to low state */
}
414 CHAPTER 15 Target USB Driver
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
15.2.2 USB_X_AddDriver()
Description
Adds a USB hardware driver to the USB stack.
Prototype
void USB_X_AddDriver(void)
Additional information
This function is always called from USB_Init().
Example
/* Example excerpt from USB_Config_SAM7A3.c */
void USB_X_AddDriver(void) {
USB_AddDriver(&USB_Driver_AtmelSAM7A3);
}
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
415
15.3 Interrupt handling
emUSB is interrupt driven and optimized to be used with a real-time operating sys-
tem. If you use embOS in combination with emUSB, you can skip the following sec-
tions.
If you are not using embOS, you have to be familiar with how interrupts are handled
on your target system. This includes knowledge about how the CPU handles inter-
rupts, how and which registers are saved, the interrupt vector table, how the inter-
rupt controller works and how it is reset.
15.3.1 ARM7 / ARM9 based cores
ARM7 and ARM9 cores will jump to IRQ vector address 0x18, where a jump to an ARM
specific IRQ handler should be located. This ARM specific IRQ handler calls a device
specific interrupt handler which handles the interrupt controller.
The ARM specific interrupt handler is typically coded in assembly language. It has to
ensure that no context information will be lost if an interrupt occurs. The environ-
ment of the interrupted function has to be restored after processing the interrupt.
The environment of the interrupted function includes the value of the processor reg-
isters and the processor status register. The ARM specific interrupt handler calls a
high-level interrupt handler which manages the call of the interrupt source specific
service routine.
IRQ_HandlerASM()
Unified ARM specific
interrupt handler
IRQ_Handler()
Unified device specific
interrupt handler
Purpose: Saves registers &
calls C-Handler
This handler is activated for
all interrupts.
Responsibility of application
programmer / OS.
Typically coded in assembly
language.
Purpose: Resets the
interrupt controller and
calls interrupt specific
handler (depending on
cause). This handler is
activated for all interrupts.
Responsibility of application
programmer / OS.
Typically coded in C.
Purpose: Handles
USB data transfer.
Part of emUSB driver.
Coded in C.
Interrupt
specific handler
Interrupt
specific handler
USB interrupt
handler
416 CHAPTER 15 Target USB Driver
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
15.3.1.1 ARM specific IRQ handler
The ARM specific interrupt handler saves the context of the function which is inter-
rupted, calls the high-level interrupt handler and restores the context. Sample imple-
mentations of the high-level handler are supplied in the following device specific
sections.
Sample implementation interrupt handler
EXTERN IRQ_Handler
IRQ_HandlerASM:
;
; Save temp. registers
;
stmdb SP!,{R0-R3,R12,LR} ; push
;
; push SPSR (req. if we allow nested interrupts)
;
mrs R0, SPSR ; load SPSR
stmdb SP!,{R0} ; push SPSR_irq on IRQ stack
;
; Call "C" interrupt handler
;
ldr R0,=IRQ_Handler
mov LR,PC
bx R0
;
; pop SPSR
;
ldmia SP!, {R1} ; pop SPSR_irq from IRQ stack
msr SPSR_cxfs, R1
;
; Restore temp registers
;
ldmia SP!, {R0-R3,R12,LR} ; pop
subs PC, LR, #4 ; RETI
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
417
15.3.1.2 Device specifics ATMEL AT91CAP9x
The interrupt handler needs to read the address of the interrupt source specific han-
dler function.
Sample implementation interrupt handler
#define _AIC_BASE_ADDR (0xfffff000UL)
#define _AIC_IVR (*(volatile unsigned int*)(_AIC_BASE_ADDR + 0x100))
#define _AIC_EOICR (*(volatile unsigned int*)(_AIC_BASE_ADDR + 0x130))
typedef void ISR_HANDLER(void);
void IRQ_Handler(void) {
ISR_HANDLER* pISR;
pISR = (ISR_HANDLER*) _AIC_IVR; // Read interrupt vector to release
// NIRQ to CPU core
pISR(); // Call interrupt service routine
_AIC_EOICR = 0; // Reset interrupt controller => Restore
// previous priority
}
Additional information
This example can also be used with an ATMEL AT91RM9200, AT91SAM7A3,
AT91SAM7S64, AT91SAM7S128, AT91SAM7S256, AT91SAM7SE, AT91SAM7X64,
AT91SAM7X128, AT91SAM7X256, and AT91SAM9261.
15.3.1.3 Device specifics ATMEL AT91RM9200
For an example implementation of an interrupt handler function refer to Device spe-
cifics ATMEL AT91CAP9x on page 417.
15.3.1.4 Device specifics ATMEL AT91SAM7A3
For an example implementation of an interrupt handler function refer to Device spe-
cifics ATMEL AT91CAP9x on page 417.
15.3.1.5 Device specifics ATMEL AT91SAM7S64, AT91SAM7S128,
AT91SAM7S256
For an example implementation of an interrupt handler function refer to Device spe-
cifics ATMEL AT91CAP9x on page 417.
15.3.1.6 Device specifics ATMEL AT91SAM7X64, AT91SAM7X128,
AT91SAM7X256
For an example implementation of an interrupt handler function refer to Device spe-
cifics ATMEL AT91CAP9x on page 417.
15.3.1.7 Device specifics ATMEL AT91SAM7SE
For an example implementation of an interrupt handler function refer to Device spe-
cifics ATMEL AT91CAP9x on page 417.
15.3.1.8 Device specifics ATMEL AT91SAM9260
For an example implementation of an interrupt handler function refer to Device spe-
cifics ATMEL AT91CAP9x on page 417.
15.3.1.9 Device specifics ATMEL AT91SAM9261
For an example implementation of an interrupt handler function refer to Device spe-
cifics ATMEL AT91CAP9x on page 417.
418 CHAPTER 15 Target USB Driver
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
15.3.1.10Device specifics ATMEL AT91SAM9263
For an example implementation of an interrupt handler function refer to Device spe-
cifics ATMEL AT91CAP9x on page 417.
15.3.1.11Device specifics ATMEL AT91SAMRL64, AT91SAMR64
For an example implementation of an interrupt handler function refer to Device spe-
cifics ATMEL AT91CAP9x on page 417.
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
419
15.3.1.12Device specifics NXP LPC214x
The interrupt handler needs to read the address of the interrupt source specific han-
dler function.
Sample implementation interrupt handler
#define _VIC_BASE_ADDR (0xFFFFF000)
#define _VIC_VECTORADDR *(volatile unsigned int*)(_VIC_BASE_ADDR + 0x0030)
typedef void ISR_HANDLER(void);
void IRQ_Handler(void) {
ISR_HANDLER* pISR;
pISR = (ISR_HANDLER*) _VIC_VECTORADDR; // Get current interrupt handler
pISR(); // Call interrupt service routine
_VIC_VECTORADDR = 0; // Clear current interrupt pending
// condition, reset VIC
}
15.3.1.13Device specifics NXP LPC23xx
For an example implementation of an interrupt handler function refer to Device spe-
cifics NXP LPC214x on page 419.
15.3.1.14Device specifics NXP (formerly Sharp) LH79524/5
For an example implementation of an interrupt handler function, please contact SEG-
GER, www.segger.com.
15.3.1.15Device specifics OKI 69Q62
For an example implementation of an interrupt handler function, please contact SEG-
GER, www.segger.com.
15.3.1.16Device specifics ST STR71x
For an example implementation of an interrupt handler function, please contact SEG-
GER, www.segger.com.
15.3.1.17Device specifics ST STR750
For an example implementation of an interrupt handler function, please contact SEG-
GER, www.segger.com.
15.3.1.18Device specifics ST STR750
For an example implementation of an interrupt handler function, please contact SEG-
GER, www.segger.com.
420 CHAPTER 15 Target USB Driver
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
15.4 Writing your own driver
This section is only relevant if you plan to develop a driver for an unsupported
device. Refer to Available USB drivers on page 410 for a list of currently supported
devices.
Access to the USB hardware is realized through an API-function table. The structure
USB_HW_DRIVER is declared in USB\USB.h.
15.4.1 Structure USB_HW_DRIVER
Description
Structure that contains callback function which manage the hardware access.
Prototype
typedef struct USB_HW_DRIVER {
void (*pfInit) (void);
U8 (*pfAllocEP) (U8 InDir, U8 TransferType);
void (*pfUpdateEP) (EP_STAT * pEPStat);
void (*pfEnable) (void);
void (*pfAttach) (void);
unsigned (*pfGetMaxPacketSize) (U8 EPIndex);
int (*pfIsInHighSpeedMode) (void);
void (*pfSetAddress) (U8 Addr);
void (*pfSetClrStallEP) (U8 EPIndex, int OnOff);
void (*pfStallEP0) (void);
void (*pfDisableRxInterruptEP)(U8 EpOut);
void (*pfEnableRxInterruptEP) (U8 EpOut);
void (*pfStartTx) (U8 EPIndex);
void (*pfSendEP) (U8 EPIndex, const U8 * p,
unsigned NumBytes);
void (*pfDisableTx) (U8 EPIndex);
void (*pfResetEP) (U8 EPIndex);
int (*pfControl) (U8 Cmd, void * p);
} USB_HW_DRIVER;
Member Description
USB initialization functions
pfInit() Initializes the USB controller.
General USB functions
pfAttach() Indicates device attachment.
pfEnable() Enables endpoint.
pfControl Used to support additional driver functionality.
This function is optional.
pfSetAddress() Notifies the USB controller of the new address
assigned by the host for it.
General endpoints functions
pfAllocEP Allocates an endpoint to be used with emUSB.
pfGetMaxPacketSize Returns the maximum packet size of an end-
point.
pfSetClrStallEP() Set or cleats the stall condition of the end-
point.
pfUpdateEP() Configures the USB controller’s endpoint.
pfResetEP() Resets an endpoint including resetting the
data toggle of the endpoint.
Endpoint 0 (Control endpoint) related functions
Table 15.2: List of callback functions of USB_HW_DRIVER
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
421
pfStallEP0() Stalls endpoint 0.
OUT-endpoints functions
pfDisableRxInterruptEP() Disables OUT-endpoint interrupt.
pfEnableRxInterruptEP() Enables OUT-endpoint interrupt.
IN-endpoints functions
pfDisableTx Disables IN endpoint transfers.
pfSendEP() Sends data on the given IN-endpoint.
pfStartTx() Starts data transfer on the given IN-endpoint.
Member Description
Table 15.2: List of callback functions of USB_HW_DRIVER
422 CHAPTER 15 Target USB Driver
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
15.4.2 USB initialization functions
15.4.2.1 (*pfInit)()
Description
Performs any necessary initializations on the USB controller.
Prototype
void (*pfInit)(void);
Additional information
The initializations performed in this routine should include what is needed to prepare
the device for enumeration. Such initializations might include setting up endpoint 0
and enabling interrupts. It sets default values for EP0 and enables the various inter-
rupts needed for USB operations.
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
423
15.4.3 General USB functions
15.4.3.1 (*pfAttach)()
Description
For USB controllers that have a USB Attach/Detach register (such as the OKI
ML69Q6203), this routine sets the register to indicate that the device is attached.
Prototype
void (*pfAttach)(void);
15.4.3.2 (*pfEnable)()
Description
This function is used for enabling the USB controller after it was initialized.
Prototype
void (*pfEnable)(void);
Additional information
For most USB controllers this function can be empty. This function is only necessary
for USB devices that reset their configuration data after an USB-RESET.
15.4.3.3 (*pfControl)()
Description
This function is used to support additional driver functionality. This function is
optional.
Prototype
int (*pfControl)(U8 Cmd, void * p);
Return value
0 - Command operation was successful.
1 - Command operation was not successful.
-1 - Command was unknown.
Additional information
This control function is only called when available. This function will check or changes
state of a device driver. Currently the following commands are available:
Parameter Description
Cmd Command that shall be executed.
pPointer to data, necessary for the command.
Table 15.3: (*pfControl)() parameter list
Command Description
0USB_DRIVER_CMD_SET_CONFIGURATION
1USB_DRIVER_CMD_GET_TX_BEHAVIOR
Table 15.4: (*pfControl): Commands
424 CHAPTER 15 Target USB Driver
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
15.4.3.4 (*pfSetAddress)()
Description
This function is used for notifying the USB controller of the new address that the host
has assigned to it during enumeration.
Prototype
void (*pfSetAddress)(U8 Addr);
Additional information
If the USB controller does not automatically send a 0-byte acknowledgment in the
status stage of the control transfer phase, make sure to set a state variable to Addr
and defer setting the controller's Address register until after the status stage. This is
necessary because the host sends the token packet for the status stage to the default
address (0x00), which means the device must still be using this address when the
packet is sent.
Parameter Description
Addr New address assigned by the USB host.
Table 15.5: (*pfSetAddress)() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
425
15.4.4 General endpoint functions
15.4.4.1 (*pfAllocEP)()
Description
Allocates a physical endpoint to be used with emUSB.
Prototype
U8 (*pfAllocEP)(U8 InDir, U8 TransferType);
Return value
Index number of the logical endpoint. Allowed values are 1..15.
Additional information
This function is typically called after stack initialization, in order to have the right
endpoint settings for building the descriptors correctly.
It is the responsibility of the driver engineer to give a valid logical endpoint number.
If there is no valid endpoint for the desired configuration available, 0 should be
returned.
15.4.4.2 (*pfGetMaxPacketSize)()
Description
Returns the maximum packet size of an endpoint.
Prototype
unsigned (*pfGetMaxPacketSize)(U8 EPIndex);
Return value
The maximum packet size in bytes.
Parameter Description
InDir
Indicates the direction of the endpoint.
0 indicates an OUT-endpoint.
1 indicates an IN-endpoint.
TransferType
Specifies the transfer type for the desired endpoint.
The following transfer types are available:
USB_TRANSFER_TYPE_BULK
USB_TRANSFER_TYPE_ISO
USB_TRANSFER_TYPE_INT
Table 15.6: (*pfAllocEP)() parameter list
Parameter Description
EPIndex Endpoint index.
Table 15.7: (*pfGetMaxPacketSize)() parameter list
426 CHAPTER 15 Target USB Driver
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
15.4.4.3 (*pfSetClrStallEP)()
Description
Sets or clears the stall condition of an endpoint.
Prototype
void (*pfSetClrStallEP)(U8 EPIndex, int OnOff);
Additional information
Typically, this function is called whenever a protocol/transfer error occurs.
15.4.4.4 (*pfUpdateEP)()
Description
Configures the USB controller’s endpoint.
Prototype
void (*pfUpdateEP)(EP_STAT * pEPStat);
Additional information
EP_STAT is defined as follows:
typedef struct {
U16 NumAvailBuffers;
U16 MaxPacketSize;
U16 Interval;
U8 EPType;
BUFFER Buffer;
U8 * pData;
volatile U32 NumBytesRem;
U8 EPAddr; // b[6:0]: EPAddr b7: Direction, 1: Device to Host (IN)
U8 Send0PacketIfRequired;
} EP_STAT;
Before a hardware attach is done, this function is called to configure the desired end-
points, so that the additional endpoints are ready for use after the enumeration
phase.
Parameter Description
EPIndex Endpoint that shall be stalled.
OnOff
Specifies if the stall condition shall be set or cleared.
Whereas:
0 - Clears the stall condition.
1 - Set the stall condition.
Table 15.8: (*pfSetClrStallEP)() parameter list
Parameter Description
pEPStat Pointer to EP_STAT structure that holds the information for the end-
point.
Table 15.9: (*pfUpdateEP)() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
427
15.4.4.5 (*pfResetEP)()
Description
Resets an endpoint including resetting the data toggle of the endpoint.
Prototype
void (*pfResetEP)(U8 EPIndex);
Additional information
Resets the endpoint which includes setting data toggle to DATA0.
It is useful after removing a HALT condition on a BULK endpoint.
Refer to Chapter 5.8.5 in the USB Serial Bus Specification, Rev.2.0.
Note: Configuration of the endpoint needs to be unchanged. If the USB controller
loses the EP configuration the pfUpdateEP of the driver shall be called.
Parameter Description
EPIndex Endpoint that shall be reset.
Table 15.10: (*pfResetEP)() parameter list
428 CHAPTER 15 Target USB Driver
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
15.4.5 Endpoint 0 (control endpoint) related functions
15.4.5.1 (*pfStallEP0)()
Description
This function is used for stalling endpoint 0 (by setting the appropriate bit in a con-
trol register).
Prototype
void (*pfStallEP0)(void);
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
429
15.4.6 OUT-endpoint functions
15.4.6.1 (*pfDisableRxInterruptEP)()
Description
Disables the OUT-endpoint interrupt.
Prototype
void (*pfDisableRxInterruptEP)(U8 EPIndex);
15.4.6.2 (*pfEnableRxInterruptEP)()
Description
Enables the OUT-endpoint interrupt.
Prototype
void (*pfEnableRxInterruptEP)(U8 EPIndex);
Parameter Description
EPIndex OUT-endpoint whose interrupt needs to be disabled.
Table 15.11: (*pfDisableRxInterruptEP)() parameter list
Parameter Description
EPIndex OUT-endpoint whose interrupt needs to be enabled.
Table 15.12: (*pfEnableRxInterruptEP)() parameter list
430 CHAPTER 15 Target USB Driver
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
15.4.7 IN-endpoint functions
15.4.7.1 (*pfStartTx)()
Description
Starts data transfer on the given IN-endpoint.
Prototype
void (*pfStartTx)(U8 EPIndex);
Additional information
This function is called to start sending data to the host.
Depending on the design of the USB controller, one of the following steps needs to be
done:
If the USB controller sends a packet and waits for acceptance by the host, your appli-
cation must:
Enable IN-endpoint interrupt.
Send a packet using USB__Send(EPIndex).
If the USB controller waits for an IN-token, your application must:
Enable the IN-endpoint interrupt.
15.4.7.2 (*pfSendEP)()
Description
Sends data on the given IN-endpoint.
Prototype
void (*pfSendEP)(U8 EPIndex, const U8 * p, unsigned NumBytes);
Additional information
This function is called whenever data should be transferred to the host. Because p
might not be aligned, it is the responsibility of the developer to care about the align-
ment of the USB controller buffer/FIFO.
Parameter Description
EPIndex IN-endpoint that needs to be enabled.
Table 15.13: (*pfStartTX)() parameter list
Parameter Description
EPIndex IN-endpoint that is used to send the data.
pPointer to a buffer that needs to be sent.
NumBytes Number of bytes that needs to be sent.
Table 15.14: (*pfSendEP)() parameter list
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
431
15.4.7.3 (*pfDisableTx)()
Description
Disables IN-endpoint transfers.
Prototype
void (*pfDisableTx)(U8 EPIndex);
Additional information
Normally, this function should disable the IN-endpoint interrupt. Some USB control-
lers do not work correctly after the IN interrupt is disabled, therefore this should be
done by the software.
Parameter Description
EPIndex IN-endpoint that needs to be disabled.
Table 15.15: (*pfDisableTx)() parameter list
432 CHAPTER 15 Target USB Driver
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
15.4.8 USB driver interrupt handling
emUSB is interrupt driven. Therefore, it is necessary to have an interrupt handler for
the used USB controller. For the drivers that are available this is already done. If you
are writing your own USB driver the following schematic shows which functions need
to be called when an USB interrupt occurs:
Function Description
USB__HandleSetup() Determines request type.
USB__OnBusReset() Flushes the input buffer and set the
“_IsInReset” flag.
USB__OnTx() Handles a Tx transfer.
USB__OnRx() Handles a Rx transfer.
USB__OnResume() Resumes the device.
USB__OnSuspend() Suspends the device.
Table 15.16: emUSB interrupt handling functions
EP0?
USB
interrupt
occured
RX? Yes
Read Setup
packet
Call
USB_HandleSetup()
Setup packet?
Yes
Read data
Call
USB__OnRX()
TX?
No
No
Yes
No
Yes
Call
USB__OnTx()
USB interrupt
end
USB reset
occurred
No
Call
USB__OnReset()
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
433
Chapter 16
Support
This chapter can help you if any problem occurs; this could be a problem with the
tool chain, with the hardware, the use of the functions, or with the performance and
it describes how to contact the support.
434 CHAPTER 16 Support
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
16.1 Problems with tool chain (compiler, linker)
The following shows some of the problems that can occur with the use of your tool
chain. The chapter tries to show what to do in case of a problem and how to contact
the support if needed.
16.1.1 Compiler crash
You ran into a tool chain (compiler) problem, not a problem with the software. If one
of the tools of your tool chain crashes, you should contact your compiler support:
"Tool internal error, please contact support"
16.1.2 Compiler warnings
The code of the software has been tested with different compilers. We spend a lot of
time on improving the quality of the code and we do our best to avoid compiler warn-
ings. But the sensitivity of each compiler regarding warnings is different. So we can
not avoid compiler warnings for unknown tools.
Warnings you should not see
This kind of warnings should not occur:
"Function has no prototype"
"Incompatible pointer types"
"Variable used without having been initialized"
’Illegal redefinition of macro’
Warnings you may see
Warnings such as the ones below should be ignored:
"Integer conversion, may lose significant bits"
’Statement not reached"
"Meaningless statements were deleted during optimization"
Most compilers offers a way to suppress selected warnings.
16.1.3 Compiler errors
We assume that the used compiler is ANSI C compatible. If it is compatible there
should be no problem to translate the code.
16.1.4 Linker problems
Undefined externals
If your linker shows the error message “Undefined external symbols...” check if all
required files have been included to the project.
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
435
16.2 Problems with hardware/driver
If your tools are working fine but your USB-Bulk device does not work may be one of
the following helps to find the problem.
Stack size to low?
Make sure there have been configured enough stack. We can not estimate exactly
how much stack will be used by your configuration and with your compiler.
16.3 Contacting support
If you need to contact the support, send the following information
to support@segger.com:
A detailed description of the problem
The configuration file USB_Conf.h
The error messages of the compiler
436 CHAPTER 16 Support
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
437
Chapter 17
Certification
This chapter describes the process of USB driver certification with
Microsoft Windows.
438 CHAPTER 17 Certification
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
17.1 What is the Windows Logo Certification and why
do I need it?
The Windows Logo Certification process will sign the driver with a Microsoft certificate
which signifies that the device is compatible and safe to use with Microsoft Windows
operating systems.
If the driver is not signed the user will be confronted with messages saying that the
driver is not signed and may not be safe to use with Microsoft Windows. Depending on
which Windows version you are using a different message will be shown.
Users of Windows Server 2008, Windows Vista x64 and Windows 7 x64 will be warned
about the missing signature and the driver will show up as installed, but the driver will
not be loaded. The user can override this security measure by hitting F8 on Windows
start-up and selecting "Disable Driver Signature Enforcement" or editing the registry.
Microsoft Windows XP:
Microsoft Windows Vista/7:
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
439
17.2 Certification offer
Customers can complete the certification by themselves. But SEGGER also offers cer-
tification for our customers. To certify a device a customer needs a valid vendor ID,
registered at www.usb.org and a free product ID. Using the Microsoft Windows Logo
Kit a certification package is created. The package is sent to Microsoft for confirma-
tion. After the confirmation is received from Microsoft the customer receives a .cat
file which allows the drivers to be installed without problems.
17.3 Vendor and Product ID
A detailed description of the Vendor and Product ID can be found in chapter Product /
Vendor IDs on page 35
The customer can acquire a Vendor ID from the USB Implementers Forum, Inc.
(www.usb.org). This allows to freely decide which Product ID is used for which prod-
uct.
17.4 Certification without SEGGER Microcontroller
Certification can be completed by the customer themselves. To complete the certifi-
cation the Windows Logo Kit software is needed. It has to be installed on a Windows
2008 Server x64. A Code Signing certificate from Microsoft, two target devices and
two client computers will also be needed, Windows 7 x86 and Windows 7 x64 respec-
tively. After installing and setting up the WLK, the client software has to be down-
loaded via a Windows share from the Windows 2008 Server. The target devices will
have to be connected to the client computer.
Using the WLK the target devices can be selected and the appropriate tests can be
scheduled. A few of the tests need human intermission and a few tests only run with
one device, while others only run with two. The tests can take up to 15 hours. The
tests have to be done separately for x86 and x64. Two separate submission packages
have to be created for both architectures. The submission packages has to be consol-
idated using the Winqual Submission Tool and signed with the Code Sign certificate.
Further information, as well as the required software can be found at:
http://msdn.microsoft.com/en-us/library/windows/hardware/gg487530.aspx
Please refer to Microsoft’s WLK documentation for a detailed description of the certi-
fication process.
440 CHAPTER 17 Certification
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
441
Chapter 18
Performance & resource usage
This chapter covers the performance and resource usage of emUSB. It contains infor-
mation about the memory requirements in typical systems which can be used to
obtain sufficient estimates for most target systems.
442 CHAPTER 18 Performance & resource usag e
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
18.1 Memory footprint
emUSB is designed to fit many kinds of embedded design requirements. Several fea-
tures can be excluded from a build to get a minimal system. Note that the values are
only valid for the given configuration.
The tests were run on a 32-bit CPU running at 48MHz. The test program was com-
piled for size optimization.
18.1.1 ROM
The following table shows the ROM requirement of emUSB:
* ROM size of emFile Storage app. 4 Kbytes.
18.1.2 RAM
The following table shows the RAM requirement of emUSB:
Additionally 64 or 512 bytes (64 for Full Speed and 512 for High Speed devices) are
necessary for each OUT-endpoint as a data buffer. This buffer is assigned within the
application.
Description ROM
emUSB core app. 5.5 Kbytes
Bulk component app. 400 Bytes
MSD component app. 5 Kbytes + sizeof(Storage-
Layer)*
HID component app. 400 Bytes
CDC component app. 1.1 Kbytes
PrinterClass component app. 400 Bytes
USB target driver app. 1.2 - 3 Kbytes
MTP component app. 8 kBytes
Description RAM
emUSB core app. 800 Bytes
Bulk component app. 4 Bytes
MSD component
app. 200 Bytes
+ configurable sector buffer
of minimum 512 bytes
HID component app. 30 Bytes
CDC component app. 70 Bytes
PrinterClass component app. 2 Kbytes
USB target driver < 1 Kbytes
MTP component
app. 200 bytes
+ configurable file data buffer
of minimum 512 bytes
+ configurable object buffer
(typically 4 kBytes).
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
443
18.2 Performance
The tests were run on a 32-bit CPU running at 48MHz with an Atmel SAM7S device
driver using the USB Bulk component.
The following table shows the send and receive speed of emUSB:
Description Speed
Bulk
Send speed 800 KByte/sec
Receive speed 760 KByte/sec
444 CHAPTER 18 Performance & resource usag e
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
445
Chapter 19
FAQ
This chapter answers some frequently asked questions.
446 CHAPTER 19 FAQ
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
Q: Which CPUs can I use emUSB with?
A: 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.
Q: Do I need a real-time operating system (RTOS) to use the USB-MSD?
A: No, if your target application is a pure storage application. You do not need an
RTOS if all you want to do is running the USB-MSD stack as the only task on the
target device. If your target application is more than just a storage device and
needs to perform other tasks simultaneously, you need an RTOS which handles the
multi-tasking.
We recommend using our embOS Real-time OS, since all example and trial
projects are based on it.
Q: Do I need extra file system code to use the USB-MSD stack?
A: No, if you access the target data only from the host.
Yes, if you want to access the target data from within the target itself.
There is no extra file system code needed if you only want to access the data on
the target from the host side. The host OS already provides several file systems.
You have to provide file system program code on the target only if you want to
access the data from within the target application itself.
Q: Can I combine different USB components together?
A: In general this is possible, by simply calling the appropriate add function of the
USB component. See more information in Combining different USB components
(Multi-Interface) on page 381.
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
Index 447
Index
B
Bulk Communication
USB_BULK_Add() ..............................90
USB_BULK_CancelRead() ...................91
USB_BULK_CancelWrite() ...................92
USB_BULK_GetNumBytesInBuffer() .....93
USB_BULK_GetNumBytesRemToRead() 94
USB_BULK_GetNumBytesToWrite() ......95
USB_BULK_INIT_DATA ..................... 111
USB_BULK_Read() ............................96
USB_BULK_ReadOverlapped() .............97
USB_BULK_ReadTimed() ....................98
USB_BULK_Receive() ....................... 101
USB_BULK_SetOnRXHook ..................99
USB_BULK_WaitForRX() ................... 102
USB_BULK_WaitForTX() ................... 103
USB_BULK_Write() .......................... 104
USB_BULK_WriteEx() ....................... 105
USB_BULK_WriteExTimed() .............. 106
USB_BULK_WriteNULLPacket() .......... 110
USB_BULK_WriteOverlapped() ... 107–108
USB_BULK_WriteTimed() .................. 108
USB_ON_RX_FUNC .......................... 112
Bulk Communication(Host)
USBBULK_Close() .....................118, 148
USBBULK_CloseEx() ........................ 119
USBBULK_GetConfigDescriptor() ....... 128
USBBULK_GetConfigDescriptorEx() ... 129,
159
USBBULK_GetDriverCompileDate() ... 126,
177
USBBULK_GetDriverVersion() ... 127, 178–
179
USBBULK_GetMode() ....................... 130
USBBULK_GetModeEx() .............131, 160
USBBULK_GetNumAvailableDevices() 132,
180
USBBULK_GetReadMaxTransferSize() . 133
USBBULK_GetReadMaxTransferSizeEx() ...
134, ......................................... 161
USBBULK_GetSN() ...................135, 173
USBBULK_GetWriteMaxTransferSize() . 136
USBBULK_GetWriteMaxTransferSizeEx() ..
137, ......................................... 162
USBBULK_Open() .....................116, 147
USBBULK_OpenEx() ........................ 117
USBBULK_Read() .....................120, 152
USBBULK_ReadEx() ..................121, 153
USBBULK_SetMode() ....................... 138
USBBULK_SetModeEx() .............139, 165
USBBULK_SetTimeout() ................... 140
USBBULK_SetTimeoutEx() ................ 141
USBBULK_SetUSBId() ...............142, 151
USBBULK_Write() .....................122, 153
USBBULK_WriteEx() ........................ 123
USBBULK_WriteRead ................124, 154
USBBULK_WriteReadEx() ...........125, 159
C
"C" compiler ....................................... 26
CDC
USB_CDC_Add() ..............................280
USB_CDC_CancelRead() ...................281
USB_CDC_CancelReadEx ..................281
USB_CDC_CancelWrite() ...................282
USB_CDC_CancelWriteEx() ...............282
USB_CDC_INIT_DATA ......................301
USB_CDC_LINE_CODING ..................304
USB_CDC_ON_SET_LINE_CODING .....303
USB_CDC_Read() ............................283
USB_CDC_ReadEx() .........................283
USB_CDC_ReadOverlapped() ............284
USB_CDC_ReadOverlappedEx() .........284
USB_CDC_ReadTimed() ....................285
USB_CDC_ReadTimedEx() ................285
USB_CDC_Receive() ........................286
USB_CDC_ReceiveEx() .....................286
USB_CDC_ReceiveTimed() ................287
USB_CDC_ReceiveTimedEx() .............287
USB_CDC_SetLineCoding() ........289–290
USB_CDC_SetOnBreak .....................288
USB_CDC_SetOnBreakEx ..................288
USB_CDC_UpdateSerialState() ..........290
USB_CDC_UpdateSerialStateEx() .......290
USB_CDC_WaitForRX() .....................294
USB_CDC_WaitForRXEx() .................294
USB_CDC_WaitForTX() .....................295
USB_CDC_WaitForTXEx() ..................295
USB_CDC_Write() ............................291
USB_CDC_WriteEx() ........................291
USB_CDC_WriteOverlapped() ............292
USB_CDC_WriteSerialState() .............296
USB_CDC_WriteSerialStateEx() .........296
USB_CDC_WriteTimed() ...................293
USB_CDC_WriteTimedEx() ................293
E
embOS/IP
Integrating into your system .............. 40
F
FAQ ..................................................445
H
HID
USB_HID_Add() ..............................317
USB_HID_INIT_DATA .......................330
USB_HID_Read() .............................318
M
MSD
USB_MSD_Add() ..................... 192, 235
USB_MSD_AddCDRom() ...................194
USB_MSD_AddUnit() ................ 193, 236
USB_MSD_Connect() ............... 199, 202
USB_MSD_Disconnect() ....................200
USB_MSD_INFO ..............................206
USB_MSD_INIT_DATA ....... 205, 238–239
USB_MSD_INST_DATA ............. 207, 240
USB_MSD_RequestDisconnect() .........201
USB_MSD_SetPreventAllowRemovalHook()
195
USB_MSD_SetReadWriteHook() .........197
448 Index
UM09001 User & Reference Guide for emUSB © 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG
USB_MSD_Task() ..................... 198, 237
USB_MSD_WaitForDisconnection() .... 203
O
OS
USB_OS_DecRI() ............................ 397
USB_OS_Delay() ............................ 396
USB_OS_GetTickCnt() ..................... 398
USB_OS_IncDI() ............................. 399
USB_OS_Init() ............................... 400
USB_OS_Panic() ............................. 401
USB_OS_Signal() ............................ 402
USB_OS_Wait() .............................. 403
USB_OS_WaitTimed() ...................... 404
S
Support .................................... 433–446
Syntax, conventions used .......................7
U
USB Core
USB_AddDriver() .............................. 54
USB_AddEP() ................................... 61
USB_DoRemoteWakeup ..................... 75
USB_EnableIAD() .............................. 72
USB_GetState() ................................ 55
USB_IsConfigured() .......................... 57
USB_SetAddFuncDesc() ..................... 62
USB_SetAllowRemoteWakeUp() .......... 74
USB_SetClassRequestHook() .............. 63
USB_SetIsSelfPowered() .................... 65
USB_SetMaxPower() ......................... 66
USB_SetOnRxEP0() ........................... 67
USB_SetOnSetupHook() .................... 68
USB_StallEP() .................................. 70
USB_Start() ................................ 58–59
USB_WaitForEndOfTransfer() .............. 71
USB_GetProductId() ............................ 46
USB_GetProductName() ....................... 48
USB_GetSerialNumber() ....................... 49
USB_GetVendorId() ............................. 45
USB_GetVendorName() ........................ 47
USB_HW_DRIVER
(*pfAllocEP)() ................................. 425
(*pfAttach)() .................................. 423
(*pfDisableRxInterruptEP)() ............. 429
(*pfDisableTx)() ............................. 430
(*pfEnable)() ................................. 423
(*pfEnableRxInterruptEP)() .............. 429
(*pfGetMaxPacketSize)() ................. 425
(*pfInit)() ...................................... 422
(*pfSendEP)() ................................ 430
(*pfSetAddress)() .................... 423–424
(*pfSetClrStallEP)() .................. 426–427
(*pfStallEP0)() ............................... 428
(*pfUpdateEP)() ............................. 426
USB_HW_StartTx() ............................ 431
USB_Init() .......................................... 56
USB_MSD_INST_DATA_DRIVER ... 211, 241,
244
USB_MSD_STORAGE_API ............ 212, 242
(*pfDeInit)() ........................... 222, 260
(*pfGetInfo)() ......................... 216, 247
(*pfGetReadBuffer)() ................ 217, 248
(*pfGetWriteBuffer)() ............... 219, 250
(*pfInit)() ...............................215, 246
(*pfMediumIsPresent)() .... 221, 252–255,
258– ......................................... 259
(*pfRead)() ............................. 218, 249
(*pfWrite)() ...............220, 251, 256–257
USB_SetAllowRemoteWakeUp ...............74
USBHID_Close() ................................ 333
USBHID_Exit() .................................. 336
USBHID_GetInputReportSize() ............ 339
USBHID_GetNumAvailableDevices() ..... 337
USBHID_GetOutputReportSize() .......... 340
USBHID_GetProductId() ..................... 341
USBHID_GetProductName() ................ 338
USBHID_GetVendorId() ...................... 342
USBHID_Open() ................................ 334
USBHID_RefreshList() ........................ 343
USBHID_SetVendorPage() .................. 344