1 emUSB USB Device stack CPU-independent User & Reference Guide Document: UM09001 Software version: 2.50e Revision: 0 Date: January 23, 2015 A product of SEGGER Microcontroller GmbH & Co. KG www.segger.com UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 2 Disclaimer Specifications written in this document are believed to be accurate, but are not guaranteed 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 responsibility for any errors or omissions. SEGGER makes and you receive no warranties or conditions, express, implied, statutory or in any communication with you. SEGGER specifically disclaims any implied warranty of merchantability or fitness for a particular 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. (c) 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 respective 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 (c) 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 2.50e Revision 0 Date 150123 By YR Description 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 4 Software Revision Date By Description 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. YR Added the new Bulk Host API V2. Removed some typos. internal 0 130410 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. 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.34 0 111111 Added new functions in USB Core chapter: * USB_SetVendorRequestHook(), USB_SetIsSelfPowered() Updated the Product Ids in Chapter GettingTheTargetUp\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.32 0 101206 SR 2.30 0 101022 SR Added the function for remote wakeup. 2.27 0 100730 MD Chapter "Printer Class" added. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 5 Software Revision Date By Description 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.26 1 090127 SR 2.22 1 080917 Added new chapter Combining different USB components SR/ (Multi-Interface) SK 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. 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. 12.0 0 070706 UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 6 Software 11.0 10.0 9.0 Revision 0 0 0 Date 070704 070618 070123 By Description 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. SK Chapter "HID" added. Chapter "USB Core" added. Chapter "Bulk communication": * USB core functions removed. Chapter "Introduction": * Section "Development environment" added. 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 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. 5.0 0 061220 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 UM09001 User & Reference Guide for emUSB (c) 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 compiler) 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 Programming 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 documents. GUIElement Buttons, dialog boxes, menu names, menu commands. Emphasis Very important sections Table 1.1: Typographic conventions UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 8 SEGGER Microcontroller GmbH & Co. KG develops and distributes software development tools and ANSI C software components (middleware) for embedded systems 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 embedded 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 complemented 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 development, debugging and production, which has rapidly become the industry standard for debug access to ARM cores. Corporate Office: http://www.segger.com EMBEDDED SOFTWARE (Middleware) emWin Graphics software and GUI emWin is designed to provide an efficient, processor- and display controller-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. United States Office: http://www.segger-us.com SEGGER TOOLS Flasher Flash programmer Flash Programming tool primarily for micro controllers. 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 (Embedded Trace Macrocell). J-Link / J-Trace Related Software Add-on software to be used with SEGGER's industry standard JTAG emulator, this includes flash programming software and flash breakpoints. emFile File system emFile is an embedded file system with FAT12, FAT16 and FAT32 support. Various Device drivers, e.g. for NAND and NOR flashes, SD/MMC and CompactFlash cards, are available. USB-Stack USB device/host stack A USB stack designed to work on any embedded system with a USB controller. Bulk communication and most standard device classes are supported. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 9 Table of Contents 1 Introduction ....................................................................................................................15 1.1 1.2 1.3 1.3.1 1.3.1.1 1.3.2 1.3.2.1 1.3.2.2 1.3.2.3 1.3.2.4 1.3.3 1.3.3.1 1.3.4 1.3.4.1 1.3.5 1.3.5.1 1.3.6 1.3.6.1 1.3.7 1.3.7.1 1.4 1.4.1 1.4.2 1.5 1.5.1 1.5.2 1.5.3 1.5.4 Overview ................................................................................................ 16 emUSB features ...................................................................................... 16 emUSB components ................................................................................. 17 emUSB-Bulk ........................................................................................... 18 Purpose of emUSB-Bulk............................................................................ 18 emUSB-MSD ........................................................................................... 19 Purpose of emUSB-MSD ........................................................................... 19 Typical applications.................................................................................. 19 emUSB-MSD features............................................................................... 19 How does it work? ................................................................................... 19 emUSB-CDC ........................................................................................... 21 Typical applications.................................................................................. 21 emUSB-HID ............................................................................................ 22 Typical applications.................................................................................. 22 emUSB-MTP............................................................................................ 23 Typical applications.................................................................................. 23 emUSB-Printer ........................................................................................ 24 Typical applications.................................................................................. 24 emUSB-RNDIS ........................................................................................ 25 Typical applications.................................................................................. 25 Requirements.......................................................................................... 26 Target system ......................................................................................... 26 Development environment (compiler)......................................................... 26 File structure .......................................................................................... 27 Bulk communication component ................................................................ 28 MSD component ...................................................................................... 28 CDC component ...................................................................................... 28 HID component ....................................................................................... 28 2 Background information .................................................................................................31 2.1 2.1.1 2.1.2 2.1.3 2.1.4 2.1.5 2.1.6 2.2 2.3 2.4 USB ....................................................................................................... 32 Short Overview ....................................................................................... 32 Important USB Standard Versions.............................................................. 32 USB System Architecture .......................................................................... 33 Transfer Types ........................................................................................ 35 Setup phase / Enumeration....................................................................... 35 Product / Vendor IDs................................................................................ 35 Predefined device classes.......................................................................... 36 USB hardware analyzers ........................................................................... 36 References ............................................................................................. 36 3 Getting started ...............................................................................................................37 3.1 3.1.1 3.1.2 3.1.3 3.2 3.3 3.4 How to setup your target system ............................................................... 39 Upgrade a trial version available on the web with source code. ...................... 39 Upgrading an embOS Start project............................................................. 40 Creating a project from scratch ................................................................. 42 Select the start application........................................................................ 43 Build the project and test it....................................................................... 43 Configuration .......................................................................................... 44 UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 10 3.4.1 3.4.2 3.4.3 General emUSB configuration functions ...................................................... 45 Additional required configuration functions for emUSB-MSD .......................... 50 Descriptors............................................................................................. 50 4 USB Core.......................................................................................................................51 4.1 4.2 4.2.1 4.2.2 4.2.3 4.2.4 4.2.5 Overview ............................................................................................... 52 Target API.............................................................................................. 53 USB basic functions ................................................................................. 54 USB configuration functions ...................................................................... 61 USB control functions .............................................................................. 70 USB IAD functions ................................................................................... 72 USB Remote wakeup functions .................................................................. 73 5 Bulk communication.......................................................................................................77 5.1 5.2 5.2.1 5.2.2 5.3 5.3.1 5.3.2 5.3.3 5.4 5.4.1 5.4.2 5.5 5.5.1 5.5.2 5.5.3 5.6 5.6.1 5.6.2 5.6.3 5.6.4 Generic bulk stack................................................................................... 78 The Kernel mode driver (PC)..................................................................... 78 Why is a driver necessary? ....................................................................... 78 Supported platforms ................................................................................ 78 Installing the driver ................................................................................. 78 Recompiling the driver ............................................................................. 81 The .inf file............................................................................................. 82 Configuration.......................................................................................... 83 Example application................................................................................. 84 Running the example applications.............................................................. 85 Compiling the PC example application ........................................................ 87 Target API.............................................................................................. 88 Target interface function list ..................................................................... 89 USB-Bulk functions.................................................................................. 90 Data structures ......................................................................................111 Host API ...............................................................................................113 Host API list ..........................................................................................114 USB-Bulk Basic functions.........................................................................116 USB-Bulk direct input/output functions......................................................120 USB-Bulk Control functions......................................................................126 6 Bulk Host API V2 .........................................................................................................143 6.1 6.1.1 6.1.2 6.1.3 6.1.4 6.1.4.1 6.1.5 Bulk Host API V2 ....................................................................................144 Bulk Host API V2 list...............................................................................145 USB-Bulk Basic functions.........................................................................147 USB-Bulk direct input/output functions......................................................152 USB-Bulk Control functions......................................................................159 USBBULK_GetConfigDescriptor() ..............................................................159 Data structures ......................................................................................182 7 Mass Storage Device Class (MSD) ............................................................................183 7.1 7.2 7.2.1 7.2.2 7.2.3 7.2.4 7.2.4.1 7.3 7.3.1 7.3.2 7.3.3 7.4 7.4.1 7.4.1.1 Overview ..............................................................................................184 Configuration.........................................................................................185 Initial configuration ................................................................................185 Final configuration..................................................................................185 Class specific configuration functions ........................................................185 Running the example application ..............................................................190 MSD_Start_StorageRAM.c in detail ...........................................................190 Target API.............................................................................................191 API functions .........................................................................................192 Extended API functions ...........................................................................199 Data structures ......................................................................................205 Storage Driver .......................................................................................214 General information................................................................................214 Supported storage types .........................................................................214 User & reference manual for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 11 7.4.1.2 7.4.2 7.4.3 Storage drivers supplied with this release ................................................. 214 Interface function list ............................................................................. 214 USB_MSD_STORAGE_API in detail ........................................................... 215 8 Media Transfer Protocol Class (MTP)..........................................................................223 8.1 8.1.1 8.1.2 8.2 8.2.1 8.2.2 8.2.3 8.2.4 8.3 8.3.1 8.4 8.4.1 8.4.2 8.5 8.5.1 8.5.2 8.5.3 Overview .............................................................................................. 224 Getting access to files ............................................................................ 225 Additional information ............................................................................ 227 Configuration ........................................................................................ 228 Initial configuration................................................................................ 228 Final configuration ................................................................................. 228 Class specific configuration ..................................................................... 228 Compile time configuration ..................................................................... 233 Running the sample application ............................................................... 233 USB_MTP_Start.c in detail ...................................................................... 233 Target API ............................................................................................ 235 API functions ........................................................................................ 235 Data structures ..................................................................................... 238 Storage Driver ...................................................................................... 245 General information ............................................................................... 245 Interface function list ............................................................................. 245 USB_MTP_STORAGE_API in detail ............................................................ 246 9 Communication Device Class (CDC)...........................................................................267 9.1 9.1.1 9.2 9.3 9.3.1 9.3.2 9.3.3 9.4 9.4.1 9.4.2 9.4.3 Overview .............................................................................................. 268 Configuration ........................................................................................ 268 The example application ......................................................................... 269 Installing the driver ............................................................................... 270 The .inf file ........................................................................................... 273 Installation verification ........................................................................... 274 Testing communication to the USB device ................................................. 275 Target API ............................................................................................ 278 Interface function list ............................................................................. 279 API functions ........................................................................................ 280 Data structures ..................................................................................... 301 10 Human Interface Device Class (HID).........................................................................307 10.1 10.1.1 10.1.2 10.1.2.1 10.1.2.2 10.2 10.2.1 10.2.1.1 10.2.1.2 10.2.1.3 10.3 10.3.1 10.3.2 10.4 10.4.1 10.4.1.1 10.4.2 10.4.2.1 10.4.2.2 10.5 10.5.1 10.5.2 10.5.3 Overview .............................................................................................. 308 Further reading ..................................................................................... 308 Categories ............................................................................................ 309 True HIDs............................................................................................. 309 Vendor specific HIDs .............................................................................. 309 Background information ......................................................................... 310 HID descriptors ..................................................................................... 310 HID descriptor....................................................................................... 310 Report descriptor................................................................................... 310 Physical descriptor ................................................................................. 311 Configuration ........................................................................................ 312 Initial configuration................................................................................ 312 Final configuration ................................................................................. 312 Example application ............................................................................... 313 HID_Mouse.c ........................................................................................ 313 Running the example ............................................................................. 313 HID_Echo1.c ......................................................................................... 314 Running the example ............................................................................. 314 Compiling the PC example application ...................................................... 315 Target API ............................................................................................ 316 Target interface function list.................................................................... 316 USB-HID functions................................................................................. 317 Data structures ..................................................................................... 330 UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller Systeme GmbH 12 10.6 10.6.1 10.6.2 Host API ...............................................................................................331 Host API function list ..............................................................................332 USB-HID functions .................................................................................333 11 Printer Class ..............................................................................................................345 11.1 11.1.1 11.2 11.3 11.3.1 11.3.2 11.3.3 Overview ..............................................................................................346 Configuration.........................................................................................346 The example application..........................................................................347 Target API.............................................................................................350 Interface function list..............................................................................350 API functions .........................................................................................351 Data structures ......................................................................................353 12 Remote NDIS (RNDIS) ..............................................................................................355 12.1 12.1.1 12.1.2 12.2 12.2.1 12.2.2 12.2.3 12.2.4 12.3 12.3.0.1 12.4 12.5 12.5.1 12.5.1.1 12.5.1.2 12.5.2 12.5.2.1 12.5.2.2 12.5.2.3 12.5.2.4 Overview ..............................................................................................356 Working with RNDIS ...............................................................................356 Additional information.............................................................................357 Configuration........................................................................................358 Initial configuration ................................................................................358 Final configuration..................................................................................358 Class specific configuration ......................................................................358 Compile time configuration ......................................................................362 Running the sample application................................................................363 IP_Config_RNDIS.c in detail.....................................................................363 RNDIS + embOS/IP as a "USB Webserver" ................................................365 Target API.............................................................................................366 API functions .........................................................................................367 USB_RNDIS_Add() .................................................................................367 USB_RNDIS_Task() ................................................................................368 Data structures ......................................................................................369 USB_RNDIS_INIT_DATA .........................................................................369 USB_RNDIS_EVENT_API .........................................................................370 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 USB_RNDIS_DRIVER_DATA .....................................................................377 (*pfCreate)().........................................................................................378 (*pfSignal)() .........................................................................................378 (*pfWaitTimed)() ...................................................................................379 13 Combining different USB components (Multi-Interface).............................................381 13.1 13.1.1 13.1.2 13.1.3 13.2 13.3 13.4 13.4.1 13.4.1.1 13.4.1.2 13.4.2 Overview ..............................................................................................382 Single interface device classes .................................................................383 Multiple interface device classes ...............................................................384 IAD class ..............................................................................................384 Configuration.........................................................................................385 How to combine .....................................................................................386 emUSB component specific modification ....................................................388 BULK communication component..............................................................388 Device side............................................................................................388 Host side ..............................................................................................388 MSD component.....................................................................................390 User & reference manual for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 13 13.4.2.1 13.4.2.2 13.4.3 13.4.3.1 13.4.3.2 13.4.4 13.4.4.1 13.4.4.2 Device side ........................................................................................... 390 Host side .............................................................................................. 390 CDC component .................................................................................... 390 Device side ........................................................................................... 390 Host side .............................................................................................. 390 HID component ..................................................................................... 392 Device side ........................................................................................... 392 Host side .............................................................................................. 392 14 Target OS Interface ...................................................................................................393 14.1 14.1.1 14.2 14.3 General information ............................................................................... 394 Operating system support supplied with this release................................... 394 Interface function list ............................................................................. 395 Example ............................................................................................... 405 15 Target USB Driver......................................................................................................409 15.1 15.1.1 15.2 15.3 15.3.1 15.3.1.1 15.3.1.2 15.3.1.3 15.3.1.4 15.3.1.5 15.3.1.6 15.3.1.7 15.3.1.8 15.3.1.9 15.3.1.10 15.3.1.11 15.3.1.12 15.3.1.13 15.3.1.14 15.3.1.15 15.3.1.16 15.3.1.17 15.3.1.18 15.4 15.4.1 15.4.2 15.4.3 15.4.4 15.4.5 15.4.6 15.4.7 General information ............................................................................... 410 Available USB drivers ............................................................................. 410 Adding a driver to emUSB....................................................................... 412 Interrupt handling ................................................................................. 415 ARM7 / ARM9 based cores ...................................................................... 415 ARM specific IRQ handler ........................................................................ 416 Device specifics ATMEL AT91CAP9x .......................................................... 417 Device specifics ATMEL AT91RM9200........................................................ 417 Device specifics ATMEL AT91SAM7A3 ....................................................... 417 Device specifics ATMEL AT91SAM7S64, AT91SAM7S128, AT91SAM7S256...... 417 Device specifics ATMEL AT91SAM7X64, AT91SAM7X128, AT91SAM7X256...... 417 Device specifics ATMEL AT91SAM7SE ....................................................... 417 Device specifics ATMEL AT91SAM9260...................................................... 417 Device specifics ATMEL AT91SAM9261...................................................... 417 Device specifics ATMEL AT91SAM9263...................................................... 418 Device specifics ATMEL AT91SAMRL64, AT91SAMR64 ................................. 418 Device specifics NXP LPC214x ................................................................. 419 Device specifics NXP LPC23xx.................................................................. 419 Device specifics NXP (formerly Sharp) LH79524/5 ...................................... 419 Device specifics OKI 69Q62..................................................................... 419 Device specifics ST STR71x ..................................................................... 419 Device specifics ST STR750..................................................................... 419 Device specifics ST STR750..................................................................... 419 Writing your own driver .......................................................................... 420 USB initialization functions ...................................................................... 422 General USB functions............................................................................ 423 General endpoint functions ..................................................................... 425 Endpoint 0 (control endpoint) related functions.......................................... 428 OUT-endpoint functions .......................................................................... 429 IN-endpoint functions............................................................................. 430 USB driver interrupt handling .................................................................. 432 16 Support ......................................................................................................................433 16.1 16.1.1 16.1.2 16.1.3 16.1.4 16.2 16.3 Problems with tool chain (compiler, linker) ................................................ 434 Compiler crash ...................................................................................... 434 Compiler warnings ................................................................................. 434 Compiler errors ..................................................................................... 434 Linker problems .................................................................................... 434 Problems with hardware/driver ................................................................ 435 Contacting support ................................................................................ 435 17 Certification ................................................................................................................437 17.1 What is the Windows Logo Certification and why UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller Systeme GmbH 14 17.2 17.3 17.4 do I need it?438 Certification offer ...................................................................................439 Vendor and Product ID............................................................................439 Certification without SEGGER Microcontroller .............................................439 18 Performance & resource usage .................................................................................441 18.1 18.1.1 18.1.2 18.2 Memory footprint ...................................................................................442 ROM .....................................................................................................442 RAM .....................................................................................................442 Performance ..........................................................................................443 19 FAQ............................................................................................................................445 User & reference manual for emUSB (c) 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 16 CHAPTER 1 1.1 Introduction 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 controller. 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 automatically handled. Using USB high speed mode with an ARM9 or faster could achieve values of approx. 18 MBytes/second and faster. The USB standard defines four types of communication: Control, isochronous, interrupt, 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 (c) 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 communication 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 Bulk MSD CDC HID MTP Printer RNDIS emUSB-Core Driver Description USB protocol layer emUSB bulk component. (emUSB-Bulk) emUSB Mass Storage Device class component. (emUSB-MSD). emUSB Communication Device Class component. (emUSB-CDC) emUSB Human Interface Device Class component. (emUSB-HID) emUSB Media Transfer Protocol component. (emUSB-MTP) emUSB Printer Class component. (emUSB-Printer) emUSB RNDIS component. (emUSB-RNDIS) Core layer The emUSB core is the intrinsic USB stack. Hardware layer USB controller driver. Table 1.1: emUSB components UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 18 CHAPTER 1 1.3.1 Introduction 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 target, 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 (c) 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 possible 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 storage 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) transfer 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 implementation. 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 UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 20 CHAPTER 1 Introduction complex and time-consuming task and increases the time-to market. Thus we recommend 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 (c) 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 UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 22 CHAPTER 1 1.3.4 Introduction 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 drivers 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 (c) 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 transfer 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 24 CHAPTER 1 1.3.6 Introduction emUSB-Printer emUSB-Printer converts the target device into a printing device. A target device running emUSB-Printer is recognized by the host as a printer. Unless the device identifies 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 (c) 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 webserver or act as a telnet terminal or a FTP server. emUSB-RNDIS offer a unique customer 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 UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 26 CHAPTER 1 1.4 Introduction 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 onboard 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 switchable 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 integration 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 therefore also be programmed in C++ if desired. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 27 1.5 File structure The following table shows the contents of the emUSB root directory: Directory Contents Application Contains the application program. Depending on which stack is used, several files are available for each stack. Detailed information 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. Contains the emUSB source code. USB Note: Do not change the source code in this directory. Table 1.2: Supplied directory structure of emUSB core package Depending on the chosen emUSB component, the following additional subdirectories are available: UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 28 CHAPTER 1 1.5.1 Introduction Bulk communication component Directory Contents Bulk\WindowsDriver 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\SampleApp 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 communication. Table 1.3: Additional subdirectories for emUSB bulk communication component 1.5.2 MSD component Directory USB\MSD Contents 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 1.5.3 CDC 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 1.5.4 HID 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 (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 29 UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 30 UM09001 User & Reference Guide for emUSB CHAPTER 1 Introduction (c) 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 32 CHAPTER 2 2.1 Background information USB 2.1.1 Short Overview The Universal Serial Bus (USB) is a bus architecture for connecting multiple peripherals to a host computer. It is an industry standard -- maintained by the USB Implementers Forum -- and because of its many advantages it enjoys a huge industry-wide acceptance. Over the years, a number of USB-capable peripherals appeared on the market, for example printers, keyboards, mice, digital cameras etc. Among the top benefits of USB are: * * * * * * * Excellent plug-and-play capabilities allow devices to be added to the host system without reboots ("hot-plug"). Plugged-in devices are identified by the host and the appropriate drivers are loaded instantly. USB allows easy extensions of host systems without requiring host-internal extension cards. Device bandwidths may range from a few Kbytes/second to hundreds of Mbytes/ second. A wide range of packet sizes and data transfer rates are supported. USB provides internal error handling. Together with the already mentioned hotplug 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 several 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 SuperSpeed, which offers a maximum rate of 5 Gbit/s. UM09001 User & Reference Guide for emUSB (c) 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 controller 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 34 CHAPTER 2 Background information 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 communicate 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. Device descriptor 1...n configurat ion descriptors Configuration descriptor 1...m interf ace descriptors Interface descriptor 1...o endpoint descript ors Endpoint descriptor 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. UM09001 User & Reference Guide for emUSB (c) 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 constant data rate. Interrupt transfers Typically used by devices that need guaranteed quick responses (bounded latency). Bulk transfers Typically used by devices that generate or consume data in relatively large and bursty quantities. Bulk transfer has wide dynamic latitude in transmission constraints. It can use all remaining available bandwidth, but with no guarantees on bandwidth or latency. Because the USB bus is normally not very busy, there is typically 90% or more of the bandwidth available for USB transfers. 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 finished; 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 36 CHAPTER 2 2.2 Background information 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: * * * * 2.3 Mass Storage Device Class (MSD) Human Interface Device Class (HID) Communication Device Class (CDC) Printer Device Class (PDC) 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 Specification, Rev 1.0 UM09001 User & Reference Guide for emUSB (c) 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 38 UM09001 User & Reference Guide for emUSB CHAPTER 3 Getting started (c) 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 UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 40 CHAPTER 3 Getting started 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 (R) 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 (c) 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 applications. Add the hardware configuration USB_Config_.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 optimized 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 directory 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 UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 42 CHAPTER 3 3.1.3 Getting started 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 target 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 (c) 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 configuration 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 44 3.4 CHAPTER 3 Getting started Configuration An application using emUSB must contain the following functions: 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 required 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 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. Ids 0x8765 0x1234 0x1000 0x1200 0x1111 0x1112 0x1114 0x2114 Description Default vendor Id for all applications Example vendor Id for all examples. Used product Ids Example product Id for all bulk samples. Example product Id for all MSD samples. Example product Id for the MSD CD-ROM sample. Example product Id for all CDC samples. Example product Id for HID mouse sample. Example product Id for the vendor specific HID sample. Example product Id for the Printer class sample. Table 3.2: List of used product and vendor Ids UM09001 User & Reference Guide for emUSB (c) 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 vendor 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 46 CHAPTER 3 Getting started 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 identifier. For tests, you can use the default number above (or pretty much any other number). 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 (c) 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 48 CHAPTER 3 Getting started 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 (c) 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 50 CHAPTER 3 3.4.2 MSD Getting started Additional required configuration functions for emUSB- Refer to Configuration on page 185 for more information about the required additional 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 (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 51 Chapter 4 USB Core This chapter describes the basic functions of the USB Core. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 52 CHAPTER 4 4.1 USB Core 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 component. Target USB components USB class drivers Bulk Printer MSD CDC HID emUSB Core Driver General information To communicate with the host, the example application project includes a USB-specific 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. 2. 3. 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. 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 structures 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. Start the USB stack. Call USB_Start() to start the USB stack. Example applications for every supported USB class and the unclassified bulk component 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. UM09001 User & Reference Guide for emUSB (c) 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 Adds a USB device driver to the emUSB USB_AddDriver() 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 Returns an endpoint "handle" that can be USB_AddEP() used for the desired USB interface. Sets a callback for setting additional USB_SetAddFuncDesc() information into the configuration descriptor. Sets a callback to handle class setup USB_SetClassRequestHook() requests. Sets a callback to handle vendor setup USB_SetVendorRequestHook() requests. Sets whether the device is self-powered USB_SetIsSelfPowered() or not. Sets the target device current consumpUSB_SetMaxPower() tion. Sets a callback to handle data read of USB_SetOnRxEP0() endpoint 0. Sets a callback to handle EP0 setup packUSB_SetOnSetupHook() 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 Allows to combine multi-interface device USB_EnableIAD() classes with single-interface classes. USB RemoteWakeUp functions Allows the device to publish that remote USB_SetAllowRemoteWakeUp() wake is available. USB_DoRemoteWakeup() Performs a remote wakeup to the host. Table 4.1: Target USB Core interface function list UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 54 CHAPTER 4 4.2.1 USB Core 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 (c) 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. USB state flags USB_STAT_ATTACHED USB_STAT_READY USB_STAT_ADDRESSED USB_STAT_CONFIGURED USB_STAT_SUSPENDED Device Device Device Device Device is is is is is attached. (Note 1) ready. addressed. configured. suspended. 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 connected 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 56 CHAPTER 4 USB Core 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 (c) 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 58 CHAPTER 4 USB Core 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 (c) 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); UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 60 CHAPTER 4 USB Core 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 (c) 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); Parameter InDir TransferType Interval pBuffer BufferSize Description Specifies the direction of the desired endpoint. 1 - IN 0 - OUT Specifies the transfer type of the endpoint. The following values are allowed: USB_TRANSFER_TYPE_BULK USB_TRANSFER_TYPE_ISO USB_TRANSFER_TYPE_INT Specifies the interval in microframes [0.125 s] for the endpoint. This value can be zero for a bulk endpoint. Pointer to a buffer that is used for OUT-transactions. For IN-endpoints this parameter must be NULL. Size of the buffer. Table 4.2: USB_AddEP() parameter list Return value On success: A valid endpoint handle is returned. On failure: 0 is returned. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 62 CHAPTER 4 USB Core 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); Parameter pfAddDescFunc Description Pointer to a function that should be called when building the configuration descriptor. Table 4.3: USB_SetAddFuncDesc() parameter list Additional information USB_ADD_FUNC_DESC is defined as follows: typedef void USB_ADD_FUNC_DESC(USB_INFO_BUFFER * pInfoBuffer); UM09001 User & Reference Guide for emUSB (c) 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); Parameter Interface pfOnClassrequest Description Specifies the Interface number of the class on which the hook shall be installed. Pointer to a function that should be called when a setup class request/packet is received. Table 4.4: USB_SetClassRequestHook() parameter list 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 * pSetupPacket); UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 64 CHAPTER 4 USB Core 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); Parameter Interface pfOnClassrequest Description Specifies the Interface number of the class on which the hook shall be installed. Pointer to a function that should be called when a setup vendor request/packet is received. Table 4.5: USB_SetClassRequestHook() parameter list 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 * pSetupPacket); UM09001 User & Reference Guide for emUSB (c) 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); Parameter IsSelfPowered Description 0 - Device is not self-powered. 1 - Device is self-powered. Table 4.6: USB_SetClassRequestHook() parameter list Additional information This function shall be called before USB_Start(), as it will specify if the device is selfpowered or not. The default value is 0 (not self-powered). UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 66 CHAPTER 4 USB Core 4.2.2.6 USB_SetMaxPower() Description Sets the maximum power consumption reported to the host during enumeration. Prototype void USB_SetMaxPower(U8 MaxPower); Parameter MaxPower Description Specifies the max power consumption given in mA. MaxPower shall be in range between 0mA - 500mA. Table 4.7: USB_SetClassRequestHook() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 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); Parameter pfOnRx Description Pointer to a function that should be called when receiving data other than setup packets. Table 4.8: USB_SetOnRxEP0() parameter list 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); UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 68 CHAPTER 4 USB Core 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); Parameter Interface pfOnClassrequest Description Specifies the Interface number of the class on which the hook shall be installed. Pointer to a function that should be called when a setup class request/packet is received. Table 4.9: USB_SetClassRequestHook() parameter list 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); UM09001 User & Reference Guide for emUSB (c) 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 pData NumBytes Send0PacketIfRequ ired Description Data that should be written. Number of bytes to write. 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 UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 70 CHAPTER 4 4.2.3 USB Core USB control functions 4.2.3.1 USB_StallEP() Description Stalls an endpoint. Prototype void USB_StallEP(U8 EPIndex); Parameter EPIndex Description Endpoint handle that needs to be stalled. Table 4.11: USB_StallEP() parameter list UM09001 User & Reference Guide for emUSB (c) 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 EPIndex Description Endpoint handle to wait for end of transfer. Table 4.12: USB_WaitForEndOfTransfer() parameter list UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 72 CHAPTER 4 4.2.4 USB Core 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 descriptor 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 possible to add an interface which does not belong to the CDC class, but it may be correctly recognized by the host. In order to allow this, a new descriptor type was introduced: IAD (Interface Association Descriptor), this descriptor will encapsulate the multiinterface 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 (c) 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 74 CHAPTER 4 USB Core 4.2.5.1 USB_SetAllowRemoteWakeUp() Description Allows the device to publish that remote wake is available. Prototype void USB_SetAllowRemoteWakeUp(U8 AllowRemoteWakeup); Parameter AllowRemoteWakeup Description 1 - Allows and publishes that remote wakeup is available. 0 - Publish that remote wakeup is not available. Table 4.13: USB_SetAllowRemoteWakeUp() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 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 UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 76 UM09001 User & Reference Guide for emUSB CHAPTER 4 USB Core (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 77 Chapter 5 Bulk communication This chapter describes how to get emUSB-Bulk up and running. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 78 CHAPTER 5 5.1 Bulk communication 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 modification. 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 storage (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 supplied 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 computer is first powered up after connecting the emUSB device, Windows will detect the new hardware. UM09001 User & Reference Guide for emUSB (c) 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 80 CHAPTER 5 Bulk communication 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 wizard. UM09001 User & Reference Guide for emUSB (c) 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 82 CHAPTER 5 5.3.2 Bulk communication 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 (c) 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 84 5.4 CHAPTER 5 Bulk communication 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. Host (PC) USB bulk example application. (for example: Echo1.exe) USB connection Target programmed with the example application consistent with the application running on host side Target (for example: BULK_Echo1.c). 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 downloaded into your target.) There are additional examples that can be used for testing emUSB. The following start application files are provided: 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 different packet sizes received from and sent to the PC host. Table 5.1: Supplied sample applications The example applications for the target-side are supplied in source code in the Application directory. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 85 Depending on which application is running on the emUSB device, use one of the following example applications: 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 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 program. 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: UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 86 CHAPTER 5 Bulk communication Example output of EchoFast.exe: Example output of Test.exe: If the host example application can communicate with the emUSB device, the example application will be in interactive mode for the Echo1 and the EchoFast application. 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 connection is faulty. Could not write to device The PC sample application was not able to write one byte. Could not read from device (timeout) 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 (c) 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\SAMPLEAPP. Open the file USBBULK_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). UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 88 5.5 CHAPTER 5 Bulk communication 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 (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 89 5.5.1 Target interface function list Routine Explanation USB-Bulk functions Adds an USB-Bulk interface to emUSB. Cancels a non-blocking read operation USB_BULK_CancelRead() that is pending. Cancels a non-blocking write operation USB_BULK_CancelWrite() that is pending. Returns the number of byte in BULK-OUT USB_BULK_GetNumBytesInBuffer() buffer. Returns the number of bytes which have USB_BULK_GetNumBytesRemToRead() to be read. Returns the number of bytes which have USB_BULK_GetNumBytesToWrite() to be written. USB_BULK_Read() USB-Bulk read. Non-blocking version of USB_BULK_ReadOverlapped() USB_BULK_Read(). Starts a read operation that shall be done USB_BULK_ReadTimed() within a given timeout. Read data from host and return immediUSB_BULK_Receive() ately as soon as data has been received. Installs a hook that shall be called when USB_BULK_SetOnRXHook() an USB packet is received. Checks whether the IN endpoint is curUSB_BULK_TxIsPending() rently pending. Waits for a non-blocking write operation USB_BULK_WaitForTX() that is pending. Waits for a non-blocking write operation USB_BULK_WaitForRX() that is pending. USB_BULK_Write() Starts a blocking write operation. Starts a blocking write operation that USB_BULK_WriteEx() allows to specify whether a NULL packet shall be sent or not. Starts an USB-Bulk WriteEx operation USB_BULK_WriteExTimed() that shall be done within a given timeout. Non-blocking version of USB_BULK_WriteOverlapped() USB_Bulk_Write(). USB_BULK_WriteOverlappedEx() Sends a NULL (zero-length) packet to USB_BULK_WriteNULLPacket() host. Starts an USB-Bulk Write operation that USB_BULK_WriteTimed() shall be done within a given timeout. Data structures Initialization structure which is required USB_BULK_INIT_DATA when adding a bulk interface. USB_ON_RX_FUNC Function called when data is received. USB_BULK_Add() Table 5.4: Target interface function list UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 90 CHAPTER 5 5.5.2 Bulk communication 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 ); Parameter pInitData Description Pointer to USB_BULK_INIT_DATA structure. Table 5.5: USB_BULK_Add() parameter list 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 }; UM09001 User & Reference Guide for emUSB (c) 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 92 CHAPTER 5 Bulk communication 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 (c) 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 available 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). UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 94 CHAPTER 5 Bulk communication 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 (c) 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 96 CHAPTER 5 Bulk communication 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); Parameter pData NumBytes Description Pointer to a buffer where the received data will be stored. Number of bytes to read. Table 5.6: USB_BULK_Read() parameter list Return value Number of bytes that have been received. In case of an error -1 is returned. UM09001 User & Reference Guide for emUSB (c) 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); Parameter pData NumBytes Description Pointer to a buffer where the received data will be stored. Number of bytes to read. Table 5.7: USB_BULK_ReadOverlapped() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 98 CHAPTER 5 Bulk communication 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); Parameter pData NumBytes ms Description Pointer to a buffer where the received data will be stored. Number of bytes to read. timeout given in milliseconds. Table 5.8: USB_BULK_ReadTimed() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 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); Parameter pfOnRx Description Pointer to the callback function. Table 5.9: USB_BULK_SetOnRXHook() parameter list Additional information Setting up a callback function may be necessary to allow a monitoring task to suspend 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 100 CHAPTER 5 Bulk communication 5.5.2.11 USB_BULK_TxIsPending() Description Checks whether the TX (IN endpoint) is currently pending. Can be called in any context. 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 (c) 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); Parameter pData NumBytes Description Pointer to a buffer where the received data will be stored. Maximum number of bytes to read. Table 5.10: USB_BULK_Receive() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 102 CHAPTER 5 Bulk communication 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 (c) 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 104 CHAPTER 5 Bulk communication 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); Parameter pData NumBytes Description Data that should be written. Number of bytes to write. Table 5.11: USB_BULK_Write() parameter list Return value > 0 Number of bytes that have been written. 0 Error. UM09001 User & Reference Guide for emUSB (c) 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); Parameter pData NumBytes Send0PacketIfRequired Description Pointer to a buffer that contains the written data. Number of bytes to write. 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 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 transmission. 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); } UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 106 CHAPTER 5 Bulk communication 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* unsigned char unsigned pData, NumBytes, Send0PacketIfRequired ms); Parameter pData NumBytes Send0PacketIfRequired ms Description Pointer to a buffer that contains the written data. Number of bytes to write. Specifies that a zero-length packet shall be sent when the last data packet to the host is a multiple of MaxPacketSize. Normally MaxPacketSize for full-speed devices is 64 byte. For high-speed devices the normal packet size is between 64-512 bytes. timeout Table 5.13: USB_BULK_WriteExTimed() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 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); Parameter pData NumBytes Description Pointer to data that should be sent to the host. Number of bytes to write. Table 5.14: USB_BULK_WriteOverlapped() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 108 CHAPTER 5 Bulk communication 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); Parameter pData NumBytes Send0PacketIfRequired Description Pointer to data that should be sent to the host. Number of bytes to write. Specifies that a zero-length packet shall be sent when the last data packet to the host is a multiple of MaxPacketSize. 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 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. UM09001 User & Reference Guide for emUSB (c) 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); Parameter pData NumBytes ms Description Pointer to a buffer that contains the written data. Number of bytes to write. timeout Table 5.16: USB_BULK_ReadOverlapped() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 110 CHAPTER 5 Bulk communication 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 necessary 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 (c) 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 emUSBBulk. Prototype typedef struct { U8 EPIn; U8 EPOut; } USB_BULK_INIT_DATA; Member EPIn EPOut Description Endpoint for sending data to the host. Endpoint for receiving data from the host Table 5.17: USB_BULK_INIT_DATA elements 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); } UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 112 CHAPTER 5 Bulk communication 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 pData NumBytes Description Pointer to the data that have been received. Number of bytes that have been received. Table 5.18: USB_ON_RX_FUNC elements UM09001 User & Reference Guide for emUSB (c) 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 114 CHAPTER 5 5.6.1 Bulk communication Host API list The functions below are available on the host (Windows PC) side. Function Description USB-Bulk basic functions Opens pipes to communicate with the USBBULK_Open() first USB-Bulk device. Opens pipes to communicate with a specUSBBULK_OpenEx() ified USB-Bulk device. Closes the pipes which are used for the USBBULK_Close() communication with the first USB-Bulk device. Closes the pipes which are used for the USBBULK_CloseEx() communication to a specified USB-Bulk device. USB-Bulk direct input/output functions Reads data from the first USB-Bulk USBBULK_Read() device. Reads data from a specified USB-Bulk USBBULK_ReadEx() device. USBBULK_Write() Writes data to the first USB-Bulk device. Writes data to a specified USB-Bulk USBBULK_WriteEx() device. Reads and writes data from/to the first USBBULK_WriteRead() USB-Bulk device. Reads and writes data from/to a specified USBBULK_WriteReadEx() USB-Bulk device. USB-Bulk control functions Gets the compile date and time of the USBBULK_GetDriverCompileDate() USB-Bulk driver. Retrieves the version of the USB-Bulk USBBULK_GetDriverVersion() driver. Gets the received target USB configuraUSBBULK_GetConfigDescriptor() tion descriptor of the first USB-Bulk device. Gets the received target USB configuraUSBBULK_GetConfigDescriptorEx() tion descriptor of a specified USB-Bulk device. Returns the read operation mode of the USBBULK_GetMode() USB-Bulk device. Returns the read operation mode of the USBBULK_GetModeEx() USB-Bulk driver. Returns the number of connected USBUSBBULK_GetNumAvailableDevices() Bulk devices. Retrieves the maximum transfer size of a USBBULK_GetReadMaxTransferSize() read transaction the driver can receive from an application. Retrieves the maximum transfer size of a USBBULK_GetReadMaxTransferSizeEx() read transaction the driver can receive from an application. Returns the serial number of the USB tarUSBBULK_GetSN() get device. Retrieves the maximum transfer size of a USBBULK_GetWriteMaxTransferSize() write transaction the driver can handle from an application. Table 5.19: Host API function list UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 115 Function Description Retrieves the maximum transfer size of a USBBULK_GetWriteMaxTransferSizeEx() write transaction the driver can handle from an application. Sets the read operation mode of the USBBULK_SetMode() USB-Bulk driver. Sets the read operation mode of the USBBULK_SetModeEx() USB-Bulk driver. Sets a read timeout for a read transacUSBBULK_SetTimeout() tion. Sets a read timeout for a read transacUSBBULK_SetTimeoutEx() tion. Sets the vendor Id and product id that USBBULK_SetUSBId() are used for connecting to the device. Table 5.19: Host API function list UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 116 CHAPTER 5 5.6.2 Bulk communication USB-Bulk Basic functions 5.6.2.1 USBBULK_Open() Description Opens a read and write connection to the first connected target device using emUSBBulk. 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 (c) 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 kernel-mode driver. Prototype void * USBBULK_OpenEx(unsigned Id); Parameter Id Description Id number of the device [0..31]. Table 5.20: USBBULK_OpenEx() parameter list 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 (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 118 CHAPTER 5 Bulk communication 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 (c) 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 Id Description Id number of the device [0..31]. Table 5.21: USBBULK_CloseEx() parameter list UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 120 CHAPTER 5 5.6.3 Bulk communication 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); Parameter pBuffer NumBytes Description Pointer to a buffer where the received data will be stored. Number of bytes to read. Table 5.22: USBBULK_Read() parameter list 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 NumBytes in chunks of the maximum read size the driver can handle. UM09001 User & Reference Guide for emUSB (c) 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); Parameter Id pBuffer NumBytes Description Id number of the device [0..31]. Pointer to a buffer where the received data will be stored. Number of bytes to read. Table 5.23: USBBULK_ReadEx() parameter list 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 NumBytes in chunks of the maximum read size the driver can handle. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 122 CHAPTER 5 Bulk communication 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); Parameter pBuffer NumBytes Description Pointer to a buffer to transfer. Number of bytes to write. Table 5.24: USBBULK_Write() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 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); Parameter Id pBuffer NumBytes Description Id number of device [0..31]. Pointer to a buffer to transfer. Number of bytes to write. Table 5.25: USBBULK_WriteEx() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 124 CHAPTER 5 Bulk communication 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); Parameter pWrBuffer WrNumBytes pRdBuffer RdNumBytes Description Pointer to a buffer to transfer. Number of bytes to write. Pointer to a buffer where the received data will be stored. Number of bytes to read. Table 5.26: USBBULK_WriteRead() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 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); Parameter Id pWrBuffer WrNumBytes pRdBuffer RdNumBytes Description Id number of device [0..31]. Pointer to a buffer to transfer. Number of bytes to write. Pointer to a buffer where the received data will be stored. Number of bytes to read. Table 5.27: USBBULK_WriteReadEx() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 126 CHAPTER 5 5.6.4 Bulk communication 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); Parameter s Size Description Pointer to a buffer to store the compile date string. Size, in bytes, of the buffer pointed to by s. Table 5.28: USBBULK_GetDriverCompileDate() parameter list Return value If the function succeeds, the return value is nonzero and the buffer pointed by s contains 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. UM09001 User & Reference Guide for emUSB (c) 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 decimal value: . 24201 means 2.42a If the function fails, the return value is zero; the version could not be retrieved. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 128 CHAPTER 5 Bulk communication 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); Parameter pBuffer Size Description Pointer to a buffer to store the config descriptor. Number of bytes to read. Table 5.29: USBBULK_GetConfigDescriptor() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 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); Parameter Id pBuffer Size Description Id number of the device [0..31]. Pointer to a buffer to store the config descriptor. Number of bytes to read. Table 5.30: USBBULK_GetConfigDescriptorEx() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 130 CHAPTER 5 Bulk communication 5.6.4.5 USBBULK_GetMode() Description Returns the read operation mode of the driver for the first device running emUSBBulk. 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 (c) 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 emUSBBulk. Prototype unsigned USBBULK_GetModeEx(unsigned Id); Parameter Id Description Id number of device [0..31]. Table 5.31: USBBULK_GetModeEx() parameter list 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 (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 132 CHAPTER 5 Bulk communication 5.6.4.7 USBBULK_GetNumAvailableDevices() Description Returns the number of connected USB-Bulk devices. Prototype unsigned USBBULK_GetNumAvailableDevices(U32 * pMask); Parameter pMask Description Pointer to a U32 variable to receive the connected device mask. This parameter can be NULL. Table 5.32: USBBULK_GetNumAvailableDevices() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 134 CHAPTER 5 Bulk communication 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); Parameter Id Description Id number of device [0..31]. Table 5.33: USBBULK_GetReadMaxTransferSizeEx() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 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); Parameter Id pBuffer NumBytes Description Id number of device [0..31]. Pointer to a buffer to store the serial number of the device. Size of the buffer in bytes. Table 5.34: USBBULK_GetSN() parameter list 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 emUSBBulk. If the function fails, the return value is zero. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 136 CHAPTER 5 Bulk communication 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 (c) 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); Parameter Id Description Id number of device [0..31]. Table 5.35: USBBULK_GetWriteMaxtransferSizeEx() parameter list 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 (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 138 CHAPTER 5 Bulk communication 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); Parameter Mode Description 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 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); } UM09001 User & Reference Guide for emUSB (c) 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 emUSBBulk. Prototype unsigned USBBULK_SetModeEx(unsigned Id, unsigned Mode); Parameter Id Mode Description Id of the device. 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 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); } UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 140 CHAPTER 5 Bulk communication 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 Timeout Description Timeout in milliseconds set for a read operation. Table 5.38: USBBULK_SetTimeout() parameter list UM09001 User & Reference Guide for emUSB (c) 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 Id Timeout Description Id number of device [0..31]. Timeout in milliseconds set for a read operation. Table 5.39: USBBULK_SetTimeOutEx() parameter list UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 142 CHAPTER 5 Bulk communication 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); Parameter VendorId ProductId Description The vendor ID that was assigned by USB.org. The product ID that is used for the device. Table 5.40: USBBULK_SetUSBId() parameter list 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 UM09001 User & Reference Guide for emUSB (c) 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 144 CHAPTER 6 6.1 Bulk Host API V2 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 (c) 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. Reads from an opened device with a USBBULK_ReadTimed() timeout. Writes data to the device with a timeUSBBULK_WriteTimed() out. USBBULK_FlushRx() Removes data from the receive buffer. USB-Bulk control functions Returns the configuration descriptor of USBBULK_GetConfigDescriptor() the device. Returns the transfer mode of the USBBULK_GetMode() device. Returns the max size the driver can USBBULK_GetReadMaxTransferSize() read at once. Returns the max size the driver can USBBULK_GetWriteMaxTransferSize() write at once. Resets the pipes that are opened to USBBULK_ResetPipe() the device. USBBULK_ResetDevice() Resets the device via a USB reset. Set the read and write mode of the USBBULK_SetMode() device. Set the read timeout for an opened USBBULK_SetReadTimeout() device. Set the write timeout for an opened USBBULK_SetWriteTimeout() device. Returns the time when the USB device USBBULK_GetEnumTickCount() has been enumerated. Returns the max read transfer size of USBBULK_GetReadMaxTransferSizeDown() the device. Returns the max write transfer size of USBBULK_GetWriteMaxTransferSizeDown() the device. Set the max read transfer size of the USBBULK_SetReadMaxTransferSizeDown() device. Set the max write transfer size of the USBBULK_SetWriteMaxTransferSizeDown() device. USBBULK_GetSN() Gets the serial number of the device. Retrieves information about an opened USBBULK_GetDevInfo() USBBULK device. USBBULK_GetProductName() Returns the product name. USBBULK_GetVendorName() Returns the vendor name. Table 6.1: Bulk Host API V2 function list UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 146 CHAPTER 6 Function Bulk Host API V2 Description USB-Bulk general GET functions USBBULK_GetDriverCompileDate() Gets the compile date of the driver. USBBULK_GetDriverVersion() Returns the driver version. USBBULK_GetVersion() Returns the USBBULK API version. Returns the number of available USBBULK_GetNumAvailableDevices() devices. Returns the set Product and Vendor USBBULK_GetUSBId() IDs. Data structures Device information structure (Vendor USBBULK_DEV_INFO ID, Product ID, SN, Device Name). Table 6.1: Bulk Host API V2 function list UM09001 User & Reference Guide for emUSB (c) 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); Parameter Description 0..31 Device Id to be opened. Id Table 6.2: USBBULK_Open() parameter list Return value != 0 == 0 - Handle to the opened device. - Device cannot be opened. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 148 CHAPTER 6 Bulk Host API V2 6.1.2.2 USBBULK_Close() Description Closes an opened device. Prototype USBBULK_API void WINAPI USBBULK_Close (USB_BULK_HANDLE hDevice); Parameter hDevice Description Handle to the device that shall be closed. Table 6.3: USBBULK_Close() parameter list UM09001 User & Reference Guide for emUSB (c) 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); Parameter pfNotification pContext Description Pointer to the user callback. Context data that shall be called with the callback function. Table 6.4: USBBULK_Init() parameter list 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); <...> } UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 150 CHAPTER 6 Bulk Host API V2 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 (c) 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); Parameter VendorId ProductId Description The desired Vendor ID mask that shall be used with the USBBULK API The desired Product ID mask that shall be used with the USBBULK API Table 6.5: USBBULK_SetUSBId() parameter list 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 UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 152 CHAPTER 6 6.1.3 Bulk Host API V2 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); Parameter hDevice pBuffer NumBytes Description Handle to the opened device. Pointer to a buffer that shall store the data. Number of bytes to be read. Table 6.6: USBBULK_Read() parameter list 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 NumBytes in chunks of the maximum read size the driver can handle. UM09001 User & Reference Guide for emUSB (c) 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); Parameter hDevice pBuffer NumBytes Description Handle to the opened device. Pointer to a buffer that contains the data. Number of bytes to be written. Table 6.7: USBBULK_Write() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 154 CHAPTER 6 Bulk Host API V2 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); Parameter hDevice pWrBuffer WrNumBytes pRdBuffer RdNumBytes Description Handle to the opened device. Pointer to a buffer that contains the data. Number of bytes to be written. Pointer to a buffer that shall store the data. Number of bytes to be read. Table 6.8: USBBULK_WriteRead() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 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 hDevice Description Handle to the opened device. Table 6.9: USBBULK_CancelRead() parameter list UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 156 CHAPTER 6 Bulk Host API V2 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); Parameter hDevice pBuffer NumBytes ms Description Handle to the opened device. Pointer to a buffer that shall store the data. Number of bytes to be read. Timeout in milliseconds. Table 6.10: USBBULK_ReadTimed() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 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); Parameter hDevice pBuffer NumBytes ms Description Handle to the opened device. Pointer to a buffer that contains the data. Number of bytes to be written. Timeout in milliseconds. Table 6.11: USBBULK_WriteTimed() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 158 CHAPTER 6 Bulk Host API V2 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 hDevice Description Handle to the opened device. Table 6.12: USBBULK_FlushRx() parameter list UM09001 User & Reference Guide for emUSB (c) 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); Parameter hDevice pBuffer Size Description Handle to an opened device. Pointer to the buffer that shall store the descriptor. Size of the buffer, given in bytes. Table 6.13: USBBULK_GetConfigDescriptor() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 160 CHAPTER 6 Bulk Host API V2 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); Parameter hDevice Description Handle to an opened device. Table 6.14: USBBULK_GetMode() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 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); Parameter hDevice Description Handle to an opened device. Table 6.15: USBBULK_GetReadMaxTransferSize() parameter list Return value == 0 - Operation failed. Either an invalid handle was used or the transfer size cannot be read. != 0 - The operation was successful. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 162 CHAPTER 6 Bulk Host API V2 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); Parameter hDevice Description Handle to an opened device. Table 6.16: USBBULK_GetWriteMaxTransferSize() parameter list Return value == 0 - Operation failed. Either an invalid handle was used or the transfer size cannot be read. != 0 - The operation was successful. UM09001 User & Reference Guide for emUSB (c) 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); Parameter hDevice Description Handle to an opened device. Table 6.17: USBBULK_ResetPipe() parameter list Return value == 0 - Operation failed. Either an invalid handle was used or the pipes cannot be flushed. != 0 - The operation was successful. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 164 CHAPTER 6 Bulk Host API V2 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); Parameter hDevice Description Handle to an opened device. Table 6.18: USBBULK_ResetDevice() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 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 emUSBBulk. Prototype USBBULK_API unsigned WINAPI USBBULK_SetMode(USB_BULK_HANDLE hDevice, unsigned Mode); Parameter hDevice Mode Description Handle to an opened device. 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 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); } UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 166 CHAPTER 6 Bulk Host API V2 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 hDevice Timeout Description Handle to the opened device. Timeout in milliseconds. Table 6.20: USBBULK_SetReadTimeout() parameter list UM09001 User & Reference Guide for emUSB (c) 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 hDevice Timeout Description Handle to the opened device. Timeout in milliseconds. Table 6.21: USBBULK_SeWriteTimeout() parameter list UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 168 CHAPTER 6 Bulk Host API V2 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); Parameter hDevice Description Handle to an opened device. Table 6.22: USBBULK_GetEnumTickCount() parameter list Return value The time when the USB device was enumerated by the driver given in Windows timer ticks (normally 1 ms. ticks). UM09001 User & Reference Guide for emUSB (c) 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); Parameter hDevice Description Handle to an opened device. Table 6.23: USBBULK_GetReadMaxTransferSizeDown() parameter list Return value != 0 - Max transfer size the driver will read from device. == 0 - The transfer size cannot be read. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 170 CHAPTER 6 Bulk Host API V2 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); Parameter hDevice Description Handle to an opened device. Table 6.24: USBBULK_GetWriteMaxtransferSizeDown() parameter list Return value == 0 - Operation failed. Either an invalid handle was used or the transfer size cannot be read. != 0 - The operation was successful. UM09001 User & Reference Guide for emUSB (c) 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); 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 Return value == 0 - Operation failed. Either an invalid handle was used or the mode cannot be set. != 0 - The operation was successful. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 172 CHAPTER 6 Bulk Host API V2 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); 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 Return value == 0 != 0 - Operation failed. Either an invalid handle was used or the mode cannot be set. - Max transfer size the driver will read from device. UM09001 User & Reference Guide for emUSB (c) 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); Parameter hDevice pBuffer NumBytes Description Handle to an opened device. Pointer to a buffer which shall store the serial number of the device. Size of the buffer given in bytes. Table 6.27: USBBULK_GetSN() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 174 CHAPTER 6 Bulk Host API V2 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 hDevice pDevInfo Description Handle to the opened device. Pointer to a device info structure. Table 6.28: USBBULK_GetDevInfo() parameter list UM09001 User & Reference Guide for emUSB (c) 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 hDevice sProductName BufferSize Description Handle to the opened device. Pointer to a buffer where the product name shall be saved. Size of the product name buffer. Table 6.29: USBBULK_GetProductName() parameter list UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 176 CHAPTER 6 Bulk Host API V2 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 hDevice sVendorName BufferSize Description Handle to the opened device. Pointer to a buffer where the vendor name shall be saved. Size of the vendor name buffer. Table 6.30: USBBULK_GetVendorName() parameter list UM09001 User & Reference Guide for emUSB (c) 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); Parameter s Size Description Pointer to a buffer to store the compile date string. Size, in bytes, of the buffer pointed to by s. Table 6.31: USBBULK_GetDriverCompileDate() parameter list 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 contains the compile date and time of the emUSB driver in the standard format: mm dd yyyy hh:mm:ss UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 178 CHAPTER 6 Bulk Host API V2 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 decimal value: . 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 (c) 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: . 24201 (Mmmrr) means 2.42a UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 180 CHAPTER 6 Bulk Host API V2 6.1.5.4 USBBULK_GetNumAvailableDevices() Description Returns the number of connected USB-Bulk devices. Prototype USBBULK_API unsigned WINAPI USBBULK_GetNumAvailableDevices(U32 * pMask); Parameter pMask Description Pointer to a U32 variable to receive the connected device mask. This parameter can be NULL. Table 6.32: USBBULK_GetNumAvailableDevices() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 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 hDevice pVendorId pProductId Description Handle to the opened device. Pointer to a U16 variable that will store the Vendor ID. Pointer to a U16 variable that will store the Product ID. Table 6.33: USBBULK_GetUSBId() parameter list UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 182 CHAPTER 6 6.1.6 Bulk Host API V2 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 VendorId ProductId acSN acDevName Description An U16 which holds the device Vendor ID. An U16 which holds the device Product ID. Array of chars which holds the serial number of the device. Array of chars which holds the device name. Table 6.34: USBBULK_DEV_INFO elements UM09001 User & Reference Guide for emUSB (c) 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 184 CHAPTER 7 7.1 Mass Storage Device Class (MSD) 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, Windows 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 (c) 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 product. 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 function 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 product. 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 UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 186 CHAPTER 7 Mass Storage Device Class (MSD) 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); Parameter Lun Description Specifies the logical unit number whose vendor name shall be returned. Table 7.2: USB_MSD_GetVendorName() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 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); Parameter Lun Description Specifies the logical unit number whose product name shall be returned. Table 7.3: USB_MSD_GetProductName() parameter list Example const char * USB_GetProductName(U8 Lun) { return "MSD device"; } Additional information The product name string should be no longer than 16 byte. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 188 CHAPTER 7 Mass Storage Device Class (MSD) 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); Parameter Lun Description Specifies the logical unit number whose version shall be returned. Table 7.4: USB_MSD_GetProductVer() parameter list Example const char * USB_MSD_GetProductVer(U8 Lun) { return "1.00"; } Additional information The product version string should be no longer than 8 bytes. UM09001 User & Reference Guide for emUSB (c) 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); Parameter Lun Description Specifies the logical unit number whose serial number shall be returned. Table 7.5: USB_MSD_GetSerialNo() parameter list Example const char * USB_MSD_GetSerialNo(U8 Lun) { return "1234657890"; } Additional information The serial number string should be no longer than 10 bytes. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 190 CHAPTER 7 7.2.4 Mass Storage Device Class (MSD) 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 implemented 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 bytes). You can increase MSD_RAM_NUM_SECTORS and must be at least 23 Kbytes a size of 23 Kbytes (46 sectors with a sector size of 512 the size of the RAM disk by modifying the macros MSD_RAM_SECTOR_SIZE (in multiples of 512), but the size otherwise a Windows host cannot format the disk. /* AddMSD() - excerpt from MSD_Start_StorageRAM.c */ #define MSD_RAM_NUM_SECTORS #define MSD_RAM_SECTOR_SIZE 46 512 UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 191 7.3 Target API Function Description API functions Adds an MSD-class interface to the USB_MSD_Add() USB stack. Adds a mass storage device to the USB_MSD_AddUnit() emUSB-MSD. Adds a CD-ROM device to the emUSBUSB_MSD_AddCDRom() MSD. Sets a callback function to prevent/ USB_MSD_SetPreventAllowRemovalHook() allow removal of storage medium. USB_MSD_SetPreventAllowRemovalHookEx( Sets a callback function to prevent/ ) allow removal of storage medium. Sets a callback function which is called USB_MSD_SetReadWriteHook() with every read or write access to the storage medium. USB_MSD_Task() Handles the MSD-specific protocol. Sets a callback function for the START USB_MSD_SetStartStopUnitHook() STOP UNIT command. Extended API functions Connects the storage medium to the USB_MSD_Connect() MSD. Disconnects the storage medium from USB_MSD_Disconnect() the MSD. USB_MSD_RequestDisconnect() Sets the DisconnectRequest flag. Updates the IsWriteProtected flag for a USB_MSD_UpdateWriteProtect() storage medium. Waits for disconnection while timeout USB_MSD_WaitForDisconnection() is not reached. Data structures emUSB-MSD initialization structure USB_MSD_INIT_DATA that is needed when adding an MSD interface. USB_MSD_INFO emUSB-MSD storage information. Structure that is used when adding a USB_MSD_INST_DATA device to emUSB-MSD. Callback invoked when the storage PREVENT_ALLOW_REMOVAL_HOOK medium is removed. Callback invoked when the storage PREVENT_ALLOW_REMOVAL_HOOK_EX medium is removed. Callback invoked when accessing the READ_WRITE_HOOK storage medium. USB_MSD_INST_DATA_DRIVER Structure that is passed to the driver. Structure that contains callbacks to USB_MSD_STORAGE_API the storage driver. Callback invoked when the START START_STOP_UNIT_HOOK STOP UNIT command is received. Table 7.6: List of emUSB MSD interface functions and data structures UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 192 CHAPTER 7 7.3.1 Mass Storage Device Class (MSD) 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); Parameter pInitData Description Pointer to a USB_MSD_INIT_DATA structure. Table 7.7: USB_MSD_Add() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 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); Parameter pInstData Description 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 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 194 CHAPTER 7 Mass Storage Device Class (MSD) 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); Parameter pInstData Description 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 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. UM09001 User & Reference Guide for emUSB (c) 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) Parameter Description Pointer to the callback function PREVENT_ALLOW_REMOVAL_HOOK. For detailed information pfOnPreventAllowRemoval about the function pointer, refer to PREVENT_ALLOW_REMOVAL_HOOK on page 208. Table 7.10: USB_MSD_SetPreventAllowRemovalHook() parameter list Additional information The callback is called within the MSD task context. The callback must not block. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 196 CHAPTER 7 Mass Storage Device Class (MSD) 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) Parameter Description Pointer to the callback function pfOnPreventAllowRemoval PREVENT_ALLOW_REMOVAL_HOOK_EX. For detailed inforEx mation about the function pointer, refer to PREVENT_ALLOW_REMOVAL_HOOK_EX on page 209. Table 7.11: USB_MSD_SetPreventAllowRemovalHookEx() parameter list Additional information The callback is called within the MSD task context. The callback must not block. UM09001 User & Reference Guide for emUSB (c) 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 pfOnReadWrite Description 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 UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 198 CHAPTER 7 Mass Storage Device Class (MSD) 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 (c) 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); Parameter Lun Description Zero-based index for the unit number. Using only one storage medium, this parameter is 0. Table 7.13: USB_MSD_Connect() parameter list Additional information The storage medium is initially always connected to the MSD component. This function is normally used after the storage medium was disconnected via USB_MSD_Disconnect() to perform file system operations on the device application side. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 200 CHAPTER 7 Mass Storage Device Class (MSD) 7.3.2.2 USB_MSD_Disconnect() Description Disconnects the storage medium from the MSD module. Prototype void USB_MSD_Disconnect(U8 Lun); Parameter Lun Description Zero-based index for the unit number. Using only one storage medium, this parameter is 0. Table 7.14: USB_MSD_Disconnect() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 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); Parameter Lun Description Zero-based index for the unit number. Using only one storage medium, this parameter is 0. Table 7.15: USB_MSD_RequestDisconnect() parameter list 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 currently not available. To reconnect the storage medium, USB_MSD_Connect() shall be called. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 202 CHAPTER 7 Mass Storage Device Class (MSD) 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); Parameter Lun IsWriteProtected Description Zero-based index for the unit number. Using only one storage medium, this parameter is 0. 1 - Medium is write protected. 0 - Medium is not write protected. Table 7.16: USB_MSD_UpdateWriteProtect() parameter list 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, otherwise the WriteProtected flag is normally not recognized. UM09001 User & Reference Guide for emUSB (c) 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); Parameter Lun TimeOut Description 0-based index for the unit number. Using only one storage medium, this parameter is 0. timeout given in ms (timer ticks). Table 7.17: USB_MSD_WaitForDisconnection() parameter list 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 disconnects 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 204 CHAPTER 7 Mass Storage Device Class (MSD) 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 pfOnStartStopUnit Description 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 (c) 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; Member EPIn EPOut InterfaceNum Description Endpoint for sending data to the host. Endpoint for receiving data from the host. 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 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 206 CHAPTER 7 Mass Storage Device Class (MSD) 7.3.3.2 USB_MSD_INFO Description emUSB-MSD storage interface. Prototype typedef struct { U32 NumSectors; U16 SectorSize; } USB_MSD_INFO; Member NumSectors SectorSize Description Number of available sectors. Size of one sector. Table 7.20: USB_MSD_INFO elements UM09001 User & Reference Guide for emUSB (c) 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; Member pAPI DriverData DeviceType IsPresent pfHandleCmd IsWriteProtected Description Pointer to a structure that holds the storage device driver API. Driver data that are passed to the storage driver. Refer to USB_MSD_INST_DATA_DRIVER on page 211 for detailed information about how to initialize this structure. Determines the type of the device. Determines if the medium is storage is present. For nonremovable devices always 1. Optional pointer to a callback function which handles SCSI commands. typedef U8 (USB_MSD_HANDLE_CMD)(U8 Lun); Specifies whether the storage medium shall be write-protected. Table 7.21: USB_MSD_INST_DATA elements 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(). UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 208 CHAPTER 7 Mass Storage Device Class (MSD) 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 (c) 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); UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 210 CHAPTER 7 Mass Storage Device Class (MSD) 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 U8 U8 U32 U32 Member Lun IsRead OnOff StartLBA NumBlocks Lun, IsRead, OnOff, StartLBA, NumBlocks); Description Specifies the logical unit number which was accessed through read or write. Specifies whether a read or a write access was used (1 for read, 0 for write). States whether the read or write request has been initialized (1) or whether it is complete (0). The first Logical Block Address accessed by the transfer. 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 (c) 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; Member pStart StartSector NumSectors SectorSize pSectorBuffer NumBytes4Buffer Description A pointer defining the start address. The start sector that is used for the driver. The available number of sectors available for the driver. The sector size that should be used by the driver. Pointer to a application provided buffer to be used as temporary buffer for storing the sector data Size of the application provided buffer. Table 7.23: USB_MSD_INST_DATA_DRIVER Additional Information This structure is passed to the storage driver. Therefore, the member of this structure 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 : Member pStart StartSector NumSectors SectorSize Description A pointer defining the start address of the RAM disk. This member is ignored. The available number of sectors available for the RAM disk. The sector size that should be used by the driver. USB_MSD_StorageByName: Member pStart StartSector NumSectors SectorSize pSectorBuffer NumBytes4Buffer Description Pointer to a string holding the name of the volumes that shall be used, for example "nand:" "mmc:1:" Specifies the start sector. Number of sector that shall be used. This member is ignored. Pointer to a application provided buffer to be used as temporary buffer for storing the sector data 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-Storage-Layer functions. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 212 CHAPTER 7 Mass Storage Device Class (MSD) 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; Member pfInit pfGetInfo pfGetReadBuffer pfRead pfGetWriteBuffer pfWrite pfMediumIsPresent pfDeInit Description Initializes the storage medium. Retrieves storage medium information such as sector size and number of sectors available. Prepares read function and returns a pointer to a buffer that is used by the storage driver. Reads one or multiple sectors from the storage medium. Prepares write function and returns a pointer to a buffer that is used by the storage driver. Writes one or more sectors to the storage medium. Checks if medium is present. Deinitializes the storage medium. Table 7.24: List of callback functions of 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. UM09001 User & Reference Guide for emUSB (c) 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 U8 Member Lun StartLoadEject Lun, StartLoadEject); Description Specifies the logical unit number which was accessed through read or write. Binary OR of the SCSI LOEJ and START bits. Table 7.25: START_STOP_UNIT_HOOK elements 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 214 CHAPTER 7 7.4 Mass Storage Device Class (MSD) 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: * * * 7.4.2 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. 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 (c) 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 Lun pDriverData Description Logical unit number. Specifies for which drive the function is called. 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 structure, refer to USB_MSD_INST_DATA_DRIVER on page 211. Table 7.26: (*pfInit)() parameter list UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 216 CHAPTER 7 Mass Storage Device Class (MSD) 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 Lun pInfo Description Logical unit number. Specifies for which drive the function is called. 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 (c) 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 storage driver. Prototype U32 (*pfGetReadBuffer)(U8 Lun, U32 SectorIndex, void ** ppData, U32 NumSectors); Parameter Lun SectorIndex ppData NumSectors Description Logical unit number. Specifies for which drive the function is called. Specifies the start sector for the read operation. Pointer to a pointer to store the read buffer address of the driver. Number of sectors to read. Table 7.28: (*pfGetReadBuffer)() parameter list Return value Maximum number of consecutive sectors that can be read at once by the driver. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 218 CHAPTER 7 Mass Storage Device Class (MSD) 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); Parameter Lun SectorIndex pData NumSectors Description Logical unit number. Specifies for which drive the function is called. Specifies the start sector from where the read operation is started. Pointer to buffer to store the read data. Number of sectors to read. Table 7.29: (*pfRead)() parameter list Return value == 0 Success != 0 File System error code. UM09001 User & Reference Guide for emUSB (c) 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 storage driver. Prototype U32 (*pfGetWriteBuffer)(U8 Lun, U32 SectorIndex, void ** ppData, U32 NumSectors); Parameter Lun SectorIndex ppData NumSectors Description Logical unit number. Specifies for which drive the function is called. Specifies the start sector for the write operation. Pointer to a pointer to store the write buffer address of the driver. Number of sectors to write. Table 7.30: (*pfGetWriteBuffer)() parameter list Return value Maximum number of consecutive sectors that can be written into the buffer. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 220 CHAPTER 7 Mass Storage Device Class (MSD) 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); Parameter Lun SectorIndex pData NumSectors Description Logical unit number. Specifies for which drive the function is called. Specifies the start sector for the write operation. Pointer to data to be written to the storage medium. Number of sectors to write. Table 7.31: (*pfWrite)() parameter list Return value 0: Success Any other value means error. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 221 7.4.3.7 (*pfMediumIsPresent)() Description Checks if medium is present. Prototype char (*pfMediumIsPresent) (U8 Lun); Parameter Lun Description Logical unit number. Specifies for which drive the function is called. Table 7.32: (*pfMediumIsPresent)() parameter list Return value 1: Medium is present. 0: Medium is not present. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 222 CHAPTER 7 Mass Storage Device Class (MSD) 7.4.3.8 (*pfDeInit)() Description Deinitializes the storage medium. Prototype void (*pfDeInit) (U8 Lun); Parameter Lun Description Logical unit number. Specifies for which drive the function is called. Table 7.33: (*pfDeInit)() parameter list UM09001 User & Reference Guide for emUSB (c) 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 224 CHAPTER 8 8.1 Media Transfer Protocol Class (MTP) Overview The Media Transfer Protocol (MTP) is a USB class protocol which can be used to transfer files to and from storage devices. MTP is an official extension of the Picture Transfer 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 (c) 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 "Computer" 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: UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 226 CHAPTER 8 Media Transfer Protocol Class (MTP) On the Ubuntu Linux operating system a connected MTP device is shown in the "Computer" window: UM09001 User & Reference Guide for emUSB (c) 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 similarly. 8.1.2 Additional information For more technical details about MTP and PTP follow these links: MTP specification PTP specification UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 228 CHAPTER 8 8.2 Media Transfer Protocol Class (MTP) 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 application, 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 (c) 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 230 CHAPTER 8 Media Transfer Protocol Class (MTP) 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 (c) 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 232 CHAPTER 8 Media Transfer Protocol Class (MTP) 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 DeviceInfo dataset. For more information, refer to MTP specification. UM09001 User & Reference Guide for emUSB (c) 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. Type Macro Default N MTP_DEBUG_LEVEL 0 N MTP_MAX_NUM_STORAGES 4 B MTP_SAVE_FILE_INFO 0 N MTP_MAX_FILE_PATH 256 B MTP_SUPPORT_UTF8 1 Description 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 Maximum number of storage units the storage layer can handle. 4 additional bytes are allocated for each storage unit. 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. Maximum number of characters in the path to a file or directory. 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 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 single task called MainTask(). // MainTask() - excerpt from USB_MTP_Start.c UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 234 CHAPTER 8 Media Transfer Protocol Class (MTP) 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 storage 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 (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 235 8.4 Target API Function USB_MTP_Add() USB_MTP_AddStorage() USB_MTP_Task() USB_MTP_FILE_INFO USB_MTP_INIT_DATA USB_MTP_INST_DATA USB_MTP_INST_DATA_DRIVER USB_MTP_STORAGE_API USB_MTP_STORAGE_INFO Description API functions Adds an MTP interface to the USB stack. Adds a storage device to the emUSB-MTP. Handles the MTP communication. Data structures Stores information about a file or directory. Stores the MTP initialization parameters. Stores the initialization parameters of storage driver. Stores parameters that are passed to storage driver. Stores callbacks to the functions of storage driver. Stores information about the storage medium. Table 8.3: List of emUSB MTP interface functions and data structures 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); Parameter pInitData Description Pointer to a USB_MTP_INIT_DATA structure. Table 8.4: USB_MTP_Add() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 236 CHAPTER 8 Media Transfer Protocol Class (MTP) 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); Parameter pInstData Description 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 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. UM09001 User & Reference Guide for emUSB (c) 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 238 CHAPTER 8 8.4.2 Media Transfer Protocol Class (MTP) 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; Member Description Pointer to full path to file. Pointer to beginning of file/directory name in pFilePath Size of the file in bytes. Time and date when the file was created. Time and data when the file was last modified. Set to 1 if the path points to a directory. Bitmask containing the file or directory attributes. Unique file/directory identifier. pFilePath pFileName FileSize CreationTime LastWriteTime IsDirectory Attributes acId Table 8.6: USB_MTP_FILE_INFO elements Additional Information The date and time is formatted as follows: Bit range 0-4 5-10 11-15 16-20 21-24 25-31 Value range 0-29 0-59 0-23 1-31 1-12 0-127 Description 2-second count Minutes Hours Day of month Month of year Number of years since 1980 acId should unique for each file and directory on the file system and it should be persistent between MTP sessions. The following attributes are supported: Bitmask MTP_FILE_ATTR_WP MTP_FILE_ATTR_SYSTEM MTP_FILE_ATTR_HIDDEN UM09001 User & Reference Guide for emUSB Description File/directory can not be modified File/directory is required for the correct functioning of the system. File/directory should not be shown to user. (c) 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; Member EPIn EPOut EPInt pObjectList NumBytesObjectList pDataBuffer NumBytesDataBuffer Description Endpoint for receiving data from host. Endpoint for sending data to host. Endpoint for sending events to host. Pointer to a memory region where the list of MTP objects is stored. Number of bytes allocated for the object list. Pointer to a memory region to be used as communication buffer. Number of bytes allocated for the data buffer. Table 8.7: USB_MTP_INIT_DATA elements 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 240 CHAPTER 8 Media Transfer Protocol Class (MTP) 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; Member pAPI sDescription sVolumeId DriverData Description Pointer to a structure that holds the storage device driver API. Human-readable string which identifies the storage. This string is displayed in Windows Explorer. Unique volume identifier. Driver data that are passed to the storage driver. Refer to USB_MTP_INST_DATA_DRIVER on page 241 for detailed information 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 Additional Information The MTP device returns the sDescription string in the Storage Description parameter and the sVolumeId in the Volume Identifier of the StorageInfo dataset. For more information, refer to MTP specification. UM09001 User & Reference Guide for emUSB (c) 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; Member pRootDir Description Path to directory to be used as the root of the storage. Table 8.9: USB_MTP_INST_DATA_DRIVER Additional Information pRootDir can specify the root of the file system or any other subdirectory. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 242 CHAPTER 8 Media Transfer Protocol Class (MTP) 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 (*pfInit)() (*pfGetInfo)() (*pfFindFirstFile)() (*pfFindNextFile)() Description Initializes the storage medium. Returns information about the storage medium such as storage capacity and the available free space. Returns information about the first file in a given directory. 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 (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 243 Member (*pfOpenFile)() (*pfCreateFile)() (*pfReadFromFile)() (*pfWriteToFile)() (*pfCloseFile)() (*pfRemoveFile)() (*pfCreateDir)() (*pfRemoveDir)() (*pfFormat)() (*pfRenameFile)() (*pfDeInit)() (*pfGetFileAttributes)() (*pfModifyFileAttributes)() (*pfGetFileCreationTime)() (*pfGetFileLastWriteTime)() (*pfGetFileId)() (*pfGetFileSize)() Description Opens an existing file. Creates a new file. Reads data from the current file. Writes data to current file. Closes the current file. Removes a file from storage medium. Creates a new directory. Removes a directory from storage medium. Formats the storage. Changes the name of a file or directory Deinitializes the storage medium. Reads the attributes of a file or directory. Changes the attributes of a file or directory. Returns the creation time of a file or directory. Returns the time of the last modification made to a file or directory. Returns the unique id of a file or directory. Returns the size of a file in bytes. Table 8.10: List of callback functions of USB_MTP_STORAGE_API 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 244 CHAPTER 8 Media Transfer Protocol Class (MTP) 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 NumKbytesTotal NumKbytesFreeSpace FSType IsWriteProtected IsRemovable Description Capacity of storage medium in Kbytes. Available free space on storage medium in Kbytes. Type of file system as specified in MTP. Set to 1 if the storage medium canDone.not be modified. 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 (c) 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 246 CHAPTER 8 8.5.3 Media Transfer Protocol Class (MTP) 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); Parameter Unit pDriverData Description Logical unit number. Specifies for which storage medium the function is called. 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 structure, refer to USB_MTP_INST_DATA_DRIVER on page 241. Table 8.12: (*pfInit)() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 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); Parameter Unit pStorageInfo Description Logical unit number. Specifies for which storage medium the function is called. Pointer to a USB_MTP_STORAGE_INFO structure. For detailed information about the USB_MTP_STORAGE_INFO structure, refer to USB_MTP_STORAGE_INFO on page 244. Table 8.13: (*pfGetInfo)() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 248 CHAPTER 8 Media Transfer Protocol Class (MTP) 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); Parameter Unit pDirPath pFileInfo Description Logical unit number. Specifies for which storage medium the function is called. Full path to the directory to be searched. IN: --OUT: Information about the file/directory found. Table 8.14: (*pfFindFirstFile)() parameter list Return value ==0 ==1 <0 File/directory found No more files/directories found An error occurred Additional information The "." and ".." directory entries which are relevant only for the file system should be skipped. UM09001 User & Reference Guide for emUSB (c) 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); Parameter Unit pFileInfo Description Logical unit number. Specifies for which storage medium the function is called. IN: --OUT: Information about the file/directory found. Table 8.15: (*pfFindNextFile)() parameter list Return value ==0 ==1 <0 File/directory found No more files/directories found An error occurred Additional information The "." and ".." directory entries which are relevant only for the file system should be skipped. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 250 CHAPTER 8 Media Transfer Protocol Class (MTP) 8.5.3.5 (*pfOpenFile)() Description Opens a file for reading. Prototype int (*pfOpenFile)(U8 Unit, const char * pFilePath); Parameter Unit pFilePath Description Logical unit number. Specifies for which storage medium the function is called. IN: Full path to file. OUT ---. Table 8.16: (*pfOpenFile)() parameter list Return value ==0 !=0 File opened 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. UM09001 User & Reference Guide for emUSB (c) 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); Parameter Unit pDirPath pFileInfo Description Logical unit number. Specifies for which storage medium the function is called. IN: Full path to directory where the file should be created. OUT: --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 Return value ==0 !=0 File created and opened 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 truncated 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 generated by the file system. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 252 CHAPTER 8 Media Transfer Protocol Class (MTP) 8.5.3.7 (*pfReadFromFile)() Description Reads data from the current file. Prototype int (*pfReadFromFile)(U8 Unit, U32 Off, void * pData, U32 NumBytes); Parameter Unit Off pData NumBytes Description Logical unit number. Specifies for which storage medium the function is called. Byte offset where to read from. IN: --OUT: Data read from file. Number of bytes to read from file. Table 8.18: (*pfReadFromFile)() parameter list Return value ==0 !=0 Data read from file An error occurred Additional information The function reads data from the file opened by (*pfOpenFile)(). UM09001 User & Reference Guide for emUSB (c) 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); Parameter Unit Off pData NumBytes Description Logical unit number. Specifies for which storage medium the function is called. Byte offset where to write to. IN: Data to write to file OUT: --Number of bytes to write to file. Table 8.19: (*pfWriteToFile)() parameter list Return value ==0 !=0 Data written to file An error occurred Additional information The function writes data to file opened by (*pfCreateFile)(). UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 254 CHAPTER 8 Media Transfer Protocol Class (MTP) 8.5.3.9 (*pfCloseFile)() Description Closes the current file. Prototype int (*pfCloseFile)(U8 Unit); Parameter Description Logical unit number. Specifies for which storage medium the function is called. Lun Table 8.20: (*pfCloseFile)() parameter list Return value ==0 !=0 File closed An error occurred Additional information The function closes the file opened by (*pfCreateFile)() or (*pfOpenFile)(). UM09001 User & Reference Guide for emUSB (c) 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); Parameter Unit pFilePath Description Logical unit number. Specifies for which drive the function is called. IN: Full path to file/directory to be removed OUT: --- Table 8.21: (*pfRemoveFile)() parameter list Return value ==0 !=0 File removed An error occurred UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 256 CHAPTER 8 Media Transfer Protocol Class (MTP) 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); Parameter Unit pDirPath pFileInfo Description Logical unit number. Specifies for which storage medium the function is called. IN: Full path to directory where the directory should be created. OUT: --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 Return value ==0 !=0 Directory created 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. UM09001 User & Reference Guide for emUSB (c) 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); Parameter Unit pDirPath Description Logical unit number. Specifies for which storage medium the function is called. IN: Full path to directory to be removed. OUT: --- Table 8.23: (*pfRemoveDir)() parameter list Return value ==0 !=0 Directory removed An error occurred Additional information The function should remove the directory and the entire file tree under it. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 258 CHAPTER 8 Media Transfer Protocol Class (MTP) 8.5.3.13 (*pfFormat)() Description Initializes the storage medium. Prototype int (*pfFormat)(U8 Unit); Parameter Description Logical unit number. Specifies for which storage medium the function is called. Unit Table 8.24: (*pfFormat)() parameter list Return value ==0 !=0 Storage medium initialized 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 directories underneath pRootDir should be removed. UM09001 User & Reference Guide for emUSB (c) 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); Parameter Unit pFileInfo Description Logical unit number. Specifies for which storage medium the function is called. 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 Return value ==0 !=0 File/directory renamed An error occurred Additional information Only the name of the file/directory should be changed. The path to parent directory should remain the same. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 260 CHAPTER 8 Media Transfer Protocol Class (MTP) 8.5.3.15 (*pfDeInit)() Description Deinitializes the storage medium. Prototype void (*pfDeInit)(U8 Unit); Parameter Unit Description Logical unit number. Specifies for which storage medium the function is called. Table 8.26: (*pfDeInit)() parameter list Additional information Typically called when the application calls USB_Stop() to de-initialize emUSB. UM09001 User & Reference Guide for emUSB (c) 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); Parameter Unit pFilePath pMask Description Logical unit number. Specifies for which storage medium the function is called. Full path to file or directory (0-terminated string). IN: --OUT: The bitmask of the attributes. Table 8.27: (*pfGetFileAttributes)() parameter list Return value ==0 !=0 Information returned 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 262 CHAPTER 8 Media Transfer Protocol Class (MTP) 8.5.3.17 (*pfModifyFileAttributes)() Description Sets and clears file attributes. Prototype int (*pfModifyFileAttributes)(U8 Unit, const char * pFilePath, U8 SetMask, U8 ClrMask);; Parameter Unit pFilePath SetMask ClrMask Description Logical unit number. Specifies for which storage medium the function is called. Full path to file or directory (0-terminated string). The bitmask of the attributes which should be set. The bitmask of the attributes which should be cleared. Table 8.28: (*pfModifyFileAttributes)() parameter list Return value ==0 !=0 Attributes modified 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. UM09001 User & Reference Guide for emUSB (c) 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); Parameter Unit pFilePath pTime Description Logical unit number. Specifies for which storage medium the function is called. Full path to file or directory (0-terminated string). IN: --OUT: The creation time. Table 8.29: (*pfGetFileCreationTime)() parameter list Return value ==0 !=0 Creation time returned 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 264 CHAPTER 8 Media Transfer Protocol Class (MTP) 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);; Parameter Unit pFilePath pTime Description Logical unit number. Specifies for which storage medium the function is called. Full path to file or directory (0-terminated string). IN: --OUT: The modification time. Table 8.30: (*pfGetFileLastWriteTime)() parameter list Return value ==0 !=0 Modification time returned 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. UM09001 User & Reference Guide for emUSB (c) 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); Parameter Unit pFilePath pId Description Logical unit number. Specifies for which storage medium the function is called. Full path to file or directory (0-terminated string). 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 Return value ==0 !=0 Id returned An error occurred Additional information This function is called only when the compile time switch MTP_SAVE_FILE_INFO is set to 0. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 266 CHAPTER 8 Media Transfer Protocol Class (MTP) 8.5.3.21 (*pfGetFileSize)() Description Returns the size of a file in bytes. Prototype int (*pfGetFileSize)(U8 Unit, const char * pFilePath, U32 * pFileSize); Parameter Unit pFilePath pFileSize Description Logical unit number. Specifies for which storage medium the function is called. Full path to file or directory (0-terminated string). IN: --OUT: The size of file in bytes. Table 8.32: (*pfGetFileSize)() parameter list Return value ==0 !=0 Size of file returned An error occurred Additional information This function is called only when the compile time switch MTP_SAVE_FILE_INFO is set to 0. UM09001 User & Reference Guide for emUSB (c) 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 268 CHAPTER 9 9.1 Communication Device Class (CDC) 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 (c) 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); } } } UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 270 9.3 CHAPTER 9 Communication Device Class (CDC) 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 (c) 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 272 CHAPTER 9 Communication Device Class (CDC) 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 wizard. UM09001 User & Reference Guide for emUSB (c) 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 274 CHAPTER 9 Communication Device Class (CDC) 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 (c) 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 276 CHAPTER 9 Communication Device Class (CDC) * 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 (c) 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 target is shown in the terminal window: UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 278 9.4 CHAPTER 9 Communication Device Class (CDC) Target API This chapter describes the functions and data structures that can be used with the target application. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 279 9.4.1 Interface function list Name USB_CDC_Add() USB_CDC_CancelRead() USB_CDC_CancelReadEx() USB_CDC_CancelWrite() USB_CDC_CancelWriteEx() USB_CDC_Read() USB_CDC_ReadEx() USB_CDC_ReadOverlapped() USB_CDC_ReadOverlappedEx() USB_CDC_ReadTimed() USB_CDC_ReadTimedEx() USB_CDC_Receive() USB_CDC_ReceiveEx() USB_CDC_ReceiveTimed() USB_CDC_ReceiveTimedEx() USB_CDC_SetOnBreak() USB_CDC_SetOnBreakEx() USB_CDC_SetOnLineCoding() USB_CDC_SetOnLineCodingEx() USB_CDC_UpdateSerialState() USB_CDC_UpdateSerialStateEx() USB_CDC_Write() USB_CDC_WriteEx() USB_CDC_WriteOverlapped() USB_CDC_WriteOverlappedEx() USB_CDC_WriteTimed() USB_CDC_WriteTimedEx() USB_CDC_WaitForRX() USB_CDC_WaitForRXEx() USB_CDC_WaitForTX() USB_CDC_WaitForTXEx() USB_CDC_WriteSerialState() USB_CDC_WriteSerialStateEx() USB_CDC_GetNumBytesRemToReadEx () Description API functions Adds CDC-class to the emUSB interface. Cancels an asynchronous read operation that is pending Cancels an asynchronous read operation that is pending Reads data from host. Reads data from host asynchronously. Reads data from host with a given timeout. Reads data from host. Read data from host with a given timeout. This function returns immediately as soon as data has been received or a timeout occurs. Sets a callback for receiving a SEND_BREAK by the host. Sets a callback for registering changing of the "line-coding" by the host. Changes the current serial state. Writes data to host. Write data to host asynchronously. Writes data to the host with a given timeout. Waits for reading data transfer from the Host to be ended. Waits for writing data transfer to the Host to be ended. Sends the current serial state to the Host. Returns the number of byte which still need to be read. Returns the number of byte which still need to USB_CDC_GetNumBytesToWriteEx() 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 Initialization structure that is needed when USB_CDC_INIT_DATA adding an CDC interface. Callback function to receive a break condition USB_CDC_ON_SET_BREAK sent by the host. USB_CDC_ON_SET_LINE_CODING Callback registering line-coding changes. Structure that contains the new line-coding USB_CDC_LINE_CODING sent by the host. Table 9.1: USB-CDC API overview UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 280 CHAPTER 9 9.4.2 Communication Device Class (CDC) 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); Parameter pInitData Description 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 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. UM09001 User & Reference Guide for emUSB (c) 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); Parameter hInst Description Handle to a valid CDC instance, returned by USB_CDC_Add(). Table 9.3: USB_CDC_CancelReadEx() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 282 CHAPTER 9 Communication Device Class (CDC) 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);; Parameter hInst Description Handle to a valid CDC instance, returned by USB_CDC_Add(). Table 9.4: USB_CDC_CancelWriteEx() parameter list Additional information This function shall be called when a pending asynchronously write operation (triggered by USB_CDC_WriteOverlapped() USB_CDC_WriteOverlappedEx()) should be canceled. It can be called from any task. UM09001 User & Reference Guide for emUSB (c) 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 int USB_CDC_Read(void * pData, unsigned NumBytes); USB_CDC_ReadEx(USB_CDC_HANDLE hInst, void* pData, unsigned NumBytes); Parameter hInst pData NumBytes Description Handle to a valid CDC instance, returned by USB_CDC_Add(). Pointer to a buffer where the received data will be stored. Number of bytes to read. Table 9.5: USB_CDC_Read()/USB_CDC_ReadEx()parameter list 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 disconnect USB_STATUS_ERROR is returned. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 284 CHAPTER 9 Communication Device Class (CDC) 9.4.2.5 USB_CDC_ReadOverlapped() USB_CDC_ReadOverlappedEx() Description Reads data from the host asynchronously. Prototype int int USB_CDC_ReadOverlapped(void* pData, unsigned NumBytes); USB_CDC_ReadOverlappedEx(USB_CDC_HANDLE hInst, void* pData, unsigned NumBytes); Parameter hInst pData NumBytes Description Handle to a valid CDC instance, returned by USB_CDC_Add(). Pointer to a buffer where the received data will be stored. Number of bytes to read. Table 9.6: USB_CDC_ReadOverlapped()/USB_CDC_ReadOverlappedEx() parameter list 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(). UM09001 User & Reference Guide for emUSB (c) 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); Parameter hInst pData NumBytes ms Description Handle to a valid CDC instance, returned by USB_CDC_Add(). Pointer to a buffer where the received data will be stored. Number of bytes to read. timeout given in milliseconds. A zero value results in an infinite timeout. Table 9.7: USB_CDC_ReadTimed()/USB_CDC_ReadTimedEx() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 286 CHAPTER 9 Communication Device Class (CDC) 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 contrast 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); Parameter hInst pBuffer NumBytes Description Handle to a valid CDC instance, returned by USB_CDC_Add(). Pointer to a buffer where the received data will be stored. Number of bytes to read. Table 9.8: USB_CDC_Receive()/USB_CDC_ReceiveEx() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 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 contrast 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); Parameter hInst pBuffer NumBytes ms Description Handle to a valid CDC instance, returned by USB_CDC_Add(). Pointer to a buffer where the received data will be stored. Number of bytes to read. timeout given in milliseconds. A zero value results in an infinite timeout. Table 9.9: USB_CDC_ReceiveTimed()/USB_CDC_ReceiveTimedEx() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 288 CHAPTER 9 Communication Device Class (CDC) 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); Parameter hInst pf Description Handle to a valid CDC instance, returned by USB_CDC_Add(). 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 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. UM09001 User & Reference Guide for emUSB (c) 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); Parameter hInst pf Description Handle to a valid CDC instance, returned by USB_CDC_Add(). Pointer to the callback function USB_CDC_ON_SET_LINE_CODING. For detailed information about the USB_CDC_ON_SET_LINE_CODING function pointer, refer to USB_CDC_ON_SET_LINE_CODING on page 303. Table 9.11: USB_CDC_SetLineCoding()/USB_CDC_SetLineCodingEx() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 290 CHAPTER 9 Communication Device Class (CDC) 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); Parameter hInst pSerialState Description Handle to a valid CDC instance, returned by USB_CDC_Add(). 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 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. UM09001 User & Reference Guide for emUSB (c) 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); Parameter hInst pData NumBytes Description Handle to a valid CDC instance, returned by USB_CDC_Add(). Pointer to data that should be sent to the host. Number of bytes to write. Table 9.13: USB_CDC_Write()/USB_CDC_WriteEx() parameter list Additional information This function is blocking. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 292 CHAPTER 9 Communication Device Class (CDC) 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); Parameter hInst pData NumBytes Description Handle to a valid CDC instance, returned by USB_CDC_Add(). Pointer to data that should be sent to the host. Number of bytes to write. Table 9.14: USB_CDC_WriteOverlapped()/USB_CDC_WriteOverlappedEx() parameter list 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(). UM09001 User & Reference Guide for emUSB (c) 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); Parameter hInst pData NumBytes ms Description Handle to a valid CDC instance, returned by USB_CDC_Add(). Pointer to a buffer where the data to send is stored. Number of bytes to write. timeout given in milliseconds. A zero value results in an infinite timeout. Table 9.15: USB_CDC_WriteTimed()/USB_CDC_WriteTimedEx() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 294 CHAPTER 9 Communication Device Class (CDC) 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); Parameter hInst Description Handle to a valid CDC instance, returned by USB_CDC_Add(). Table 9.16: USB_CDC_WaitForRX()/USB_CDC_WaitForRXEx() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 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); Parameter hInst Description Handle to a valid CDC instance, returned by USB_CDC_Add(). Table 9.17: USB_CDC_WaitForTX()/USB_CDC_WaitForTXEx() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 296 CHAPTER 9 Communication Device Class (CDC) 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); Parameter hInst Description Handle to a valid CDC instance, returned by USB_CDC_Add(). Table 9.18: USB_CDC_WriteSerialState()/USB_CDC_WriteSerialStateEx parameter list 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. UM09001 User & Reference Guide for emUSB (c) 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); Parameter hInst Description Handle to a valid CDC instance, returned by USB_CDC_Add(). Table 9.19: USB_CDC_GetNumBytesRemToReadEx() parameter list 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); } } UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 298 CHAPTER 9 Communication Device Class (CDC) 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); Parameter hInst Description Handle to a valid CDC instance, returned by USB_CDC_Add(). Table 9.20: USB_CDC_GetNumBytesToWriteEx() parameter list 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); } UM09001 User & Reference Guide for emUSB (c) 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); Parameter hInst Description Handle to a valid CDC instance, returned by USB_CDC_Add(). Table 9.21: USB_CDC_StartReadTransferEx() parameter list 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..> } } UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 300 CHAPTER 9 Communication Device Class (CDC) 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); Parameter hInst Description Handle to a valid CDC instance, returned by USB_CDC_Add(). Table 9.22: USB_CDC_GetNumBytesInBufferEx() parameter list Return value > 0 - Number of bytes which have been stored in the internal buffer. == 0 - Nothing stored yet. UM09001 User & Reference Guide for emUSB (c) 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; Member EPIn EPOut EPInt Description Endpoint for sending data to the host Endpoint for receiving data from the host Endpoint for sending status information. Table 9.23: USB_CDC_INIT_DATA elements 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 302 CHAPTER 9 Communication Device Class (CDC) 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); Member BreakDuration Description The BreakDuration gives the length of time, in milliseconds, of the break signal. Table 9.24: USB_CDC_ON_SET_LINE_CODING elements 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. UM09001 User & Reference Guide for emUSB (c) 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); Member pLineCoding Description Pointer to USB_CDC_LINE_CODING structure Table 9.25: USB_CDC_ON_SET_LINE_CODING elements 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 304 CHAPTER 9 Communication Device Class (CDC) 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 DTERate CharFormat ParityType DataBits Description The data transfer rate for the device in bits per second. Contain the stop bits: 0 - 1 Stop bit 1 - 1.5 Stop bits 2 - 2 Stop bits Specifies the parity type: 0 - None 1 - Odd 2 - Even 3 - Mark 4 - Space Specifies the bits per byte: (5, 6, 7, 8, 16) Table 9.26: USB_CDC_LINE_CODING elements UM09001 User & Reference Guide for emUSB (c) 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 DCD DSR Break Ring FramingError ParityError OverRunError CTS Description Data Carrier Detect: Tells that the device is connected to the telephone line. Data Set Read: Device is ready to receive data. 1 - Break condition signaled. Device indicates that it has detected a ring signal on the telephone line. When set to 1, the device indicates a framing error. When set to 1, the device indicates a parity error. When set to 1, the device indicates an over-run error. Clear to send: Acknowledges RTS and allows the host to transmit. Table 9.27: USB_CDC_LINE_CODING elements UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 306 UM09001 User & Reference Guide for emUSB CHAPTER 9 Communication Device Class (CDC) (c) 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 308 CHAPTER 10 Human Interface Device Class (HID) 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 drivers 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 Specification--6/27/01 Version 1.11 [HID2] HID Usage Tables, 1/21/2005 Version 1.12 UM09001 User & Reference Guide for emUSB (c) 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 examples 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 program 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) UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 310 CHAPTER 10 Human Interface Device Class (HID) 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 website, www.usb.org, for detailed information about the USB HID standard. Device descriptor Configuration descriptor Interface descriptor HID descriptor Endpoint descriptor Report Physical descriptor descriptor 10.2.1.1 HID descriptor A HID descriptor contains the report and optional the physical descriptors. It specifies 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 311 The USB Implementers Forum provides an application which helps to build and modify 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 312 CHAPTER 10 Human Interface Device Class (HID) 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 without 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 (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 313 10.4 Example application Example applications are supplied. These can be used for testing the correct installation and proper function of the device running emUSB. The following start application files are provided: 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 10.4.1 HID_Mouse.c HID_Mouse.c is a typical example for a "true HID" implementation. The host identifies 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. 2. 3. Add HID_Mouse.c to your project and build and download the application into the target. When you connect your target to the host via USB, Windows will detect the new HID device. 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 314 CHAPTER 10 Human Interface Device Class (HID) 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 modified echo server; the application receives data byte by byte, increments every single byte and sends them back to the host. Host (PC) HIDEcho1.exe USB HID example application USB connection Target Target programmed with the example application consistent with the application running on host side: HID_Echo1.c 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 application 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 application on page 315 for more information to the PC example project. 10.4.2.1 Running the example 1. 2. 3. Add HID_Echo1.c to your project and build and download the application into the target. Connect your target to the host via USB while the example application is running, Windows will detect the new HID device. 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 target. The target will be in interactive mode. UM09001 User & Reference Guide for emUSB (c) 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 connect. 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 compile the HID host example application. Refer to http://www.microsoft.com/whdc/devtools/ddk/default.mspx for more information. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 316 CHAPTER 10 Human Interface Device Class (HID) 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() / Returns the number of bytes in the interUSB_HID_GetNumBytesInBufferEx() nal read buffer. USB_HID_GetNumBytesRemToRead() / Returns the number of bytes which still USB_HID_GetNumBytesRemToReadEx() have to be read. USB_HID_GetNumBytesToWrite() / Returns the number of bytes which still USB_HID_GetNumBytesToWriteEx() have to be written. USB_HID_Read() / USB_HID_ReadEx() Read data from the host. USB_HID_ReadEPOverlapped() / Non-blocking version of USB_HID_Read() USB_HID_ReadEPOverlappedEx() USB_HID_ReadTimed() / Starts a read operation that shall be done USB_HID_ReadExTimed() within a given timeout. USB_HID_StartReadTransfer() / Initiate a read data transfer. USB_HID_StartReadTransferEx() USB_HID_WaitForRX() / Waits for a non-blocking write operation USB_HID_WaitForRXEx() that is pending. USB_HID_WaitForTX() / Waits for a non-blocking write operation USB_HID_WaitForTXEx() that is pending. USB_HID_Write() / USB_HID_WriteEx() Write data to the host. USB_HID_WriteEPOverlapped() / Non-blocking version of USB_HID_WriteEPOverlappedEx() USB_HID_Write() USB_HID_WriteTimed() / Starts a write operation that shall be USB_HID_WriteExTimed() done within a given timeout. Data structures Initialization structure that is required USB_HID_INIT_DATA when adding a HID interface. Table 10.2: USB-HID target interface function list UM09001 User & Reference Guide for emUSB (c) 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); Parameter pInitData Description 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 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 318 CHAPTER 10 Human Interface Device Class (HID) 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 unsigned USB_HID_GetNumBytesInBufferEx Parameter hInterface (void); (USB_HID_HANDLE hInterface); Description Handle to a HID instance. Table 10.4: USB_HID_GetNumBytesInBuffer() / USB_HID_GetNumBytesInBufferEx() parameter list Return value >= 0 Number of bytes in the internal read buffer. UM09001 User & Reference Guide for emUSB (c) 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); Parameter hInterface Description Handle to a HID instance. Table 10.5: USB_HID_GetNumBytesRemToRead() / USB_HID_GetNumBytesRemToReadEx() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 320 CHAPTER 10 Human Interface Device Class (HID) 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 unsigned USB_HID_GetNumBytesToWriteEx (void); (USB_HID_HANDLE hInterface); Parameter hInterface Description Handle to a HID instance. Table 10.6: USB_HID_GetNumBytesToWrite() / USB_HID_GetNumBytesToWriteEx() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 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); Parameter hInterface pData NumBytes Description Handle to a HID instance. Pointer to a buffer where the received data will be stored. Number of bytes to read. Table 10.7: USB_HID_Read() / USB_HID_ReadEx() parameter list Return value >= 0 Number of bytes that have been received. USB_STATUS_ERROR In case of an error. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 322 CHAPTER 10 Human Interface Device Class (HID) 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); Parameter pData NumBytes Description Pointer to a buffer where the received data will be stored. Number of bytes to read. Table 10.8: USB_HID_ReadEPOverlapped() / USB_HID_ReadEPOverlappedEx() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 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); Parameter hInterface pData NumBytes ms Description Handle to a HID instance. Pointer to a buffer where the received data will be stored. Number of bytes to read. Timeout in milliseconds. Table 10.9: USB_HID_ReadTimed() / USB_HID_ReadExTimed() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 324 CHAPTER 10 Human Interface Device Class (HID) 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); Parameter hInterface Description Handle to a HID instance. Table 10.10: USB_HID_StartReadTransfer() / USB_HID_StartReadTransferEx() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 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 hInterface Description Handle to a HID instance. Table 10.11: USB_HID_WaitForRX() / USB_HID_WaitForRXEx() parameter list UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 326 CHAPTER 10 Human Interface Device Class (HID) 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 hInterface Description Handle to a HID instance. Table 10.12: USB_HID_WaitForTX() / USB_HID_WaitForTXEx() parameter list UM09001 User & Reference Guide for emUSB (c) 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 hInterface pData NumBytes Description Handle to a HID instance. Pointer to data that should be sent to the host. Number of bytes to write. Table 10.13: USB_HID_Write() / USB_HID_WriteEx() parameter list UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 328 CHAPTER 10 Human Interface Device Class (HID) 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); Parameter hInterface pData NumBytes Description Handle to a HID instance. Pointer to data that should be sent to the host. Number of bytes to write. Table 10.14: USB_HID_WriteEPOverlapped() / USB_HID_WriteEPOverlappedEx() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 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 hInterface pData NumBytes ms Description Handle to a HID instance. Pointer to data that should be sent to the host. Number of bytes to write. Timeout in milliseconds. Table 10.15: USB_HID_WriteTimed() / USB_HID_WriteExTimed() parameter list UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 330 CHAPTER 10 Human Interface Device Class (HID) 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; Member EPIn EPOut pReport NumBytesReport Description Endpoint for sending data to the host. Endpoint for receiving data from the host. Pointer to a report descriptor. Size of the HID report. Table 10.16: USB_HID_INIT_DATA elements 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 descriptor 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); } UM09001 User & Reference Guide for emUSB (c) 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 332 CHAPTER 10 Human Interface Device Class (HID) 10.6.1 Host API function list Function Description API functions Closes the connection an open device. Opens a handle to the device. Initializes the USB human interface USBHID_Init() device. USBHID_Exit() Closes the connection an open device. USBHID_GetNumAvailableDevices() Returns the number of available devices. USBHID_GetProductName() Returns the product name. Returns the input report size of the USBHID_GetInputReportSize() device. Returns the output report size of the USBHID_GetOutputReportSize() 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. USBHID_Close() USBHID_Open() Table 10.17: USB-HID host interface function list UM09001 User & Reference Guide for emUSB (c) 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 DeviceIndex Description Index of the HID device. This is the bit number of the mask returned by USBHID_GetNumDevices() Table 10.18: USBHID_Close() parameter list UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 334 CHAPTER 10 Human Interface Device Class (HID) 10.6.2.2 USBHID_Open() Description Opens a handle to the device that shall be opened. Prototype int USBHID_Open (unsigned Id) Parameter DeviceIndex Description Index of the HID device. This is the bit number of the mask returned by USBHID_GetNumDevices(). Table 10.19: USBHID_Open() parameter list Return value == 0: Opening was successful or already opened. == 1: Error. Handle to the device could not opened. UM09001 User & Reference Guide for emUSB (c) 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 information of the HID device. Prototype void USBHID_Init(U8 VendorPage); Parameter VendorPage Description 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 UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 336 CHAPTER 10 Human Interface Device Class (HID) 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 (c) 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); Parameter pMask Description 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 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 338 CHAPTER 10 Human Interface Device Class (HID) 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); Parameter DeviceIndex pBuffer NumBytes Description Index of the HID device. This is the bit number of the mask returned by USBHID_GetNumDevices(). Pointer to a buffer for the product name. Size of the pBuffer in bytes. Table 10.22: USBHID_GetProductName() parameter list Return value == 0: An error occured. == 1: On success. UM09001 User & Reference Guide for emUSB (c) 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); Parameter DeviceIndex Description Index of the HID device. This is the bit number of the mask returned by USBHID_GetNumDevices(). Table 10.23: USBHID_GetInputReportSize() parameter list Return value == 0: An error occured. != 0: Size of the report in bytes. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 340 CHAPTER 10 Human Interface Device Class (HID) 10.6.2.8 USBHID_GetOutputReportSize() Description Returns the output report size of the device. Prototype int USBHID_GetOutputReportSize(unsigned Id); Parameter DeviceIndex Description Index of the HID device. This is the bit number of the mask returned by USBHID_GetNumDevices(). Table 10.24: USBHID_GetOutputReportSize() parameter list Return value == 0: An error occured. != 0: Size of the report in bytes. UM09001 User & Reference Guide for emUSB (c) 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); Parameter DeviceIndex Description Index of the HID device. This is the bit number of the mask returned by USBHID_GetNumDevices(). Table 10.25: USBHID_GetProductId() parameter list Return value == 0: An error occured. != 0: Product Id. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 342 CHAPTER 10 Human Interface Device Class (HID) 10.6.2.10USBHID_GetVendorId() Description Returns the vendor Id of the device. Prototype U16 USBHID_GetVendorId(unsigned Id); Parameter DeviceIndex Description Index of the HID device. This is the bit number of the mask returned by USBHID_GetNumDevices(). Table 10.26: USBHID_GetVendorId() parameter list Return value == 0: An error occured. != 0: Vendor Id. UM09001 User & Reference Guide for emUSB (c) 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 connection list. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 344 CHAPTER 10 Human Interface Device Class (HID) 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 VendorPage Description 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 (c) 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 346 CHAPTER 11 Printer Class 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 (c) 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 #include #include #include "USB_PrinterClass.h" "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; UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 348 CHAPTER 11 Printer Class } /********************************************************************* * * _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 (c) 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 ***************************/ UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 350 CHAPTER 11 Printer Class 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 USB_PRINTER_Init() USB_PRINTER_Task() USB_PRINTER_API Description API functions Initializes the printer class. Processes the request from USB Host. Data structures 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 (c) 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); Parameter pAPI Description 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 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 352 CHAPTER 11 Printer Class 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 (c) 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 pfGetDeviceIdString pfOnDataReceived pfGetHasNoError pfGetIsSelected pfGetIsPaperEmpty pfOnReset Description 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;MANUFACTURER:Hewlett-Packard;DESCRIPTION:Hewlett-Packard LaserJet 6MP Printer;COMMAND SET:PJL,MLC,PCLXL,PCL,POSTSCRIPT;" This function is called when data arrives from USB host. This function should return a non-zero value if the printer has no error. This function should return a non-zero value if the printer is selected. This function should return a non-zero value if the printer is out of paper. The library calls this function if the USB host sends a soft reset command. Table 11.3: USB_PRINTER_API elements UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 354 UM09001 User & Reference Guide for emUSB CHAPTER 11 Printer Class (c) 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 Specification class and describes how to get the RNDIS component running on the target. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 356 CHAPTER 12 Remote NDIS (RNDIS) 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 running 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 emUSBRNDIS 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 (c) 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 UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 358 CHAPTER 12 12.2 Remote NDIS (RNDIS) Configuration 12.2.1 Initial configuration To get emUSB-RNDIS up and running as well as doing an initial test, the configuration 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 initialization. The functions should be implemented in the application. A sample implementation 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 provides 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 (c) 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 Organizationally 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 360 CHAPTER 12 Remote NDIS (RNDIS) 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 (c) 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 362 CHAPTER 12 Remote NDIS (RNDIS) 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 N Macro RNDIS_DEBUG_LEVEL Default 0 Description 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 (c) 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 endpoints 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 corresponding 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 connection to the IP stack. The HW address configured here is assigned to the PC network interface. The HW address of the IP stack is configured in the IP_X_Config() function of embOS/IP as described below. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 364 CHAPTER 12 Remote NDIS (RNDIS) // 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 (c) 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 customer 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 automatically. 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 366 CHAPTER 12 Remote NDIS (RNDIS) 12.5 Target API Function USB_RNDIS_Add() USB_RNDIS_Task() USB_RNDIS_INIT_DATA USB_RNDIS_EVENT_API USB_RNDIS_DRIVER_API USB_RNDIS_DRIVER_DATA Description API functions Adds a RNDIS-class interface to the USB stack. Handles the RNDIS protocol. Data structures Initialization data for RNDIS interface. API functions for OS event handling. Network interface driver API functions. 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 (c) 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); Parameter pInitData Description IN: Pointer to a USB_RNDIS_INIT_DATA structure. OUT: --- Table 12.4: USB_RNDIS_Add() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 368 CHAPTER 12 Remote NDIS (RNDIS) 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 (c) 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; Member EPIn EPOut EPInt pEventAPI pDriverAPI DriverData Description Endpoint for sending data to the host. Endpoint for receiving data from the host. Endpoint for sending status information. Pointer to the API for OS event handling. (See USB_RNDIS_EVENT_API on page 370) Pointer to the Network interface driver API. (See USB_RNDIS_DRIVER_API on page 371) Configuration data for the network interface driver. (See USB_RNDIS_DRIVER_DATA on page 377) Table 12.5: USB_RNDIS_INIT_DATA elements 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 370 CHAPTER 12 Remote NDIS (RNDIS) 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; Member (*pfCreate)() (*pfSignal)() (*pfWaitTimed)() Description Creates an OS event. Signals an OS event. Wait for an OS event to be signaled. Table 12.6: USB_RNDIS_EVENT_API elements 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. UM09001 User & Reference Guide for emUSB (c) 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; Member (*pfInit)() (*pfGetPacketBuffer)() (*pfWritePacket)() (*pfSetPacketFilter)() (*pfGetLinkStatus)() (*pfGetLinkSpeed)() (*pfGetHWAddr)() (*pfGetStats)() (*pfGetMTU)() (*pfReset)() Description Initializes the driver. Returns a buffer for a data packet. Delivers a data packet to target IP stack. Configures the type of accepted data packets. Returns the status of the connection to target IP stack. Returns the connection speed. Returns the HW address of the PC. Returns statistical counters. Returns the size of the largest data packet which can be transferred. Resets the driver. Table 12.7: USB_RNDIS_DRIVER_API elements 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 372 CHAPTER 12 Remote NDIS (RNDIS) (*pfInit)() Description Initializes the driver. Prototype void (*pfInit)(const USB_RNDIS_DRIVER_DATA * pDriverData); Parameter Description pDriverData IN: Pointer to driver configuration data. OUT: --- Table 12.8: (*pfInit)() parameter list 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); Parameter Description Size of the requested buffer in bytes. NumBytes Table 12.9: (*pfGetPacketBuffer)() parameter list Return value !=NULL ==NULL Pointer to allocated buffer 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); Parameter pData NumBytes Description IN: Data of the received packet. OUT: --Number of bytes stored in the buffer. Table 12.10: (*pfWriteBuffer)() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 373 (*pfSetPacketFilter)() Description Configures the type of accepted data packets Prototype void (*pfSetPacketFilter)(U32 Mask); Parameter Mask Description Type of accepted data packets Table 12.11: (*pfSetPacketFilter)() parameter list 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 ==USB_RNDIS_LINK_STATUS_DISCONNECTED Connected to target IP stack 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 374 CHAPTER 12 Remote NDIS (RNDIS) (*pfGetHWAddr)() Description Returns the HW address of PC Prototype void (*pfGetHWAddr)(U8 * pAddr, unsigned NumBytes); Parameter pAddr NumBytes Description IN: --OUT: The HW address Maximum number of bytes to store to pAddr Table 12.12: (*pfGetHWAddr)() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 375 (*pfGetStats)() Description Returns statistical counters. Prototype U32 (*pfGetStats)(int Type); Parameter Type Description 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 USB_RNDIS_STATS_WRITE_PACKET_ERROR USB_RNDIS_STATS_READ_PACKET_OK USB_RNDIS_STATS_READ_PACKET_ERROR USB_RNDIS_STATS_READ_NO_BUFFER USB_RNDIS_STATS_READ_ALIGN_ERROR USB_RNDIS_STATS_WRITE_ONE_COLLISION USB_RNDIS_STATS_WRITE_MORE_COLLISIONS Number of packets sent without errors to target IP stack Number of packets sent with errors to target IP stack Number of packets received without errors from target IP stack Number of packets received with errors from target IP stack Number of packets received from target IP stack but dropped. Number of packets received from target IP stack with alignment errors. Number of packets which were not sent to target IP stack due to the occurrence of one collision. Number of packets which were not sent to target IP stack due to the occurrence of one or more collisions. Return value Value of requested statistical counter. Additional information The counters should be set to 0 when the (*pfReset)() function is called. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 376 CHAPTER 12 Remote NDIS (RNDIS) (*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 (c) 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 pHWAddr NumBytesHWAddr Description HW address (or MAC address) of the host network interface. Number of bytes in the HW address. Typically 6 bytes. Table 12.14: USB_RNDIS_DRIVER_DATA elements UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 378 CHAPTER 12 Remote NDIS (RNDIS) 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; Member Description (*pfCreate) (*pfSignal) (*pfWaitTimed) Initializes the driver. Returns a buffer for a data packet. Delivers a data packet to target IP stack. Table 12.15: USB_RNDIS_EVENT_API elements (*pfCreate)() Description Creates a new OS event. Prototype void * (*pfCreate)(void); Return value !=0 ==0 Event has been created, the return value is the pointer to the event. 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); Parameter pEvent Description IN: Pointer to the OS event to be signaled. OUT: --- Table 12.16: (*pfSignal)() parameter list Example For a sample implementation refer to IP_Config_RNDIS.c in detail on page 363. UM09001 User & Reference Guide for emUSB (c) 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); Parameter Description IN: Pointer to the OS event to wait for. OUT: --Number of milliseconds to wait for the event to be signaled. pEvent Timeout Table 12.17: (*pfWaitTimed)() parameter list Return value ==0 !=0 Success, the event was signaled within the specified time. 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 380 UM09001 User & Reference Guide for emUSB CHAPTER 12 Remote NDIS (RNDIS) (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 381 Chapter 13 Combining different USB components (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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 382 face) CHAPTER 13 Combining different USB components (Multi-Inter- 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. Interface 0 MSD Endpoint IN Endpoint OUT Control EP0 IN/OUT Endpoint OUT Endpoint IN USB HOST Interface 1 HID USB Device UM09001 User & Reference Guide for emUSB (c) 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. Device descriptor Interface descriptor 0: BULK EP UM09001 User & Reference Guide for emUSB EP Interface descriptor 1: MSD EP EP Function 1 Function 0 Config descriptor (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 384 face) CHAPTER 13 Combining different USB components (Multi-Inter- 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 component that is defined in the device descriptor. This prevents the combination of multiple 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 decouples the multi-interface class from other interfaces. Device descriptor: IAD class Config descriptor Interface desc 0: Control EP Interface desc. 1: Data EP Interface desc. 2: MSD EP EP Function 1 Function 0 IA descriptor (IAD): CDC EP 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 UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 385 13.2 Configuration In general, no configuration is required. By default, emUSB supports up to four interfaces. If more interfaces are needed the following macro must be modified: Type Macro Default Numeric USB_MAX_NUM_IF 4 Numeric USB_MAX_NUM_IAD 1 UM09001 User & Reference Guide for emUSB Description Defines the maximum number of interfaces emUSB shall handle. Defines the maximum number of Interface Association Descriptors emUSB shall handle. (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 386 face) CHAPTER 13 Combining different USB components (Multi-Inter- 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 information, refer to emUSB component specific modification on page 388 and check the following 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 #include #include #include static static static static "RTOS.H" "USB.h" "USB_MSD.h" "USB_CDC.h" OS_STACKPTR int Stack0[512]; /* Task stacks for MSD task */ OS_STACKPTR int Stack1[512]; /* Task stacks for CDC task */ OS_TASK TCB0; /* Task-control-block for MSD task*/ 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 (c) 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() } UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 388 face) CHAPTER 13 Combining different USB components (Multi-Inter- 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 (c) 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 interfaces (in the example, 00 and 01). UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 390 face) CHAPTER 13 Combining different USB components (Multi-Inter- 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 identification 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 (c) 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 392 face) CHAPTER 13 Combining different USB components (Multi-Inter- 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 (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 393 Chapter 14 Target OS Interface This chapter describes the functions of the operating system abstraction layer. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 394 CHAPTER 14 Target OS Interface 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 (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 395 14.2 Interface function list Routine Explanation Delays for a given number of ms. Decrement interrupt disable count and enable interrupts if USB_OS_DecRI() 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. Block the task until USB_OS_Signal() is called or a timeout USB_OS_WaitTimed() occurs. USB_OS_Delay() Table 14.1: Target OS interface function list UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 396 CHAPTER 14 Target OS Interface 14.2.1 USB_OS_Delay() Description Delays for a given number of ms. Prototype void USB_OS_Delay(int ms); Parameter ms Description Number of ms. Table 14.2: USB_OS_Delay() parameter list UM09001 User & Reference Guide for emUSB (c) 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); UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 398 CHAPTER 14 Target OS Interface 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 (c) 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); UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 400 CHAPTER 14 Target OS Interface 14.2.5 USB_OS_Init() Description Initializes OS. Prototype void USB_OS_Init(void); UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 401 14.2.6 USB_OS_Panic() Description Halts emUSB. Prototype void USB_OS_Panic(unsigned ErrCode); Parameter ErrCode Description Error code. Table 14.3: USB_OS_Panic() parameter list Add. information Errorcode 1 2 3 4 5 6 7 Explanation USB_ERROR_RX_OVERFLOW USB_ERROR_ILLEGAL_MAX_PACKET_SIZE USB_ERROR_ILLEGAL_EPADDR USB_ERROR_IBUFFER_SIZE_TOO_SMALL USB_ERROR_DRIVER_ERROR USB_ERROR_IAD_DESCRIPTORS_EXCEED USB_ERROR_INVALID_INTERFACE_NO Table 14.4: USB_OS_Panic(): Errorcodes UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 402 CHAPTER 14 Target OS Interface 14.2.7 USB_OS_Signal() Description Wakes the task waiting for signal. Prototype void USB_OS_Signal(unsigned EPIndex); Parameter EPIndex Description Endpoint index. Table 14.5: USB_OS_Signal() parameter list Add. information This routine is typically called from within an interrupt service routine. UM09001 User & Reference Guide for emUSB (c) 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); Parameter EPIndex Description Endpoint index. Table 14.6: USB_OS_Wait() parameter list Add. information This routine is called from a task. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 404 CHAPTER 14 Target OS Interface 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); Parameter EPIndex ms Description Endpoint index. timeout time given in ms. Table 14.7: USB_OS_WaitTimed() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 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 example 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 * UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 406 CHAPTER 14 Target OS Interface * 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 (c) 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. * UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 408 CHAPTER 14 Target OS Interface */ 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 (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 409 Chapter 15 Target USB Driver This chapter describes emUSB hardware interface functions in detail. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 410 CHAPTER 15 Target USB Driver 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) ATMEL AV32 UC3x ATMEL AT91CAP9x ATMEL AT91SAM3S/AT91SAM4S ATMEL AT91SAM3Uxx ATMEL AT91SAM3x8 ATMEL AT91RM9200 ATMEL AT91SAM7A3 ATMEL AT91SAM7S64 ATMEL AT91SAM7S128 ATMEL AT91SAM7S256 ATMEL AT91SAM7SE ATMEL AT91SAM7X128 ATMEL AT91SAM7X256 ATMEL AT91SAM9260 ATMEL AT91SAM9261 ATMEL AT91SAM9263 ATMEL AT91SAM9R64 ATMEL AT91SAM9RL64 ATMEL AT91SAM9G20 ATMEL AT91SAM9G45 ATMEL AT91SAM9XE EnergyMicro EFM32GG Freescale iMX25x Freescale iMX28x Freescale Kinetis K40 Freescale Kinetis K60 Freescale MCF227x Freescale MCF225x Freescale MCF51JMx Freescale Vybrid Fujitsu MB9BF50x NXP LPC13xx Identifier USB_Driver_Atmel_AT32UC3x USB_Driver_Atmel_CAP9 USB_Driver_Atmel_SAM3S USB_Driver_Atmel_SAM3US USB_Driver_Atmel_AT91SAM3X USB_Driver_Atmel_RM9200 USB_Driver_Atmel_SAM7A3 USB_Driver_Atmel_SAM7S USB_Driver_Atmel_SAM7S USB_Driver_Atmel_SAM7S USB_Driver_Atmel_SAM7SE USB_Driver_Atmel_SAM7X USB_Driver_Atmel_SAM7X USB_Driver_Atmel_SAM9260 USB_Driver_Atmel_SAM9261 USB_Driver_Atmel_SAM9263 USB_Driver_Atmel_SAMRx64 USB_Driver_Atmel_SAM9G20 USB_Driver_Atmel_SAM9G45 USB_Driver_Atmel_SAM9XE USB_Driver_EM_EFM32GG990 USB_Driver_Freescale_iMX25x USB_Driver_Freescale_iMX28x USB_Driver_Freescale_K40 USB_Driver_Freescale_K60 USB_Driver_Freescale_MCF227x USB_Driver_Freescale_MCF225x USB_Driver_Freescale_MCF51JMx USB_Driver_Freescale_Vybrid USB_Driver_Fujitsu_MB9BF50x USB_Driver_NXP_LPC13xx Table 15.1: List of included USB device drivers UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 411 Driver (Device) NXP LPC17xx NXP LPC18xx NXP LPC214x NXP LPC23xx NXP LPC24xx NXP LPC313x NXP LPC318x NXP LPC43xx NXP (formerly Sharp) LH79524/5 NXP (formerly Sharp) LH7A40x OKI 69Q62 Renesas H8S2472 Renesas H8SX1668R Renesas RX62N Renesas RX63N/RX631 Renesas SH7203 Renesas SH7216 Renesas SH7286 Renesas (NEC) 78K0R-KE3L Renesas (NEC) PD720150 Renesas (NEC) V850ESJG3H ST STM32 ST STM32F105/107 ST STR71x ST STR750 ST STR912 Toshiba TMPA900 Toshiba TMPA910 Texas Intruments MSP430X5529 Texas Intruments (Luminary) LM3S9B9x Identifier USB_Driver_NXP_LPC17xx USB_Driver_NXP_LPC18xx USB_Driver_NXP_LPC214x USB_Driver_NXP_LPC23xx USB_Driver_NXP_LPC24xx USB_Driver_NXP_LPC313x USB_Driver_NXP_LPC318x USB_Driver_NXP_LPC43xx USB_Driver_Sharp_LH79524 USB_Driver_Sharp_LH7A40x USB_Driver_OKI_69Q62 USB_Driver_Renesas_H8S2472 USB_Driver_Renesas_H8SX1668R USB_Driver_Renesas_RX62N USB_Driver_Renesas_RX62N USB_Driver_Renesas_SH7203 USB_Driver_Renesas_SH7216 USB_Driver_Renesas_SH7286 USB_Driver_NEC_78F102x USB_Driver_NEC_uPD720150 USB_Driver_NEC_70F376x USB_Driver_ST_STM32 USB_Driver_ST_STM32F107 USB_Driver_ST_STR71x USB_Driver_ST_STR750 USB_Driver_ST_STR91x USB_Driver_Toshiba_TMPA900 USB_Driver_Toshiba_TMPA910 USB_Driver_TI_MSP430 USB_Driver_TI_LM3S9B9x Table 15.1: List of included USB device drivers UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 412 CHAPTER 15 Target USB Driver 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 (c) 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 #define #define #define #define #define #define #define #define #define #define _AT91C_PIOA_BASE (0xFFFFF400) _AT91C_PIOB_BASE (0xFFFFF600) _AT91C_PMC_BASE (0xFFFFFC00) _PIO_PER_OFFS (0x00) _PIO_OER_OFFS (0x10) _PIO_CODR_OFFS (0x34) /* Clear output data register */ _PMC (*(volatile unsigned int*) _AT91C_PMC_BASE) _USB_ID (_PIOB_ID) _USB_OER (*(volatile unsigned int*) (_AT91C_PIOB_BASE + _PIO_OER_OFFS)) _USB_CODR (*(volatile unsigned int*) (_AT91C_PIOB_BASE + _PIO_CODR_OFFS)) _USB_DP_PUP_BIT (1) void USB_X_HWAttach(void) { _PMC = (1 << _USB_ID); _USB_OER = (1 << _USB_DP_PUP_BIT); _USB_CODR = (1 << _USB_DP_PUP_BIT); } UM09001 User & Reference Guide for emUSB /* Enable peripheral clock for USB-Port */ /* set USB_DP_PUP to output */ /* set _USB_DP_PUP_BIT to low state */ (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 414 CHAPTER 15 Target USB Driver 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 (c) 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 system. If you use embOS in combination with emUSB, you can skip the following sections. 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 interrupts, how and which registers are saved, the interrupt vector table, how the interrupt 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 environment of the interrupted function has to be restored after processing the interrupt. The environment of the interrupted function includes the value of the processor registers 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 Interrupt specific handler USB 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. Interrupt specific handler Purpose: Handles USB data transfer. Part of emUSB driver. Coded in C. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 416 CHAPTER 15 Target USB Driver 15.3.1.1 ARM specific IRQ handler The ARM specific interrupt handler saves the context of the function which is interrupted, calls the high-level interrupt handler and restores the context. Sample implementations 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 (c) 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 handler function. Sample implementation interrupt handler #define _AIC_BASE_ADDR #define _AIC_IVR #define _AIC_EOICR typedef void (0xfffff000UL) (*(volatile unsigned int*)(_AIC_BASE_ADDR + 0x100)) (*(volatile unsigned int*)(_AIC_BASE_ADDR + 0x130)) ISR_HANDLER(void); void IRQ_Handler(void) { ISR_HANDLER* pISR; pISR = (ISR_HANDLER*) _AIC_IVR; pISR(); _AIC_EOICR = 0; // // // // // Read interrupt vector to release NIRQ to CPU core Call interrupt service routine 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 specifics 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 specifics 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 specifics 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 specifics 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 specifics 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 specifics 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 specifics ATMEL AT91CAP9x on page 417. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 418 CHAPTER 15 Target USB Driver 15.3.1.10Device specifics ATMEL AT91SAM9263 For an example implementation of an interrupt handler function refer to Device specifics 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 specifics ATMEL AT91CAP9x on page 417. UM09001 User & Reference Guide for emUSB (c) 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 handler function. Sample implementation interrupt handler #define _VIC_BASE_ADDR #define _VIC_VECTORADDR typedef void (0xFFFFF000) *(volatile unsigned int*)(_VIC_BASE_ADDR + 0x0030) ISR_HANDLER(void); void IRQ_Handler(void) { ISR_HANDLER* pISR; pISR = (ISR_HANDLER*) _VIC_VECTORADDR; pISR(); _VIC_VECTORADDR = 0; // // // // Get current interrupt handler Call interrupt service routine 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 specifics 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 SEGGER, www.segger.com . 15.3.1.15Device specifics OKI 69Q62 For an example implementation of an interrupt handler function, please contact SEGGER, www.segger.com . 15.3.1.16Device specifics ST STR71x For an example implementation of an interrupt handler function, please contact SEGGER, www.segger.com . 15.3.1.17Device specifics ST STR750 For an example implementation of an interrupt handler function, please contact SEGGER, www.segger.com . 15.3.1.18Device specifics ST STR750 For an example implementation of an interrupt handler function, please contact SEGGER, www.segger.com . UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 420 CHAPTER 15 Target USB Driver 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. Used to support additional driver functionality. pfControl This function is optional. Notifies the USB controller of the new address pfSetAddress() assigned by the host for it. General endpoints functions pfAllocEP Allocates an endpoint to be used with emUSB. Returns the maximum packet size of an endpfGetMaxPacketSize point. Set or cleats the stall condition of the endpfSetClrStallEP() point. pfUpdateEP() Configures the USB controller's endpoint. Resets an endpoint including resetting the pfResetEP() 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 (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 421 Member pfStallEP0() pfDisableRxInterruptEP() pfEnableRxInterruptEP() pfDisableTx pfSendEP() pfStartTx() Description Stalls endpoint 0. OUT-endpoints functions Disables OUT-endpoint interrupt. Enables OUT-endpoint interrupt. IN-endpoints functions Disables IN endpoint transfers. Sends data on the given IN-endpoint. Starts data transfer on the given IN-endpoint. Table 15.2: List of callback functions of USB_HW_DRIVER UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 422 CHAPTER 15 Target USB Driver 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 interrupts needed for USB operations. UM09001 User & Reference Guide for emUSB (c) 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); Parameter Description Command that shall be executed. Pointer to data, necessary for the command. Cmd p Table 15.3: (*pfControl)() parameter list 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: Command 0 1 Description USB_DRIVER_CMD_SET_CONFIGURATION USB_DRIVER_CMD_GET_TX_BEHAVIOR Table 15.4: (*pfControl): Commands UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 424 CHAPTER 15 Target USB Driver 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); Parameter Addr Description New address assigned by the USB host. Table 15.5: (*pfSetAddress)() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 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); Parameter Description Indicates the direction of the endpoint. 0 indicates an OUT-endpoint. 1 indicates an IN-endpoint. Specifies the transfer type for the desired endpoint. The following transfer types are available: TransferType USB_TRANSFER_TYPE_BULK USB_TRANSFER_TYPE_ISO USB_TRANSFER_TYPE_INT InDir Table 15.6: (*pfAllocEP)() parameter list 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); Parameter EPIndex Description Endpoint index. Table 15.7: (*pfGetMaxPacketSize)() parameter list Return value The maximum packet size in bytes. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 426 CHAPTER 15 Target USB Driver 15.4.4.3 (*pfSetClrStallEP)() Description Sets or clears the stall condition of an endpoint. Prototype void (*pfSetClrStallEP)(U8 EPIndex, int OnOff); Parameter EPIndex OnOff Description Endpoint that shall be stalled. 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 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); Parameter pEPStat Description Pointer to EP_STAT structure that holds the information for the endpoint. Table 15.9: (*pfUpdateEP)() parameter list Additional information EP_STAT is defined as follows: typedef struct U16 U16 U16 U8 BUFFER U8 * volatile U32 U8 U8 } EP_STAT; { NumAvailBuffers; MaxPacketSize; Interval; EPType; Buffer; pData; NumBytesRem; EPAddr; // b[6:0]: EPAddr b7: Direction, 1: Device to Host (IN) Send0PacketIfRequired; Before a hardware attach is done, this function is called to configure the desired endpoints, so that the additional endpoints are ready for use after the enumeration phase. UM09001 User & Reference Guide for emUSB (c) 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); Parameter EPIndex Description Endpoint that shall be reset. Table 15.10: (*pfResetEP)() parameter list 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 428 CHAPTER 15 Target USB Driver 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 control register). Prototype void (*pfStallEP0)(void); UM09001 User & Reference Guide for emUSB (c) 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); Parameter EPIndex Description OUT-endpoint whose interrupt needs to be disabled. Table 15.11: (*pfDisableRxInterruptEP)() parameter list 15.4.6.2 (*pfEnableRxInterruptEP)() Description Enables the OUT-endpoint interrupt. Prototype void (*pfEnableRxInterruptEP)(U8 EPIndex); Parameter EPIndex Description OUT-endpoint whose interrupt needs to be enabled. Table 15.12: (*pfEnableRxInterruptEP)() parameter list UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 430 CHAPTER 15 Target USB Driver 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); Parameter EPIndex Description IN-endpoint that needs to be enabled. Table 15.13: (*pfStartTX)() parameter list 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 application 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); Parameter EPIndex p NumBytes Description IN-endpoint that is used to send the data. Pointer to a buffer that needs to be sent. Number of bytes that needs to be sent. Table 15.14: (*pfSendEP)() parameter list 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 alignment of the USB controller buffer/FIFO. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 431 15.4.7.3 (*pfDisableTx)() Description Disables IN-endpoint transfers. Prototype void (*pfDisableTx)(U8 EPIndex); Parameter EPIndex Description IN-endpoint that needs to be disabled. Table 15.15: (*pfDisableTx)() parameter list Additional information Normally, this function should disable the IN-endpoint interrupt. Some USB controllers do not work correctly after the IN interrupt is disabled, therefore this should be done by the software. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 432 CHAPTER 15 Target USB Driver 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: USB interrupt occured RX? Yes No EP0? Yes Setup packet? Yes TX? No Read data No Yes Read Setup packet No Call USB__OnTx() Call USB__OnRX() Call USB_HandleSetup() USB reset occurred Call USB__OnReset() USB interrupt end Function USB__HandleSetup() USB__OnBusReset() USB__OnTx() USB__OnRx() USB__OnResume() USB__OnSuspend() Description Determines request type. Flushes the input buffer and set the "_IsInReset" flag. Handles a Tx transfer. Handles a Rx transfer. Resumes the device. Suspends the device. Table 15.16: emUSB interrupt handling functions UM09001 User & Reference Guide for emUSB (c) 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. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 434 CHAPTER 16 Support 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 warnings. 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 (c) 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 UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 436 UM09001 User & Reference Guide for emUSB CHAPTER 16 Support (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 437 Chapter 17 Certification This chapter describes the process of USB driver certification with Microsoft Windows. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 438 CHAPTER 17 Certification 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 (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 439 17.2 Certification offer Customers can complete the certification by themselves. But SEGGER also offers certification 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 confirmation. 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 product. 17.4 Certification without SEGGER Microcontroller Certification can be completed by the customer themselves. To complete the certification 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 respectively. After installing and setting up the WLK, the client software has to be downloaded 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 consolidated 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 certification process. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 440 UM09001 User & Reference Guide for emUSB CHAPTER 17 Certification (c) 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 information about the memory requirements in typical systems which can be used to obtain sufficient estimates for most target systems. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 442 CHAPTER 18 Performance & resource usage 18.1 Memory footprint emUSB is designed to fit many kinds of embedded design requirements. Several features 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 compiled for size optimization. 18.1.1 ROM The following table shows the ROM requirement of emUSB: Description ROM emUSB core Bulk component app. 5.5 Kbytes app. 400 Bytes app. 5 Kbytes + sizeof(StorageLayer)* app. 400 Bytes app. 1.1 Kbytes app. 400 Bytes app. 1.2 - 3 Kbytes app. 8 kBytes MSD component HID component CDC component PrinterClass component USB target driver MTP component * ROM size of emFile Storage app. 4 Kbytes. 18.1.2 RAM The following table shows the RAM requirement of emUSB: Description emUSB core Bulk component MSD component HID component CDC component PrinterClass component USB target driver MTP component RAM app. 800 Bytes app. 4 Bytes app. 200 Bytes + configurable sector buffer of minimum 512 bytes app. 30 Bytes app. 70 Bytes app. 2 Kbytes < 1 Kbytes app. 200 bytes + configurable file data buffer of minimum 512 bytes + configurable object buffer (typically 4 kBytes). 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. UM09001 User & Reference Guide for emUSB (c) 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 Receive speed UM09001 User & Reference Guide for emUSB 800 KByte/sec 760 KByte/sec (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 444 UM09001 User & Reference Guide for emUSB CHAPTER 18 Performance & resource usage (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 445 Chapter 19 FAQ This chapter answers some frequently asked questions. UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 446 CHAPTER 19 FAQ Q: A: Which CPUs can I use emUSB with? It can be used with any CPU (or MPU) for which a C compiler exists. Of course, it will work faster on 16/32-bit CPUs than on 8-bit CPUs. Q: A: Do I need a real-time operating system (RTOS) to use the USB-MSD? 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: A: Do I need extra file system code to use the USB-MSD stack? 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: A: Can I combine different USB components together? 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 (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG Index 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 UM09001 User & Reference Guide for emUSB 447 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 (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG 448 Index USB_MSD_Task() ..................... 198, 237 USB_MSD_WaitForDisconnection() .... 203 O OS USB_OS_DecRI() ............................ USB_OS_Delay() ............................ USB_OS_GetTickCnt() ..................... USB_OS_IncDI() ............................. USB_OS_Init() ............................... USB_OS_Panic() ............................. USB_OS_Signal() ............................ USB_OS_Wait() .............................. USB_OS_WaitTimed() ...................... 397 396 398 399 400 401 402 403 404 S Support .................................... 433-446 Syntax, conventions used ....................... 7 (*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 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 UM09001 User & Reference Guide for emUSB (c) 2010 - 2015 SEGGER Microcontroller GmbH & Co. KG