usb

April 4, 2018 | Author: Fernandez Shian | Category: C Sharp (Programming Language), Usb, Library (Computing), Device Driver, Areas Of Computer Science


Comments



Description

1541 USB2USB: Bridging the gap between PC application and end device Class Objectives  When you finish this class you will:   Understand the benefits/limitations of various USB device classes for implementing generic data transfer Be able to implement generic data transfers between a Windows® PC and a PIC® MCU running as a HID or Custom Class (WinUSB) USB Device © 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 2 Agenda       Application Overview (Thermometer) Full-Speed USB Review Debugging USB Applications Microchip USB Framework (MCHPFSUSB) .NET Framework Basics Building a HID Class Thermometer   Lab 1 – HID Class Thermometer Building a Custom Class Thermometer Using WinUSB  Lab 2 – Custom Class Thermometer using WinUSB © 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 3 Agenda (Continued)   Matching a Driver to a Device Detecting Devices  Finding Your Device    Obtaining a Handle Handling Attach/Detach Events   Lab 3a – Find Your Device Lab 3b – WinUSB Thermometer using WM_DEVICECHANGE Summary & References © 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 4 . Embedded Host.0 Device. OTG PIC24F Mid-Range. Low Cost Up to 12 MIPS 18.to 80-Pin Packages Up to 128 KB Flash Up to 4 KB RAM USB 2. 80. OTG PIC18F 32-bit Small. family and software migration path PIC32 High Performance.& 100-Pin Packages Up to 512 KB Flash Up to 32 KB RAM USB 2. Capacitive-Touch Capable Up to 16 MIPS 64-.& 100-Pin Packages Up to 256 KB Flash Up to 16 KB RAM USB 2.0 Device. Low Power. All Rights Reserved. 1. Pin Compatible to PIC24F 80 MHz. Embedded Host.0 Device Support 16-bit 8-bit Migration © 2011 Microchip Technology Incorporated.Scalable USB PIC® MCU Portfolio Performance ~40 USB PIC MCUs The industry’s strongest scalable product.53 DMIPS/MHz Up to 80 MIPS 64. 1541 USB2 Slide 5 . Lab3 \Device \Device Solution \Host \Host Solution \Microchip \Presentation and Handouts \Users Guides & Data Sheets © 2011 Microchip Technology Incorporated.Class Folders C:\Masters\1541 \Development Tools \Lab1. 1541 USB2 Slide 6 .. All Rights Reserved. Application Overview (Thermometer) . 1541 USB2 Slide 8 .Outline .Application Overview  Application Requirements    Commands (see Appendix E in lab manual):      Demonstrate moving data between PC Application and end device via USB The data is Temperature 0 – get Version 1 – get Temperature 2 – get Potentiometer Platform: PIC18F Starter Kit 1 (DM180021) PIC18F46J50 Features © 2011 Microchip Technology Incorporated. All Rights Reserved. Board Key Components On Board Debugger (provides SYS CLK) © 2011 Microchip Technology Incorporated. 1541 USB2 Slide 9 . All Rights Reserved. 1541 USB2 Slide 10 .Board Key Components PIC18F46J50 © 2011 Microchip Technology Incorporated. All Rights Reserved. All Rights Reserved. 1541 USB2 Slide 11 .Board Key Components Capacitive Touch Buttons and Scroll Bar © 2011 Microchip Technology Incorporated. Board Key Components Organic LED display © 2011 Microchip Technology Incorporated. 1541 USB2 Slide 12 . All Rights Reserved. Board Key Components 3 Axis Acceleration Sensor (BMA150) © 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 13 . 1541 USB2 Slide 14 .Board Key Components I/O Expansion © 2011 Microchip Technology Incorporated. All Rights Reserved. All Rights Reserved. 1541 USB2 Slide 15 .Board Key Components S1 Menu Button © 2011 Microchip Technology Incorporated. 1541 USB2 Slide 16 . All Rights Reserved.Board Key Components MicroSD Memory Card © 2011 Microchip Technology Incorporated. All Rights Reserved.Board Key Components Potentiometer © 2011 Microchip Technology Incorporated. 1541 USB2 Slide 17 . All Rights Reserved. 1541 USB2 Slide 18 .Board Key Components mini-B USB Receptacle © 2011 Microchip Technology Incorporated. 13-Channel Analog-to-Digital Converter Two Enhanced USART Peripheral Pin Select (PPS) Nanowatt XLP Technology © 2011 Microchip Technology Incorporated. 1541 USB2 Slide 19 . All Rights Reserved.PIC18F46J50 Features           Parallel Master Port (PMP) Real-Time Clock and Calendar (RTCC) USB FS Device Capability Charge Time Measurement Unit (CTMU) Master Synchronous Serial Port (MSSP) Enhanced Capture/Compare/PWM (ECCP) 10-Bit. Full-Speed USB Review . Printer 1541 USB2 Speaker Slide 21 . All Rights Reserved.Full-Speed USB Basics   USB is a “Single Master + Multiple Slaves” polled bus In/Out WRT host USB Host Controller (Master) and Root Hub Mouse © 2011 Microchip Technology Incorporated. Logical Device  Up to 16 bidirectional pipelines    “End Points” Data CRC-32 protected Bad packets auto resent* Host EP1-16 Device EP0 © 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 22 . inf file Host associates driver Vendor & Product ID © 2011 Microchip Technology Incorporated.Enumeration  Enumeration process        EP0 “Control Endpoint” Chapter 9 commands Descriptors Dynamic address . 1541 USB2 Slide 23 . All Rights Reserved. 1541 USB2 Slide 24 . All Rights Reserved.Transfer types  Control   Interrupt   Low rate/bounded latency Bulk   Bus configuration Guaranteed integrity Isochronous  Guaranteed timeliness © 2011 Microchip Technology Incorporated. # Data Bytes/Frame/Endpoint (Max# transactions per frame @ Max Ep Size)* Data Integrity Interrupt Fixed. Periodic 90 1023 (1 x 1023) No Bulk Variable. Periodic 90 64 (1 x 64) Yes Isochronous Fixed.Full Speed USB - Transfer/ Endpoint Type Polling Interval % Reserved BW/Frame for all transfers of this type Max. 1541 USB2 Slide 25 .Maximum Transfer Rates . Uses Free Bandwidth 0 1216 (19 x 64) Yes Control Variable 10 832 (13 x 64) Yes *Assumes transfers use maximum packet sizes allowed per Ep type © 2011 Microchip Technology Incorporated. All Rights Reserved. All Rights Reserved. © 2011 Microchip Technology Incorporated. 1541 USB2 Slide 26 .USB Device Classes Thumb Drive Data Glove Ethernet Adapter Mouse External Hard Drive PICkit™ 2 Starter Kit Joystick Mass Storage Device Class (MSD) COM Port MCP2200 Communication Device Class (CDC) Keyboard ICD2 Custom Class (Vendor Class) Human Interface Device Class (HID) Many more classes…. 1541 USB2 Slide 27 .Considerations When Using Standard Classes  The Logical USB Device is predefined   Max. All Rights Reserved. bandwidth is fixed The Device data communication protocol is defined  For CDC Class:  The PIC® MCU looks like a modem. or terminal connected to a serial portsome implications:   PIC MCU may need to reply to “class-specific” requests – which have nothing to do with your application (wastes some USB bandwidth) Main Benefit: Cross-platform use  Custom OS driver is not required! © 2011 Microchip Technology Incorporated. 6) Driver support built into Windows Yes Need .0. 1541 USB2 Slide 28 .sys CDC WinUSB LibUSB (v1.inf No 64-bit PC Support Yes Yes Yes Yes Yes XP Ready Yes Yes Yes Yes Yes Vista/Win7 Ready Yes Yes Yes Yes No** Control Yes No Yes Yes Yes Interrupt Yes No Yes Yes Yes Bulk No Yes Yes Yes Yes 64KB/s ~64kByte/s ~1.USB Driver Choices Features HID mchpusb.0.inf No Need . All Rights Reserved.0 MB/s ~1.0MB/s ~1.0MB/s Transfer Types Max Speed © 2011 Microchip Technology Incorporated. Microchip USB Framework (MCHPFSUSB) . com/mal Contains different stacks (USB.) Default installation path: C:/Microchip Solutions YYYY-MM-DD/  Contains libraries source code and several example firmware projects based on Microchip’s Development Tools © 2011 Microchip Technology Incorporated. mTouch™ Sensing Solution. TCP/IP. Graphics. etc.Downloading the Microchip Application Libraries    Download from www. 1541 USB2 Slide 30 .microchip. All Rights Reserved. 1541 USB2 Slide 31 . All Rights Reserved.Default Install Directory C:/Microchip Solutions YYYY-MM-DD/ © 2011 Microchip Technology Incorporated. 1541 USB2 Slide 32 . All Rights Reserved.Default Install Directory C:/Microchip Solutions YYYY-MM-DD/USB © 2011 Microchip Technology Incorporated. 1541 USB2 Slide 33 .Supported Platforms -  Low Pin Count USB Development Kit (PIC18F14K50 Family)  PICDEM™ Full Speed USB (PIC18F4550 family)  PIC18F Starter Kit 1 (PIC18F46J50 family)  PIC18F46J50 FS USB Demo Board (+ HPC Explorer Board)  PIC18F87J50 FS USB Demo Board (+ HPC Explorer Board)  PIC24F Starter Kit 1 (PIC24FJ256GB110 family)  PIC24F USB PIM (+ Explorer 16 + USB PICtail™ Plus)  PIC32 USB PIM (+ Explorer 16 + USB PICtail Plus)  PIC32 USB Starter Board (PIC32MX460F512L family)  PIC32 USB Starter Board II (PIC32MX795F512L family) © 2011 Microchip Technology Incorporated. All Rights Reserved.MCHPFSUSB Framework . c usb_descriptors.h usb_config.Generic USB Project  General structure . All Rights Reserved.h . 1541 USB2 Slide 34 ./Microchip /Include /USB /Common /… © 2011 Microchip Technology Incorporated.c Editable files HardwareProfile./USB/Your application main. // Product ID … © 2011 Microchip Technology Incorporated.Editable Files  usb_descriptors. // Vendor ID 0x0000. 1541 USB2 Slide 35 . // Size of this descriptor (byte) USB_DESCRIPTOR_DEVICE. // Protocol code EP0_BUFF_SIZE. // Max packet size for EP0 0x0000. // USB Spec Release Number My_Class_code. All Rights Reserved.MCHPFSUSB Framework . // Class code My_Subclass_code.c  Define your device descriptors    VID & PID Class Specific (may not need to change) Strings /* Device Descriptor */ ROM USB_DEVICE_DESCRIPTOR device_dsc= { 0x12. // DEVICE descriptor type 0x0200. // Subclass code My_Protocol_code. h  Defines your board & hardware initialization routines for your board // #define USE_SELF_POWER_SENSE_IO #define tris_self_power TRISAbits.RA2 #else #define self_power 1 #endif //#define USE_USB_BUS_SENSE_IO #define tris_usb_bus_sense TRISAbits.TRISA2 #if defined (USE_SELF_POWER_SENSE_IO) #define self_power PORTAbits.RA1 #else #define USB_BUS_SENSE 1 #endif © 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 // Input // Input Slide 36 .Editable Files  HardwareProfile.MCHPFSUSB Framework .TRISA1 #if defined (USE_USB_BUS_SENSE_IO) #define USB_BUS_SENSE PORTAbits. or 64 bytes. All Rights Reserved. //#define USB_POLLING #define USB_INTERRUPT //#define USB_SPEED_OPTION USB_LOW_SPEED //(not valid option // for PIC24F devices) #define USB_SPEED_OPTION USB_FULL_SPEED #define USB_SUPPORT_DEVICE #define USB_NUM_STRING_DESCRIPTORS 3 … /** DEVICE CLASS USAGE *************************************/ #define USB_USE_CDC … © 2011 Microchip Technology Incorporated.Editable Files  usb_config.MCHPFSUSB Framework . 1541 USB2 Slide 37 . // 16. 32.h  Define framework options (use configuration tool)    USB Definitions Device Class Usage Endpoint Allocation /** DEFINITIONS ********************************************/ #define USB_EP0_BUFF_SIZE 8 // Valid Options: 8. Editable Files  main.c   Contains UserInit() Main Loop USBDeviceTasks()     Polled or Interrupt-driven ProcessIO() Callback function() © 2011 Microchip Technology Incorporated. All Rights Reserved.MCHPFSUSB Framework . 1541 USB2 Slide 38 . MCHPFSUSB Framework . All Rights Reserved. 1541 USB2 Slide 39 . Use state machine.Polled Program Flow - Reset main() InitializeSystem() You edit UserInit() while(1) Cooperative Multitasking!! USBDeviceTasks() USB Stack ProcessIO() Your application code Function Services CDCTxService() MSDTasks() Re-arm OUT Endpoint (HID & Generic) No blocking functions. © 2011 Microchip Technology Incorporated. Interrupt Program Flow - Reset main() USB Interrupt Context InitializeSystem() You edit UserInit() USBDeviceAttach() Notifies the stack when the device is attached while(1) USBDeviceTasks() ProcessIO() Function Services © 2011 Microchip Technology Incorporated.MCHPFSUSB Framework . All Rights Reserved. 1541 USB2 Your application code CDCTxService() MSDTasks() Re-arm OUT Endpoint (HID & Generic) Slide 40 . Cooperative Multitasking State Machine Main Loop Task A.2 .200us Task A Task A.3 . All Rights Reserved. Max Loop Time 500us VS. 1000us 1541 USB2 Slide 41 .400us 900us Task A.100us © 2011 Microchip Technology Incorporated.1 .300us Task B . } } Conditional compiling (No need to change) No need to change © 2011 Microchip Technology Incorporated.h” #include “. … Put your application code (state machine) here … CDCTxService(). USBDeviceInit().h” Needed (usb_config.Code Example Main.h is called by usb./USB/usb_function_cdc. } int main(void){ InitializeSystem(). 1541 USB2 USBDeviceTasks() is executed into an ISR (High Priority PIC18.c #include “. All Rights Reserved.h) void UserInit(void){ … Put your initzialization code here … } void ProcessIO(void){ if((USBDeviceState < CONFIGURED_STATE)||(USBSuspendControl==1)) return.h” #include “HardwareProfile. while(1){ USBDeviceTasks(). } static void InitializeSystem(void){ #if define … #endif UserInit(). ProcessIO()./USB/usb. _USB1Interrupt() PIC24 & PIC32) Slide 42 . c © 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 43 .Call Back Function  The USB firmware stack will call a callback function in response to certain USB related events Application Layer CALLBACK FUNCTION MAIN PROGRAM USB firmware stack   LIBRARY FUNCTION Modify that callback function to take appropriate actions for each of these conditions Bottom of main. Debugging USB Applications . 1541 USB2 Slide 45 . All Rights Reserved.Hardware Protocol Analyzer    The most useful tool for USB debugging Captures signals in a cable segment and decodes/displays the data down to each individual byte Typical Scenarios    View the device enumeration process View protocol-specific communications (HID. MSD) Understand bus bandwidth utilization © 2011 Microchip Technology Incorporated. All Rights Reserved.Hardware Protocol Analyzer Image © USB Complete: The Developer’s Guide by Jan Axelson © 2011 Microchip Technology Incorporated. 1541 USB2 Slide 46 . totalphase. All Rights Reserved. Linux & MAC US $1200 © 2011 Microchip Technology Incorporated.com)       Non-obtrusive real-time monitoring Monitors USB 2. 1541 USB2 (Image © Total Phase Inc.) Slide 47 . FS. HS Protocol-level decoding Real-time filtering Data Center Software runs on PC.Hardware Protocol Analyzer  Beagle 480 (www.0 LS. Using the Beagle 480  Capturing a transaction © 2011 Microchip Technology Incorporated. 1541 USB2 Slide 48 . All Rights Reserved. NET Framework Basics .. NET C++ Language Visual C++ 2008 Express Making Calls to Unmanaged DLLs © 2011 Microchip Technology Incorporated.NET Framework?         Common Language Runtime (CLR) Framework Class Library Namespaces & Assemblies Common Type System Compilation in the .NET Framework Basics   Modern PC Application Development Requirements What is the . 1541 USB2 Slide 50 . All Rights Reserved.Outline ..NET Framework C++/CLI: The . All Rights Reserved. 1541 USB2 Slide 51 .Modern PC Application Development Requirements      Simplified GUI and application development Platform Independence Applications can be developed using multiple languages Local and distributed over the internet New security and reliability features  Control code and/or give rights to certain actions and deny others © 2011 Microchip Technology Incorporated. All Rights Reserved.What is the .NET Framework?  Microsoft Visual Basic .NET C++ C# … …  Common Language Specification Framework Class Library Common Language Runtime Windows   Linux An abstraction layer over an existing OS Allows applications compiled into a special intermediate language (IL) to run in a “managed” environment Based on ECMA/ISO/IEC CLI standard 2 available implementations   © 2011 Microchip Technology Incorporated.NET Framework Novell’s Mono Project Slide 52 . 1541 USB2 Microsoft . Common Language Runtime (CLR)  A virtual machine  Microsoft Visual Basic . All Rights Reserved.NET assemblies. Verifies that the IL code is “safe” to execute.  Common Language Runtime Windows  Linux  © 2011 Microchip Technology Incorporated.NET C++ C# … …  Common Language Specification Framework Class Library Loads . 1541 USB2 Argument type checking Invokes a JIT compiler to compile the IL to native code before execution Garbage collection Slide 53 . 1541 USB2 Classes for File/Stream IO Classes for Windows GUI apps Slide 54 . All Rights Reserved.Framework Class Library (FCL)  Microsoft Visual Basic .NET C++ C# … … Common Language Specification Framework Class Library   A set of thousands of classes that provide system services Wrap Win32 APIs & more Examples  Common Language Runtime System::IO  Windows Linux  System::Windows:: Forms  © 2011 Microchip Technology Incorporated. Using Class Libraries (1/2)  .NET projects must have “references” to the Class Library DLLs so that their code can be linked in .dll” © 2011 Microchip Technology Incorporated. 1541 USB2 Slide 55 . All Rights Reserved.or #using “HID class. Windows.Forms. 1541 USB2 Slide 56 .dll” using namespace System::Windows::Forms. you can use the “using namespace” statement to avoid having to type the fully qualified name #using “System. World!”).Using Class Libraries (2/2)  To use a method from a particular class library. // Fully-qualified name: // System::Windows::Forms::MessageBox:Show(“Hello. int main() { MessageBox::Show(“Hello. All Rights Reserved. World!”). } © 2011 Microchip Technology Incorporated. Common Language Specification (CLS)  Microsoft Visual Basic . 1541 USB2 Class written in one language can inherit from a class written in another Common type system Prohibit use of pointers Support interlanguage debugging Slide 58 . All Rights Reserved.NET C++ C# … … Common Language Specification Framework Class Library CLS represents the basic functionality each .NET language should implement if they are to interoperate with each other  Common Language Runtime Windows  Linux   © 2011 Microchip Technology Incorporated. Common Type System  Some basic . All Rights Reserved.NET types and their language keywords Base Class C# C++/CLI System::Byte Visual Basic 2008 Byte byte unsigned char System::SByte SByte sbyte char System::Int16 Short short short System::Int32 Integer int int System::Int64 Long long long long System::Single Single float float System::Double Double double double System::String String string String^ System::Decimal Decimal decimal Decimal © 2011 Microchip Technology Incorporated. 1541 USB2 Slide 59 . NET C# VC++ . 1541 USB2 Slide 60 . All Rights Reserved.NET Framework VB.NET vbc Compiler csc Compiler cpp Compiler Unmanaged Code MSIL Common Language Runtime JIT Compiler CLR Services Win32 API + Operating System © 2011 Microchip Technology Incorporated.Compilation in the . All Rights Reserved. 1541 USB2 Slide 61 . Unmanaged Code  Managed   Code whose every action is subject to approval by the CLR and types conform to the common type system Advantages    Type safe (type checked by the CLR) Garbage collection Unmanaged (“Native”)  Native machine code that runs without the CLR © 2011 Microchip Technology Incorporated.Managed vs. NET framework     New CLR data type keywords New override specifiers New language constructs New C++ operators © 2011 Microchip Technology Incorporated.C++/CLI: The . All Rights Reserved. 1541 USB2 Slide 62 .NET C++ Language  C++/CLI is an adaptation of the standard (ANSI) C++ language by Microsoft. targeted for the . networking © 2011 Microchip Technology Incorporated. C# and VB. file I/O.NET  Best of Both Worlds   Reuse existing C/C++ code.NET framework class libraries to simplify GUI development. 1541 USB2 Slide 63 .C++/CLI vs. . All Rights Reserved.dlls and libraries Easiest to interop with Win32 APIs   Which we need for USB I/O Use the extensive . 1541 USB2 Slide 64 .com/express/ © 2011 Microchip Technology Incorporated.microsoft.Building C++/CLI Programs for the CLR   Visual C++ is Microsoft’s C++/CLI compiler for their CLR This class uses Visual C++ 2008 “Express Edition”    Win32 Console/GUI apps .NET Console/GUI apps New: Visual C++ 2010 Express Edition  Free Download  http://www. All Rights Reserved. NET framework version 3.5 or newer installed to run your program Already installed on Windows Vista/7 systems The .Running Visual C++ 2008 . 1541 USB2 Slide 65 .Net Apps    Target PC must have .NET framework typically installed through Windows Update  Stand-alone redistributable installer also available © 2011 Microchip Technology Incorporated. All Rights Reserved. Compiles classic C/C++ & C++/CLI code.Visual C++ Compilation Modes Compiler Switch -none/clr /clr:pure /clr:safe Produces Native mode executable. 1541 USB2 Slide 66 . Can only use . All Rights Reserved. Compiles classic C/C++ code+libraries (no C++/CLI features) Mixed mode assembly (contains native and MSIL code).NET types. Compiles classic C/C++ & C++/CLI code MSIL-only assembly (no native code). Can use classic types compiled to MSIL MSIL-only verifiable assembly. Compiles classic C/C++ & C++/CLI code. © 2011 Microchip Technology Incorporated. Visual C++ Compilation Modes   Recommended: /clr:pure (default) Features  Produces pure IL code     Minimize need to jump outside CLR during program execution – faster. All Rights Reserved. Define & use native (LPCSTR) and managed (String^) types #include native headers See Appendix F for summary and comparison of compilation mode features © 2011 Microchip Technology Incorporated. 1541 USB2 Slide 67 . dll. user32. winusb. All Rights Reserved.Calling Win32 Functions from .dll.NET languages Consists of a method (DllImport) that     Finds the .. 1541 USB2 Slide 68 . Handled by a mechanism called P/Invoke (Platform Invoke) – available to all .dll .dll and loads into memory Marshals its arguments (converts from managed to native) so the DLL can understand the call Makes the call to the DLL function Marshals the return value (converts from native to managed format) so that the managed code understands the result © 2011 Microchip Technology Incorporated.NET    USB I/O requires calling native (Win32) functions in setupapi.. P/Invoke Example Create a managed entry point for calling Win32 API RegisterDeviceNotification(..) Step 1. Set compilation mode to \clr, \clr:pure  Allows you to define & use native types © 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 69 P/Invoke Example Step 2.  From Visual Studio Help, search for & identify the function signature, dll, and header file HDEVNOTIFY WINAPI RegisterDeviceNotification( HANDLE hRecipient, LPVOID NotificationFilter, DWORD Flags); Header Winuser.h (include Windows.h) Library User32.lib DLL User32.dll Unicode and ANSI names RegisterDeviceNotificationW (Unicode) and RegisterDeviceNotificationA (ANSI) © 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 70 P/Invoke Example Step 3.  #include the windows header file(s) & import the namespace containing the DllImport method #include <Windows.h> using namespace System::Runtime::InteropServices; © 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 71 and use attributes to associate it to an existing native function [DllImport(“User32. // Input: The window that will receive the // notification.P/Invoke Example Step 4.  Create a managed function declaration. CharSet = CharSet::Unicode.dll" . All Rights Reserved. // Input: Pointer to a // DEV_BROADCAST_DEVICEINTERFACE structure DWORD Flags // Input: Indicate whether the handle is for a // window or service status ). LPVOID NotificationFilter. © 2011 Microchip Technology Incorporated. 1541 USB2 Slide 72 . EntryPoint="RegisterDeviceNotificationW")] extern "C" HDEVNOTIFY WINAPI RegisterDeviceNotificationUM( HANDLE hRecipient. Summary       .NET solves problems of past Windows development One development paradigm for all major languages .NET uses managed code with services provided by the CLR The .NET Framework is a very large class library available consistently across many languages Visual C++ enables interoperability between classical Windows (C/C++) & .NET (C++/CLI) application development Choose your compiler settings carefully! © 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 73 HID Class Transfers Outline - HID Class Thermometer -     The HID Device Class The HID Report Descriptor Using the HID Function Driver APIs MCHPHID DLL Implementation  Lab  1 – HID Class Thermometer HID Summary – Benefits/Drawbacks © 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 75 All Rights Reserved. 1541 USB2 Slide 76 .The HID Device Class   Human Interface Device Designed for devices that operate in “human time”     Low rate data Limited latency “Device Class Definition for Human Interface Devices” “HID Usage Tables” © 2011 Microchip Technology Incorporated. 1541 USB2 Slide 77 . All Rights Reserved.HID limitations     Interrupt transfers only Up to 64 bytes per transaction (FS) No more than one transaction per frame Up to 1000 frames per second  Maximum data rate: 64.000 Bytes/Sec © 2011 Microchip Technology Incorporated. The HID Report Descriptor   HID data transferred by “reports” Report Descriptor    Detailed description of the data coming from the device Tells the host how to parse the data Host sends a Get Report Descriptor class specific request during enumeration © 2011 Microchip Technology Incorporated. 1541 USB2 Slide 78 . All Rights Reserved. 0x00. 1541 USB2 data Slide 79 . 0x02. Ads) 0xC0} // End Collection }. // Usage Minimum (Vendor Usage = 0) 0x29. 0x00. Var.Generic HID Data Descriptor //Class specific descriptor . 0xFF. 0x01. 0x40. // Collection (Application) 0x19. 0x00. 0xFF. 0x02. // Output (Data. Abs) 0x19. // Input (Data.}hid_rpt01={ { 0x06. 0x01. 0x40. // Report Size 8 bits per report. // Usage Maximum (64) 0x15. // Usage Minimum (0) 0x29. // Usage Page = 0xFFFF (Vendor Defined) 0x09. All Rights Reserved. // Usage (Vendor Usage 1) 0xA1. // Usage Maximum (Vendor Usage = 64) 0x91. // Logical Minimum (0) 0x26. 0x95. // Report Count 64 bytes per report.HID ROM struct{BYTE report[HID_RPT01_SIZE]. 0x01. © 2011 Microchip Technology Incorporated. // Logical Maximum (255) 0x75. 0x01. 0x81. 0x08. Var. 0x40. 0x00 1  Leave at 1 3 3 1 29 1541 USB2 Slide 80 . before using HID PC DLL functions /* HID */ #define HID_INTF_ID #define HID_EP #define HID_INT_OUT_EP_SIZE #define HID_INT_IN_EP_SIZE #define HID_NUM_OF_DSC #define HID_RPT01_SIZE © 2011 Microchip Technology Incorporated.h  Need to update this field after creating your HID descriptor table. All Rights Reserved.usb_config. Using the HID Function Driver APIs .     Configures an endpoint to receive data Returns a handle to the endpoint Buffer must be within USB Dual Port RAM HIDRxHandleBusy(USBOutHandle)   Returns 0 when buffer contains data 1 – no data Rx’d yet © 2011 Microchip Technology Incorporated.Inbound data -  HIDRxPacket(HID_EP. 1541 USB2 Slide 81 .64).(BYTE*) &ReceivedDataBuffer. All Rights Reserved. All Rights Reserved.. 1541 USB2 Slide 82 .HID Receive Usage void ProcessIO(void) { .64).. } } © 2011 Microchip Technology Incorporated. if(!HIDRxHandleBusy(USBOutHandle)) { /* Process received buffer */ //Re-arm the OUT endpoint for the next packet USBOutHandle = HIDRxPacket(HID_EP.(BYTE*) &ReceivedDataBuffer. 1541 USB2 Slide 83 .Using the HID Function Driver APIs .  Puts data on the endpoint for transport to host © 2011 Microchip Technology Incorporated.64). (BYTE*)&ToSendDataBuffer. All Rights Reserved.Outbound data -  HIDTxHandleBusy(USBInHandle   Is endpoint available? HIDTxPacket(HID_EP. HID Transmit Usage case 0x81: //Get push button state ToSendDataBuffer[0] = 0x81. 1541 USB2 Slide 84 . else ToSendDataBuffer[1] = 0x00.(BYTE*)&ToSendDataBuffer.64). break. All Rights Reserved. if(!HIDTxHandleBusy(USBInHandle)) USBInHandle = HIDTxPacket(HID_EP. © 2011 Microchip Technology Incorporated. if(sw2 == 1) ToSendDataBuffer[1] = 0x01. HIDWriteReport(buffer. HIDReadReport(buffer). PID.NET Assembly “HID class. (optional) © 2011 Microchip Technology Incorporated. len). 1541 USB2 Slide 85 . len).HID Class DLL     . HIDIsConnected().dll” Encapsulates the Win32 HID Data transfer APIs Namespace HIDClass::MCHPHIDClass Four Basic Functions:     void bool bool bool HIDClassInit(VID. All Rights Reserved. 1541 USB2 Slide 86 . PID. len.Initializing the Methods void HIDClassInit (VID. All Rights Reserved.     VID – Vendor ID assigned by USBIF PID – Product ID assigned by VID holder Len – Buffer length (normally 64) Timeout – Default 1000 mS (optional) © 2011 Microchip Technology Incorporated. timeout). 1541 USB2 Slide 87 . Does NOT communicate with device © 2011 Microchip Technology Incorporated.Polled Connection Detection bool HIDIsConnected(). All Rights Reserved.    Checks to see if the VID & PID set by HIDClassInit has been enumerated Returns true or false OS inquiry only. All Rights Reserved. Remainder of buffer padded to actual HID buffer length Returns True or False indicating transfer success/failure The device firmware must implement a “Generic” HID report descriptor as shown earlier! © 2011 Microchip Technology Incorporated.Writing A Report bool HIDWriteReport (buffer. len). 1541 USB2 Slide 88 .    Buffer to transmit len – Length of valid data in buffer.   Buffer – Returned data Non-blocking function  Returns true if data received within 1 second The device firmware must implement a “Generic” HID report descriptor as shown earlier! © 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 89 .Reading a Report bool HIDReadReport (buffer). All Rights Reserved.chm © 2011 Microchip Technology Incorporated.Documentation  C:\Microchip Solutions\Microchip\Help\ HID Class DLL. 1541 USB2 Slide 90 . Lab 1 HID Class Thermometer . 1541 USB2 Slide 92 .Lab 1 . All Rights Reserved.HID Class Thermometer  Objective       To familiarize you with HID class transfers Start with Generic HID example Modify to read BMA150 temperature sensor Modify PC Application to read data Display on application Follow instructions in lab manual © 2011 Microchip Technology Incorporated. Benefits/Drawbacks  Easy installation      no . 1541 USB2 Slide 93 .HID Summary . All Rights Reserved.dll” © 2011 Microchip Technology Incorporated.dll provides methods to simplify connection to HID-class devices Must use “generic HID” report descriptor to use the methods in “HID class.inf file driver built into OS Throughput limited to 64 KB/sec HID class. Building a Custom Class Thermometer using WinUSB . Outline . All Rights Reserved.Custom Class Thermometer Using WinUSB -    Using the Custom Class Function Driver APIs WinUSB Overview & APIs Obtaining & Using WinUSB   Lab 2 – Custom Class Thermometer using WinUSB WinUSB Conclusion © 2011 Microchip Technology Incorporated. 1541 USB2 Slide 95 . Vendor Class Firmware Structure Reset main() InitializeSystem() You Edit UserInit() main() USB Interrupt Context ProcessIO() USBDeviceTasks() You edit in main.c Synchronous model    © 2011 Microchip Technology Incorporated. Accepts commands from host Returns results Waits for next command 1541 USB2 Slide 96 . All Rights Reserved.c/user. All Rights Reserved.len).    USBGenRead(ep.len)    Copies data from user’s buffer to the IN Ep buffer Returns a USBGenericInHandle Copies data from the OUT Ep buffer to the user’s buffer Returns a USBGenericOutHandle USBHandleBusy(USBGenericInHandle)  Checks to see if the In or Out handle is busy © 2011 Microchip Technology Incorporated. 1541 USB2 Slide 97 .Custom Class Function Driver APIs USBGenWrite(ep.pSrc.pSrc. All Rights Reserved.len)    “Arms” an endpoint to receive data from the host Returns a USBGenericOutHandle to the endpoint USBHandleBusy(USBGenericOutHandle)   Returns TRUE if the handle is busy (i. still waiting for the host) Returns FALSE if the transfer is complete © 2011 Microchip Technology Incorporated.Inbound data  USBGenRead(ep. 1541 USB2 Slide 98 .pSrc.e. All Rights Reserved.(BYTE*)&OUTPacket.USBGEN_E P_SIZE)... break.Vendor Class Receive Usage void ProcessIO(void) { . if(!USBHandleBusy(USBGenericOutHandle)) { switch(OUTPacket[0]) { case 0x81: //Get push button state .. 1541 USB2 Slide 99 .. } //Re-arm the OUT endpoint for the next packet USBGenericOutHandle = USBGenRead(USBGEN_EP_NUM. } } © 2011 Microchip Technology Incorporated. 1541 USB2 Slide 100 .Outbound Data  USBGenWrite(ep. still sending to the host) Returns FALSE if the transfer is complete (i.len)    Puts data on the endpoint for transport to host Returns a USBGenericInHandle to the endpoint USBHandleBusy(USBGenericInHandle)   Returns TRUE if the handle is busy (i. All Rights Reserved.e.e.pSrc. the IN endpoint buffer is available) © 2011 Microchip Technology Incorporated. © 2011 Microchip Technology Incorporated.Vendor Class Transmit Usage case 0x81: //Get push button state INPacket[0] = 0x81.USBGEN_ EP_SIZE). if(sw2 == 1) INPacket[1] = 0x01. else INPacket[1] = 0x00. 1541 USB2 Slide 101 . break.(BYTE*)&INPacket. All Rights Reserved. if(!USBHandleBusy(USBGenericInHandle)) USBGenericInHandle = USBGenWrite(USBGEN_EP_NUM. h 0x04D8. // DEVICE descriptor type 0x0200. // Max packet size for EP0.Descriptor Table Settings File usb_descriptors. © 2011 Microchip Technology Incorporated.c /* Device Descriptor */ ROM USB_DEVICE_DESCRIPTOR device_dsc= { 0x12. All Rights Reserved. // Class Code 0x00. // Vendor ID 0x0053. // USB Spec Release Number in BCD format 0x00. // Device release number in BCD format 0x01. // Protocol code USB_EP0_BUFF_SIZE. see usb_config. // Size of this descriptor in bytes USB_DESCRIPTOR_DEVICE. // Subclass code 0x00. 1541 USB2 Slide 102 . // Product ID: Microchip WinUSB Demo 0x0100. // Device serial number string index 0x01 // Number of possible configurations }. // Manufacturer string index 0x02. // Product string index 0x03. USBGEN_EP_SIZE. USB_DESCRIPTOR_ENDPOINT. _BULK. 1541 USB2 Slide 103 . USB_DESCRIPTOR_ENDPOINT. _BULK. /*sizeof(USB_EP_DSC)*/ //Endpoint Descriptor //EndpointAddress //Attributes //size //Interval 0x07.c /* Endpoint Descriptor */ 0x07.h #define USBGEN_EP_SIZE 64 © 2011 Microchip Technology Incorporated. 1. _EP01_OUT. USBGEN_EP_SIZE. 1 /*sizeof(USB_EP_DSC)*/ //Endpoint Descriptor //EndpointAddress //Attributes //size //Interval _BULK. All Rights Reserved.Endpoint Descriptors File usb_descriptors.0x00.0x00. _EP01_IN. _CTRL or _INT (Interrupt) USBGEN_EP_SIZE defined in usb_config. WinUSB Overview & APIs . All Rights Reserved. 1541 USB2 Slide 105 .sys) User-mode dynamic link library (winusb.dll) © 2011 Microchip Technology Incorporated.WinUSB   Before Windows® Vista®. all USB device drivers had to operate in kernel mode WinUSB architecture :   Kernel-mode driver (winusb. WinUSB Architecture     No need to write your own driver FULL speed Works with XP and Vista/7 One . Kernel mode Microsoft Existing Component 1541 USB2 Microsoft New Component Device Slide 106 .SYS Vendor Component USB Stack USB Device (PIC18F14K50) © 2011 Microchip Technology Incorporated. All Rights Reserved.inf file Application WinUSB DLL User mode WinUSB. and interrupt transfers Selective suspend Remote wake No isochronous transfers! © 2011 Microchip Technology Incorporated. All Rights Reserved. control. 1541 USB2 Slide 107 .WinUSB features  WinUSB supports:      Device I/O control requests Bulk. aspx#winusb for the complete list of WinUsb routines.com/en-us/library/ff540046(v=VS. All Rights Reserved.dll exposes user mode client routines*:     WinUsb_Initialize WinUsb_WritePipe WinUsb_ReadPipe WinUSB_Free *See http://msdn.Key WinUSB APIs  winusb. © 2011 Microchip Technology Incorporated.85). 1541 USB2 Slide 108 .microsoft. __out PWINUSB_INTERFACE_HANDLE InterfaceHandle ). DeviceHandle [in] The handle to the device that CreateFile returned.WinUsb_Initialize  Creates a WinUSB handle for the device specified by a file handle BOOL __stdcall WinUsb_Initialize( __in HANDLE DeviceHandle. © 2011 Microchip Technology Incorporated. InterfaceHandle [out] The WinUSB handle for the device. All Rights Reserved. 1541 USB2 Slide 109 . All other WinUSB routines require this handle as input. WinUsb_WritePipe immediately returns. 1541 USB2 Slide 110 . © 2011 Microchip Technology Incorporated. __out_opt PULONG LengthTransferred. InterfaceHandle [in] WinUSB handle. BufferLength [in] The number of bytes to write. Buffer [in] A caller-allocated buffer that contains the data to write. which is used for asynchronous operations. PipeID [in] An 8-bit value that consists of a 7-bit address and a direction bit. optional] A pointer to a ULONG variable that receives the actual number of bytes that were written to the pipe. __in ULONG BufferLength. optional] An optional pointer to an OVERLAPPED structure. which is returned by WinUsb_Initialize. LengthTransferred [out. All Rights Reserved. This number must be less than or equal to the size.WinUsb_WritePipe  Writes data to a pipe BOOL __stdcall WinUsb_WritePipe( __in WINUSB_INTERFACE_HANDLE InterfaceHandle. __in UCHAR PipeID. __in PUCHAR Buffer. for the device. If this parameter is specified. Overlapped [in. and the event is signaled when the operation is complete. of Buffer. __in_opt LPOVERLAPPED Overlapped ). in bytes. which is used for asynchronous operations. Overlapped [in. All Rights Reserved. BufferLength [in] The maximum number of bytes to read. If this parameter is specified. 1541 USB2 Slide 111 . __in ULONG BufferLength. __in_opt LPOVERLAPPED Overlapped ). __out PUCHAR Buffer. This number must be less than or equal to the size. An event is signaled when the operation is complete. for the device. in bytes. of Buffer. © 2011 Microchip Technology Incorporated. optional] An optional pointer to an OVERLAPPED structure. optional] A pointer to a ULONG variable that receives the actual number of bytes that were copied into Buffer. __out_opt PULONG LengthTransferred. Buffer [in] A caller-allocated buffer that receives the data that is read. PipeID [in] An 8-bit value that consists of a 7-bit address and a direction bit. InterfaceHandle [in] WinUSB handle. __in UCHAR PipeID. WinUsb_ReadPipe returns immediately rather than waiting synchronously for the operation to complete before returning.WinUsb_ReadPipe  Reads data from the specified pipe BOOL __stdcall WinUsb_ReadPipe( __in WINUSB_INTERFACE_HANDLE InterfaceHandle. LengthTransferred [out. which is returned by WinUsb_Initialize. this routine returns FALSE. Otherwise. InterfaceHandle [in] WinUSB handle. which is returned by WinUsb_Initialize All WinUsb BOOL functions return TRUE if the operation succeeds. All Rights Reserved. © 2011 Microchip Technology Incorporated. and the caller can retrieve the logged error by calling GetLastError() .WinUsb_Free  Releases all of the resources that WinUsb_Initialize allocated BOOL __stdcall WinUsb_Free( __in WINUSB_INTERFACE_HANDLE InterfaceHandle ). 1541 USB2 Slide 112 . for the device. Obtaining & Using WinUSB . 1541 USB2 Slide 114 .How to Obtain WinUSB   WinUSB is part of the Windows Driver Kit (WDK) 2 Ways to get it  Microsoft Connect Web Site    MSDN Subscriber Download   http://connect.microsoft.com See Appendix D for detailed instructions http://msdn. All Rights Reserved.microsoft.com/enus/subscriptions/default.aspx Default folder:  C:\WinDDK\buildnumber © 2011 Microchip Technology Incorporated. NET Application using WinUSB APIs  1. 1541 USB2 Slide 115 . Set the compilation mode enabling managed code with native types:  Click ProjectPropertiesConfigurat ion PropertiesGeneralCommon Language Runtime Support/clr:pure © 2011 Microchip Technology Incorporated.Building a . All Rights Reserved. 0\inc\ddk C:\WinDDK\7600. 1541 USB2 Slide 116 ..NET Application using WinUSB APIs  2. Add WDK include paths to MSVC++   Click ToolsOptions+Projects and SolutionsVC++ DirectoriesShow Directories for: "Include files" Then click the Folder icon (new line) and then the ".16385.0\inc\api © 2011 Microchip Technology Incorporated." button and add these directories to the bottom of the list:   C:\WinDDK\7600.16385. All Rights Reserved..Building a . 1 Adding per project WDK include paths to MSVC++  In “Solution Explorer” right click on “Current Project” C++ Additional Include Directories  Then add the following lines:   C:\WinDDK\7600. All Rights Reserved.16385. 1541 USB2 Slide 117 .0\inc\ddk C:\WinDDK\7600.NET Application using WinUSB APIs  2.16385.Building a .0\inc\api © 2011 Microchip Technology Incorporated. h>   Provides definitions for common Win32 types Provides definitions for SetupDixxx() functions we use to find our device #include <winusb.h>   #include <setupapi.NET Application using WinUSB APIs  3.h>  Provides definitions for WinUSB APIs © 2011 Microchip Technology Incorporated. 1541 USB2 Slide 118 . Include the header files  #include <windows.Building a . All Rights Reserved. //Input: Supply the class GUID here. not important HWND hwndParent. //Input: Use NULL here. //Input: Use NULL here. All Rights Reserved.Building a . [DllImport("setupapi. EntryPoint="SetupDiGetClassDevs")] extern "C" HDEVINFO SetupDiGetClassDevsUM( LPGUID ClassGuid.NET Application using WinUSB APIs  4. © 2011 Microchip Technology Incorporated. CharSet = CharSet::Seeifdef. Use P/Invoke to create a prototype of each WinUSB API function you will use using namespace System::Runtime::InteropServices. not important DWORD Flags). PCTSTR Enumerator. 1541 USB2 Slide 119 .dll" . 2. 3. Use the Device Interface GUID + VID_PID to get the device path Use the device path to get a handle to the device Use the device handle to initialize WinUSB and receive an interface handle Use the interface handle to communicate with the endpoints © 2011 Microchip Technology Incorporated.WinUSB – Using the APIs  4-Step Procedure: 1. 1541 USB2 Slide 120 . 4. All Rights Reserved. inf devicePath.Sample 1 2 GetDevicePath ((GUID) & GUID_DEVICE. // output buffer length &transferredBytes. 0x01. All Rights Reserved. // pass the deviceHandle and you get the Interface Handle 4 WinUSB_WritePipe( interfaceHandle. // size of device path deviceHandle = CreateFile (devicePath. // output buffer sizeof ( output ). // pointer to device path sizeof(DeviceName)). // optional OVERLAPPED structure © 2011 Microchip Technology Incorporated. // endpoint address for bulk out output.// obtain the handle 3 WinUsb_Initialize(deviceHandle.WinUSB . // GUID declared in . ………). &interfaceHandle). 1541 USB2 Slide 121 . // bytes transferred NULL). dll & winusb. 1541 USB2 Slide 122 .inf © 2011 Microchip Technology Incorporated.sys  Create a package**:    WinUSBCoInstaller2.dll* and WUDFUpdate_01009. The name is given for version 1.How to Install winusb.inf file that installs winusb.dll & .sys .9 ** XP Only. Windows Vista/7 already comes with the .sys as the device’s function driver *The actual name might vary.dll (Installs WinUSB files on the target system) WdfCoInstaller01009.dll* (Kernel-mode coinstallers) . All Rights Reserved.only requires the . inf file is provided   C:\Masters\1541\Lab2\Host\Driver and inf\MCHPWinUSBDevice_v2. 1541 USB2 Slide 123 .Sample .inf You can modify it    Put your VID and PID Device description Disk name © 2011 Microchip Technology Incorporated. All Rights Reserved.inf  A sample WinUSB . NTx86] %DESCRIPTION% =USB_Install.NTamd64 [MyDevice_WinUSB.inf  [Manufacturer] %MFGNAME% = MyDevice_WinUSB. 1541 USB2 Slide 124 . All Rights Reserved..NTamd64] %DESCRIPTION% =USB_Install.NTx86.inf File Modifications  Modifiable sections in MCHPWinUSBDevice. USB\VID_04D8&PID_0053  [Dev_AddReg] HKR.. USB\VID_04D8&PID_0053 [MyDevice_WinUSB.0x10000.DeviceInterfaceGUIDs."{58D07 210-27C1-11DD-BD0B-0800200C9a66}"  Device Interface GUID must be identical with the one declared in the PC Host Application © 2011 Microchip Technology Incorporated. inf File Modifications  Modifiable sections in MCHPWinUSBDevice.DeviceDesc="WinUSB Demo" WinUSB_SvcDesc="WinUSB Device" DISK_NAME="WinUSB Device Install Disk" DEVICEMANAGERCATEGORY="Custom USB Devices" © 2011 Microchip Technology Incorporated.inf  [Strings]       MFGNAME="Microchip Technology. All Rights Reserved.." DESCRIPTION="Microchip WinUSB Device" USB\MyDevice. Inc. 1541 USB2 Slide 125 . Lab 2 Custom Class Thermometer Using WinUSB . add the functions to communicate with endpoints and process/display the result Use the Beagle analyzer to look at the packets (refer to Appendix C) © 2011 Microchip Technology Incorporated. 1541 USB2 Slide 127 . All Rights Reserved.Lab 2 Custom Class Thermometer Using WinUSB    Modify the default WinUSB demo firmware to read BMA150 temperature data In the PC Host App. microsoft.com/enus/library/ff540046(v=VS. Create an *.inf and you have your own driver.aspx#winusb © 2011 Microchip Technology Incorporated. Works with XP. Vista & 7 Reference:  C:\Masters\1541\Users Guides and Data Sheets\WinUsb_HowTo. 1541 USB2 Slide 128 .Conclusion     WinUSB allows full-speed USB communication No custom driver needed.85). All Rights Reserved.pdf  WinUSB User‐Mode Client Support Routines  http://msdn.WinUSB . Matching a Driver to a Device Overview  When the Windows USB bus driver enumerates a device, it reports 2 device identifiers to the PnP manager:  deviceID (or hardwareID)    instanceID    Consists of the Serial Number –or- USB port# Format: “\1234” or “\6&57cbc&0&2” The PnP manager combines these to form the deviceinstanceID   Consists of enumerating bus ID, VID, PID Format: “USB\Vid_04d8&Pid_0053” Format: “USB\Vid_04d8&Pid_0053\1234” This ID is unique to the physical device, and is used by the PnP manager to search the Windows Registry for the device’s enumeration key, which contains information on which driver to load © 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 130 Viewing deviceID and deviceinstanceID in the Device Manager (Lab 2 - Device) © 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 131 All Rights Reserved. regardless of which port it is plugged into The serial string produces a unique instanceID which allows the system and your application to distinguish different instances of the same hardware © 2011 Microchip Technology Incorporated.USB Serial String Descriptor    A device without a USB serial number gets a new deviceinstanceID every time the device attaches to a different port Devices with a USB serial number have 1 unique deviceinstanceID per physical device. 1541 USB2 Slide 132 . All Rights Reserved. 1541 USB2 Slide 133 .A Device’s deviceinstanceID Before/After adding a Serial Number © 2011 Microchip Technology Incorporated. Device Information in the Registry  Regedit applet available to view the registry   StartRunRegedit Enumeration key identifies a specific device instance:  \HKLM\SYSTEM\CurrentControlSet\Enum\USB\<VID_PID> \<serial number/USB Port> © 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 134 . 1541 USB2 Slide 135 .Driver Key    The Driver Key names an inf to open If the inf’s deviceID string matches the identifier produced by the USB bus driver. the driver is loaded Path: \HKLM\SYSTEM\CurrentControlSet\Control\Class\<ClassGUID>\ <driver#> © 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 136 . All Rights Reserved.8*1038 possible combinations ClassGUID – used to identify drivers Device interface GUID Used to obtain information about attached devices  HID device interface class GUID:   4D1E55B2-F16F-11CF-88CB-001111000030  Custom class: Create your own © 2011 Microchip Technology Incorporated.What is a GUID?  A 128-bit random number      Globally Unique Identifier Uniquely identifies all Windows classes or entities 2128 or 3. net/ © 2011 Microchip Technology Incorporated.How to Create a GUID    Any licensed Visual Studio distribution Free tool found with WDK Free tools available on the internet :   http://www.newguid. All Rights Reserved.com/ http://www. 1541 USB2 Slide 137 .guidgen. 1541 USB2 Slide 138 . All Rights Reserved. 0x00. 0x30}. © 2011 Microchip Technology Incorporated. 0x11. 0x11. 0xcb. 0x88. 0x00.Defining a GUID #include <Windows. 0xf16f. 0x11cf.h> // declare/initialize a HID device // interface class GUID GUID InterfaceClassGuid = {0x4d1e55b2. 0x00. Detecting Devices . 1541 USB2 Slide 140 .Agenda (Detecting Devices)  Finding Your Device    Lab 3a – Finding Your Device Obtaining a Handle Handling Attach/Detach Events  Lab 3b – WinUSB Thermometer using WM_DEVICECHANGE © 2011 Microchip Technology Incorporated. All Rights Reserved. Finding Your Device . All Rights Reserved. 1541 USB2 Slide 141 .What we need to find -   Searching for the device’s path Required to open a “handle” to the device © 2011 Microchip Technology Incorporated. Finding Your Device . looking for a matching deviceinstanceID  On a match.Procedure -    Obtain your device interface GUID and deviceinstanceID for your device Get a pointer to a “device information set”. 1541 USB2 Slide 142 . for all devices plugged in having the same device interface GUID Enumerate through each “device information element” in the set. extract the device’s path (to be used in CreateFile()) © 2011 Microchip Technology Incorporated. All Rights Reserved. All Rights Reserved. 1541 USB2 Slide 143 .Device Information Sets © 2011 Microchip Technology Incorporated. 0x08. 0x0c. [Dev_AddReg] HKR. 0xbd. © 2011 Microchip Technology Incorporated. 0x9a. All Rights Reserved.. 1541 USB2 Slide 144 . 0x0b.Obtain Your Device Interface GUID  Get it from the . 0x27c1. 0x20. 0x66}..   HID devices can use HidD_GetHidGuid() Declare/Define it in your PC code GUID MyInterfaceClassGuid = {0x58d07210.DeviceInterfaceGUIDs.0x10000. 0x00."{58D0 7210-27C1-11DD-BD0B-0800200C9a66 .inf file you used to install your device .... 0x11dd. © 2011 Microchip Technology Incorporated.Obtain Your deviceinstanceID  Add a serial number string descriptor to your device (see  Appendix B in the Lab manual) Declare/Define it in your PC code PCWSTR MyDeviceInstanceId L"USB\\VID_04D8&PID_0053\\1234". -orString ^MyDeviceInstanceID = L"USB\\VID_04D8&PID_0053\\1234". 1541 USB2 Slide 145 . All Rights Reserved. SetupDiGetClassDevs  Returns a handle to a device information set that contains requested device information elements for a local computer HDEVINFO SetupDiGetClassDevs( __in_opt const GUID *ClassGuid. All Rights Reserved.  Usage HDEVINFO hDevInfo = SetupDiGetClassDevs( &InterfaceClassGUID. __in_opt HWND hwndParent. © 2011 Microchip Technology Incorporated. 0. 0. DIGCF_PRESENT | DIGCF_DEVICEINTERFACE ). __in_opt PCTSTR Enumerator. __in DWORD Flags ). 1541 USB2 Slide 146 . MemberIndex..*/ } © 2011 Microchip Technology Incorporated. All Rights Reserved.  Usage while(SetupDiEnumDeviceInfo(hdevinfo... &DeviceInfoData)) { /* call SetupDiGetDeviceInstanceID() to query the device information element for it’s deviceinstanceID and look for a match. __out PSP_DEVINFO_DATA DeviceInfoData ). __in DWORD MemberIndex.SetupDiEnumDeviceInfo  Returns a pointer to a SP_DEVINFO_DATA structure that specifies a device information element in a device information set BOOL SetupDiEnumDeviceInfo( __in HDEVINFO DeviceInfoSet. 1541 USB2 Slide 147 . // Look for a match between found and desired DeviceInstanceIDs if(!wcscmp(DeviceInstanceId. DeviceInstanceId. RequiredSize. } © 2011 Microchip Technology Incorporated. FoundDevice = true. All Rights Reserved. MyDeviceInstanceId)) { wprintf(L"Found Device!\n\n"). 1541 USB2 Slide 148 . NULL). __in DWORD DeviceInstanceIdSize.SetupDiGetDeviceInstanceID  Retrieves the deviceinstanceID that is associated with a device information element BOOL SetupDiGetDeviceInstanceId( __in HDEVINFO DeviceInfoSet. __in PSP_DEVINFO_DATA DeviceInfoData.  Usage SetupDiGetDeviceInstanceId(hDevInfo. __out_opt PTSTR DeviceInstanceId. break. __out_opt PDWORD RequiredSize ). &DeviceInfoData. SetupDiEnumDeviceInterfaces  Enumerates the device interfaces that are contained in a device information set  Can enumerate interfaces in a single device information element. __in const GUID *InterfaceClassGuid. __in DWORD MemberIndex. __out PSP_DEVICE_INTERFACE_DATA DeviceInterfaceData ). 1541 USB2 Slide 149 . © 2011 Microchip Technology Incorporated. All Rights Reserved. or the whole info set BOOL SetupDiEnumDeviceInterfaces( __in HDEVINFO DeviceInfoSet. __in_opt PSP_DEVINFO_DATA DeviceInfoData. SetupDiGetDeviceInterfaceDetail  Returns details about a device interface BOOL SetupDiGetDeviceInterfaceDetail( __in HDEVINFO DeviceInfoSet. __out_opt PSP_DEVINFO_DATA DeviceInfoData ). __out_opt PDWORD RequiredSize. Pointer to a structure containing the device path © 2011 Microchip Technology Incorporated. __out_opt PSP_DEVICE_INTERFACE_DETAIL_DATA DeviceInterfaceDetailData. __in DWORD DeviceInterfaceDetailDataSize. __in PSP_DEVICE_INTERFACE_DATA DeviceInterfaceData. All Rights Reserved. 1541 USB2 Slide 150 . All Rights Reserved.Summary: SetupDixxx Usage SetupDiGetClassDevs  Gets the device info set SetupDiEnumDeviceInfo  Gets a specific info element SetupDiGetDeviceInstanceID  Match? SetupDiEnumDeviceInterfaces SetupDiGetDeviceInterfaceDetail  Get the path! © 2011 Microchip Technology Incorporated. 1541 USB2 Slide 151 . __out LPWSTR MyDevicePath ).h BOOL FindMyDevice( __in PCWSTR MyDeviceInstanceId. __in const GUID MyInterfaceClassGuid. All Rights Reserved. FindMyDevice.cpp & . if present Uses SetupDixxx APIs 2 files.FindMyDevice     Written for this class Retrieves the device path for a specific device instance. © 2011 Microchip Technology Incorporated. 1541 USB2 Slide 152 . and if found. prints the device path Project uses function FindMyDevice() © 2011 Microchip Technology Incorporated.Lab 3a Find Your Device  Objective   Device   Learn about the SetupDixxx() APIs used to find information about plugged in USB devices Add serial number string descriptor to Lab2 (WinUSB Thermometer) project. 1541 USB2 Slide 153 . Record the device instance ID Host   Build/Run a Win32 console project that searches for the device instance. All Rights Reserved. MyInterfaceClassGuid.. 0x66}. // Specific Device Instance ID to to search for PCWSTR MyDeviceInstanceId = L"USB\\VID_04D8&PID_0053\\1234".h> #include “FindMyDevice. return 0. 0x0c. // Wide char array to hold the device path WCHAR MyDevicePath[256]..cpp) #include <wchar. } else { wprintf(L"No Device Found!\n\n"). strcmp() etc. 0xbd. 0x00. 0x27c1.Lab 3a Solution (main. return 0. 1541 USB2 Slide 154 . 0x11dd. (LPWSTR)&MyDevicePath)) { wprintf(L"Found Device!\n\n"). // Win32 types etc // Prototype for FindMyDevice(0 int main( int argc. 0x0b.. All Rights Reserved.inf file const GUID MyInterfaceClassGuid = {0x58d07210. char *argv[ ].. wprintf(L"Path:[%s]\n\n". char *envp[ ] ) { // Interface Class GUID from the MCHP WinUSB .h> #include <windows. } } © 2011 Microchip Technology Incorporated. if(FindMyDevice(MyDeviceInstanceID.h” // Wide char versions of printf(). 0x08.&MyDevicepath).0x20. 0x9a. 1541 USB2 Slide 155 . All Rights Reserved.Lab 3a  Result (device attached)  Result (device detached) © 2011 Microchip Technology Incorporated. Obtaining a Handle . CreateFile   Creates or opens a file or I/O device Returns a handle that can be used to access the device for various types of I/O depending on the device and the flags and attributes specified HANDLE WINAPI CreateFile( __in LPCTSTR lpFileName, __in DWORD dwDesiredAccess, __in DWORD dwShareMode, __in_opt LPSECURITY_ATTRIBUTES lpSecurityAttributes, __in DWORD dwCreationDisposition, __in DWORD dwFlagsAndAttributes, __in_opt HANDLE hTemplateFile ); © 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 157 CreateFile - Usage (WinUSB) if(FindMyDevice(...)) { //Make sure one device instance is attached /* We have the device path, open a device handle to the device */ /* WinUSB requires the device handle to be opened with the FILE_FLAG_OVERLAPPED attribute */ MyDeviceHandle = CreateFile((DetailedInterfaceDataStructure->DevicePath), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0); DWORD ErrorStatus = GetLastError(); if(ErrorStatus == ERROR_SUCCESS) { /* Now get the WinUSB interface handle by calling WinUsb_Initialize() and providing the device handle*/ BOOL BoolStatus = WinUsb_Initialize(MyDeviceHandle, &MyWinUSBInterfaceHandle); if(BoolStatus == TRUE) { /* WinUSB initialized. Initialize rest of application */ ... © 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 158 Handling Attach/Detach Events does what’s needed. 1541 USB2 Slide 160 . returns control to OS © 2011 Microchip Technology Incorporated.Windows Messages  Windows applications are event-driven by nature:      User clicks a mouse over an application’s window area (an event) OS decodes HW signals from mouse Figures out which window user has selected Sends a message to that window’s application program Program reads message data. All Rights Reserved. this message processing is normally hidden  You don’t see the method © 2011 Microchip Technology Incorporated. 1541 USB2 Slide 161 .WndProc(m) Method  Application’s “callback” function    Called by the Windows OS to process messages Receives a message structure m In a Win Forms application. All Rights Reserved. 1541 USB2 Slide 162 . All Rights Reserved.Handling Attach/Detach  Two ways to find out if device is attached:    Polling Event-driven Windows can notify your application when a device is attached or removed from the system.  “Device notification” messages sent to WndProc() © 2011 Microchip Technology Incorporated. 1541 USB2 Slide 163 . All Rights Reserved.   Using Device Notification Messages Register to receive notification messages for devices in a device interface class Windows detects attach/detach and passes appropriate WM_DEVICECHANGE notification message to the form’s WndProc() method (normally hidden) Application must override its default WndProc() method to intercept this message and process it © 2011 Microchip Technology Incorporated. 1541 USB2 Slide 164 . LPVOID NotificationFilter.) function to request to receive notification messages Synopsis: Register a type of device for which a window will receive notifications HDEVNOTIFY WINAPI RegisterDeviceNotification(HANDLE hRecipient.h) Library User32.dll Unicode and ANSI names RegisterDeviceNotificationW (Unicode) and RegisterDeviceNotificationA (ANSI) © 2011 Microchip Technology Incorporated.h (include Windows..Registering for Device Notifications   Applications use the RegisterDeviceNotification(. All Rights Reserved.lib DLL User32. DWORD Flags). Header Winuser. h> © 2011 Microchip Technology Incorporated. All Rights Reserved.RegisterDeviceNotification()  Parameters HANDLE hRecipient Handle to the window that will receive the message LPVOID NotificationFilter Pointer to a DEV_BROADCAST_DEVICEINTERFACE structure that holds information about the request DWORD Flags Indicates whether the handle is for a window or service status. 1541 USB2 Slide 165 . Can be 2 possible values: DEVICE_NOTIFY_WINDOW_HANDLE DEVICE_NOTIFY_SERVICE_HANDLE Must #include <Dbt. dll" . 1541 USB2 Slide 166 . // Input: Pointer to a DEV_BROADCAST_DEVICEINTERFACE structure DWORD Flags // Input: Indicate whether the handle is for a window or // service status ). // Input: The window that will receive the notification. © 2011 Microchip Technology Incorporated. All Rights Reserved. EntryPoint="RegisterDeviceNotificationW")] extern "C" HDEVNOTIFY WINAPI RegisterDeviceNotificationUM( HANDLE hRecipient. LPVOID NotificationFilter.P/Invoke Signature [DllImport(“User32. CharSet = CharSet::Unicode. GUID InterfaceClassGuid = {0x4d1e55b2.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE).. 0x88.h> .dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE. © 2011 Microchip Technology Incorporated. &MyDevBroadcastInterface.h> #include <Dbt. 0x00. 0x11. MyDevBroadcastInterface. MyDevBroadcastInterface. DEV_BROADCAST_DEVICEINTERFACE MyDevBroadcastInterface. 1541 USB2 Slide 167 . MyDevBroadcastInterface. //Reserved says not to use....dbcc_classguid = InterfaceClassGuid. 0xcb. 0x11.Calling the Function #include <Windows. MyDevBroadcastInterface. All Rights Reserved. 0x30}. 0x11cf..dbcc_reserved = 0. .. [DllImport. 0x00. RegisterDeviceNotificationUM((HANDLE)this->Handle. DEVICE_NOTIFY_WINDOW_HANDLE). 0xf16f... 0x00. msg for WM_DEVICECHANGE Test m. All Rights Reserved..wParam for DBT_DEVICEARRIVAL or DBT_DEVICEREMOVECOMPLETE  Check connection status for your specific device   BOOL FindMyDevice(..) Call System::Windows::Forms::WndProc(m) to process any other messages © 2011 Microchip Technology Incorporated.Processing the Message  Override default WndProc() method    Receives a Message Structure m Test m. 1541 USB2 Slide 168 . All Rights Reserved. 1541 USB2 Slide 169 .hex file as Lab3a Host  Create simple .Lab 3b WinUSB Thermometer Using WM_DEVICECHANGE  Device   Use same .NET application that    Registers for WM_DEVICECHANGE notifications Overrides the existing WndProc() method to intercept WM_DEVICECHANGE messages When a message is sent to the Window:     Verify connection status of your device Open a device handle to your device Initialize WinUSB Communicate with the endpoints © 2011 Microchip Technology Incorporated. Lab 3b  Form Design “Event Triggers” WM_DEVICECHANGE on/off Timer tick event © 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 170 . Conclusion -  USB Attach/Detach is asynchronous by nature   Windows applications are event-driven (A . 1541 USB2 Slide 171 .NET Windows application is still a message-processing loop)     Event-driven detection is better than polling System::Controls:Forms:Wndproc() Need to register to receive messages Override existing method Check if our device is plugged in or not © 2011 Microchip Technology Incorporated.Handling Attach/Detach Events . All Rights Reserved. ...) WndProc() © 2011 Microchip Technology Incorporated.Detecting Devices .) Handling Attach/Detach Events   RegisterDeviceNotification(.) CreateFile(. All Rights Reserved. 1541 USB2 Slide 172 .Summary -  Finding Your Device   Obtaining a Handle   SetupDixxx(. All Rights Reserved. 1541 USB2 Slide 173 .Summary/Resources © 2011 Microchip Technology Incorporated. USB Transfer Recap   HID class – It just works WinUSB – Flexibility. 1541 USB2 Slide 174 . Microsoft Support © 2011 Microchip Technology Incorporated. All Rights Reserved. Speed. 1541 USB2 Slide 175 . Custom USB device classes for generic data transfer How to use the Microchip USB Framework in your own project The basics of the Windows USB subsystem for driver loading.Summary  Today we covered:    The benefits/limitations of the HID. connection detection and device communications © 2011 Microchip Technology Incorporated. All Rights Reserved. microchip.Additional Resources  Books       Weblinks        www.microchip.lvr. All Rights Reserved.microsoft.com 3rd Party Training (.NET Languages)   www.com/usb www.mspx www.org (USB Spec.beyondlogic.NET 3. 5/E” – Mark Russinovich “Foundations of C++/CLI: The Visual C++ Lanaguage for .5 Platform” – Stephen Fraser “Expert C++/CLI: .com/whdc/connect/usb/winusb_howto.htm (Tutorial) Forums   “USB Complete.NET 3. 4/E” – Jan Axelson (C# & VB Example Code) “Microsoft Windows Internals.softwaretrainingacademy.5” – Gordon Hogenson “Pro Visual C++/CLI & the .NET for Visual C++ Programmers ” – Marcus Heege www.usb.org/usbnutshell/usb1.usb. 1541 USB2 Slide 176 .com (USB Examples) www.com App Notes © 2011 Microchip Technology Incorporated.org/phpbb/ forum. class definitions) www. dsPICDEM.S. Mindi. PICC. 1541 USB2 Slide 177 . PICC-18. In-Circuit Serial Programming. Omniscient Code Generation. mTouch.Trademarks • • • • • • The Microchip name and logo. Select Mode. PIC32 logo. TSHARC. MPLINK. and other countries. PICDEM. FilterLab. rfPIC and UNI/O are registered trademarks of Microchip Technology Incorporated in the U. All Rights Reserved. PICmicro. HI-TECH C.S.net. Microchip Technology Incorporated. ECONOMONITOR.A. CodeGuard. PICSTART.A. MXLAB. ECAN. PICkit. Linear Active Thermistor. SQTP is a service mark of Microchip Technology Incorporated in the U. chipKIT. the Microchip logo. MPLAB Certified logo. dsPICDEM. All other trademarks mentioned herein are property of their respective companies. rfLAB. MPLAB. KeeLoq. and other countries. MPLIB. SEEVAL and The Embedded Control Solutions Company are registered trademarks of Microchip Technology Incorporated in the U. KeeLoq logo.net. FanSense. Analog-for-the-Digital Age.S. UniWinDriver. MiWi. MXDEV. Total Endurance. PICDEM. PIC. ICSP. Hampshire.A. dsPIC. chipKIT logo. HI-TIDE. All Rights Reserved. WiperLock and ZENA are trademarks of Microchip Technology Incorporated in the U. dsSPEAK. PICtail. Application Maestro. MPASM.S.A. © 2011. dsPICworks. © 2011 Microchip Technology Incorporated. REAL ICE.
Copyright © 2024 DOKUMEN.SITE Inc.