usb
November 16, 2016 | Author: Fernandez Shian | Category: N/A
Short Description
usb...
Description
1541 USB2 USB: 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
Scalable USB PIC® MCU Portfolio
Performance
~40 USB PIC MCUs
The industry’s strongest scalable product, family and software migration path
PIC32 High Performance, Pin Compatible to PIC24F 80 MHz, 1.53 DMIPS/MHz Up to 80 MIPS 64- & 100-Pin Packages Up to 512 KB Flash Up to 32 KB RAM USB 2.0 Device, Embedded Host, OTG
PIC24F Mid-Range, Capacitive-Touch Capable Up to 16 MIPS 64-, 80- & 100-Pin Packages Up to 256 KB Flash Up to 16 KB RAM USB 2.0 Device, Embedded Host, OTG
PIC18F
32-bit
Small, Low Power, Low Cost Up to 12 MIPS 18- to 80-Pin Packages Up to 128 KB Flash Up to 4 KB RAM USB 2.0 Device Support
16-bit 8-bit
Migration © 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
5
Class Folders C:\Masters\1541 \Development Tools \Lab1..Lab3 \Device \Device Solution \Host \Host Solution \Microchip \Presentation and Handouts \Users Guides & Data Sheets
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
6
Application Overview (Thermometer)
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.
1541 USB2
Slide
8
Board Key Components
On Board Debugger (provides SYS CLK)
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
9
Board Key Components
PIC18F46J50
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
10
Board Key Components Capacitive Touch Buttons and Scroll Bar
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
11
Board Key Components
Organic LED display
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
12
Board Key Components
3 Axis Acceleration Sensor (BMA150)
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
13
Board Key Components
I/O Expansion
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
14
Board Key Components
S1 Menu Button
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
15
Board Key Components
MicroSD Memory Card
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
16
Board Key Components
Potentiometer
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
17
Board Key Components
mini-B USB Receptacle
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
18
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, 13-Channel Analog-to-Digital Converter Two Enhanced USART Peripheral Pin Select (PPS) Nanowatt XLP Technology
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
19
Full-Speed USB Review
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. All Rights Reserved.
Printer
1541 USB2
Speaker
Slide
21
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
Enumeration
Enumeration process
EP0 “Control Endpoint” Chapter 9 commands Descriptors Dynamic address .inf file
Host associates driver Vendor & Product ID
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
23
Transfer types
Control
Interrupt
Low rate/bounded latency
Bulk
Bus configuration
Guaranteed integrity
Isochronous
Guaranteed timeliness
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
24
Maximum Transfer Rates - Full Speed USB -
Transfer/ Endpoint Type
Polling Interval
% Reserved BW/Frame for all transfers of this type
Max. # Data Bytes/Frame/Endpoint (Max# transactions per frame @ Max Ep Size)*
Data Integrity
Interrupt
Fixed, Periodic
90
64 (1 x 64)
Yes
Isochronous
Fixed, Periodic
90
1023 (1 x 1023)
No
Bulk
Variable, 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.
1541 USB2
Slide
25
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…. © 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
26
Considerations When Using Standard Classes
The Logical USB Device is predefined
Max. 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 portsome 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. All Rights Reserved.
1541 USB2
Slide
27
USB Driver Choices Features
HID
mchpusb.sys
CDC
WinUSB
LibUSB
(v1.0.0.6) Driver support built into Windows
Yes
Need .inf
No
Need .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.0 MB/s
~1.0MB/s
~1.0MB/s
Transfer Types
Max Speed
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
28
Microchip USB Framework (MCHPFSUSB)
Downloading the Microchip Application Libraries
Download from www.microchip.com/mal Contains different stacks (USB, TCP/IP, Graphics, mTouch™ Sensing Solution, etc.) 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. All Rights Reserved.
1541 USB2
Slide
30
Default Install Directory
C:/Microchip Solutions YYYY-MM-DD/
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
31
Default Install Directory
C:/Microchip Solutions YYYY-MM-DD/USB
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
32
MCHPFSUSB Framework - 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.
1541 USB2
Slide
33
Generic USB Project
General structure ./USB/Your application
main.c usb_descriptors.c
Editable files
HardwareProfile.h usb_config.h ./Microchip /Include /USB /Common
/… © 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
34
MCHPFSUSB Framework - Editable Files
usb_descriptors.c
Define your device descriptors
VID & PID Class Specific (may not need to change) Strings
/* Device Descriptor */ ROM USB_DEVICE_DESCRIPTOR device_dsc= { 0x12, // Size of this descriptor (byte) USB_DESCRIPTOR_DEVICE, // DEVICE descriptor type 0x0200, // USB Spec Release Number My_Class_code, // Class code My_Subclass_code, // Subclass code My_Protocol_code, // Protocol code EP0_BUFF_SIZE, // Max packet size for EP0 0x0000, // Vendor ID 0x0000, // Product ID … © 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
35
MCHPFSUSB Framework - Editable Files
HardwareProfile.h
Defines your board & hardware initialization routines for your board
// #define USE_SELF_POWER_SENSE_IO #define tris_self_power TRISAbits.TRISA2 #if defined (USE_SELF_POWER_SENSE_IO) #define self_power PORTAbits.RA2 #else #define self_power 1 #endif //#define USE_USB_BUS_SENSE_IO #define tris_usb_bus_sense TRISAbits.TRISA1 #if defined (USE_USB_BUS_SENSE_IO) #define USB_BUS_SENSE PORTAbits.RA1 #else #define USB_BUS_SENSE 1 #endif © 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
// Input
// Input
Slide
36
MCHPFSUSB Framework - Editable Files
usb_config.h
Define framework options (use configuration tool)
USB Definitions Device Class Usage Endpoint Allocation
/** DEFINITIONS ********************************************/ #define USB_EP0_BUFF_SIZE 8 // Valid Options: 8, // 16, 32, or 64 bytes. //#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. All Rights Reserved. 1541 USB2 Slide 37
MCHPFSUSB Framework - Editable Files
main.c
Contains UserInit() Main Loop USBDeviceTasks()
Polled or Interrupt-driven
ProcessIO()
Callback function()
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
38
MCHPFSUSB Framework - 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. Use state machine.
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
39
MCHPFSUSB Framework - 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. 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.1 - 200us Task A Task A.2 - 400us 900us Task A.3 - 300us
Task B - 100us
© 2011 Microchip Technology Incorporated. All Rights Reserved.
Max Loop Time 500us VS. 1000us
1541 USB2
Slide
41
Code Example Main.c #include “./USB/usb.h” #include “./USB/usb_function_cdc.h” #include “HardwareProfile.h”
Needed (usb_config.h is called by usb.h)
void UserInit(void){ … Put your initzialization code here … }
void ProcessIO(void){ if((USBDeviceState < CONFIGURED_STATE)||(USBSuspendControl==1)) return; … Put your application code (state machine) here … CDCTxService(); } static void InitializeSystem(void){ #if define … #endif UserInit(); USBDeviceInit(); } int main(void){ InitializeSystem(); while(1){ USBDeviceTasks(); ProcessIO(); } }
Conditional compiling (No need to change)
No need to change
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
USBDeviceTasks() is executed into an ISR (High Priority PIC18, _USB1Interrupt() PIC24 & PIC32)
Slide
42
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.c
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
43
Debugging USB Applications
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.
1541 USB2
Slide
45
Hardware Protocol Analyzer
Image © USB Complete: The Developer’s Guide by Jan Axelson
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
46
Hardware Protocol Analyzer
Beagle 480 (www.totalphase.com)
Non-obtrusive real-time monitoring Monitors USB 2.0 LS, FS, HS Protocol-level decoding Real-time filtering Data Center Software runs on PC, Linux & MAC US $1200
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
(Image © Total Phase Inc.)
Slide
47
Using the Beagle 480
Capturing a transaction
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
48
.NET Framework Basics
Outline
- .NET Framework Basics
Modern PC Application Development Requirements What is the .NET Framework?
Common Language Runtime (CLR) Framework Class Library Namespaces & Assemblies Common Type System Compilation in the .NET Framework
C++/CLI: The .NET C++ Language Visual C++ 2008 Express Making Calls to Unmanaged DLLs
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
50
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.
1541 USB2
Slide
51
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. All Rights Reserved.
1541 USB2
Microsoft .NET Framework Novell’s Mono Project
Slide
52
Common Language Runtime (CLR)
A virtual machine
Microsoft Visual Basic .NET
C++
C#
…
…
Common Language Specification Framework Class Library
Loads .NET assemblies, Verifies that the IL code is “safe” to execute.
Common Language Runtime Windows
Linux
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Argument type checking
Invokes a JIT compiler to compile the IL to native code before execution Garbage collection Slide
53
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. All Rights Reserved.
1541 USB2
Classes for File/Stream IO
Classes for Windows GUI apps Slide
54
Using Class Libraries (1/2)
.NET projects must have “references” to the Class Library DLLs so that their code can be linked in
- or #using “HID class.dll”
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
55
Using Class Libraries (2/2)
To use a method from a particular class library, you can use the “using namespace” statement to avoid having to type the fully qualified name
#using “System.Windows.Forms.dll” using namespace System::Windows::Forms; int main() { MessageBox::Show(“Hello, World!”);
// Fully-qualified name: // System::Windows::Forms::MessageBox:Show(“Hello, World!”); } © 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
56
Common Language Specification (CLS)
Microsoft Visual Basic .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. All Rights Reserved.
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
Common Type System
Some basic .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. All Rights Reserved.
1541 USB2
Slide
59
Compilation in the .NET Framework VB.NET
C#
VC++ .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. All Rights Reserved.
1541 USB2
Slide
60
Managed vs. 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. All Rights Reserved.
1541 USB2
Slide
61
C++/CLI: The .NET C++ Language
C++/CLI is an adaptation of the standard (ANSI) C++ language by Microsoft, targeted for the .NET framework
New CLR data type keywords New override specifiers New language constructs New C++ operators
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
62
C++/CLI vs. C# and VB.NET
Best of Both Worlds
Reuse existing C/C++ code, .dlls and libraries Easiest to interop with Win32 APIs
Which we need for USB I/O
Use the extensive .NET framework class libraries to simplify GUI development, file I/O, networking
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
63
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.microsoft.com/express/
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
64
Running Visual C++ 2008 .Net Apps
Target PC must have .NET framework version 3.5 or newer installed to run your program Already installed on Windows Vista/7 systems The .NET framework typically installed through Windows Update
Stand-alone redistributable installer also available
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
65
Visual C++ Compilation Modes Compiler Switch -none/clr
/clr:pure /clr:safe
Produces Native mode executable. Compiles classic C/C++ code+libraries (no C++/CLI features) Mixed mode assembly (contains native and MSIL code). Compiles classic C/C++ & C++/CLI code MSIL-only assembly (no native code). Compiles classic C/C++ & C++/CLI code. Can use classic types compiled to MSIL MSIL-only verifiable assembly. Compiles classic C/C++ & C++/CLI code. Can only use .NET types.
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
66
Visual C++ Compilation Modes
Recommended: /clr:pure (default) Features
Produces pure IL code
Minimize need to jump outside CLR during program execution – faster.
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. All Rights Reserved.
1541 USB2
Slide
67
Calling Win32 Functions from .NET
USB I/O requires calling native (Win32) functions in setupapi.dll, user32.dll, winusb.dll ... Handled by a mechanism called P/Invoke (Platform Invoke) – available to all .NET languages Consists of a method (DllImport) that
Finds the .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. All Rights Reserved.
1541 USB2
Slide
68
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 using namespace System::Runtime::InteropServices;
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
71
P/Invoke Example Step 4. Create a managed function declaration, and use attributes to associate it to an existing native function [DllImport(“User32.dll" , CharSet = CharSet::Unicode, EntryPoint="RegisterDeviceNotificationW")] extern "C" HDEVNOTIFY WINAPI RegisterDeviceNotificationUM( HANDLE hRecipient, // Input: The window that will receive the // notification. LPVOID NotificationFilter, // Input: Pointer to a // DEV_BROADCAST_DEVICEINTERFACE structure DWORD Flags // Input: Indicate whether the handle is for a // window or service status ); © 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
72
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
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. All Rights Reserved.
1541 USB2
Slide
76
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. All Rights Reserved.
1541 USB2
Slide
77
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. All Rights Reserved.
1541 USB2
Slide
78
Generic HID Data Descriptor //Class specific descriptor - HID ROM struct{BYTE report[HID_RPT01_SIZE];}hid_rpt01={ { 0x06, 0x00, 0xFF, // Usage Page = 0xFFFF (Vendor Defined) 0x09, 0x01, // Usage (Vendor Usage 1) 0xA1, 0x01, // Collection (Application) 0x19, 0x01, // Usage Minimum (0) 0x29, 0x40, // Usage Maximum (64) 0x15, 0x00, // Logical Minimum (0) 0x26, 0xFF, 0x00, // Logical Maximum (255) 0x75, 0x08, // Report Size 8 bits per report. 0x95, 0x40, // Report Count 64 bytes per report. 0x81, 0x02, // Input (Data, Var, Abs) 0x19, 0x01, // Usage Minimum (Vendor Usage = 0) 0x29, 0x40, // Usage Maximum (Vendor Usage = 64) 0x91, 0x02, // Output (Data, Var, Ads) 0xC0} // End Collection };
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
data
Slide
79
usb_config.h
Need to update this field after creating your HID descriptor table, 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. All Rights Reserved.
0x00 1 Leave at 1 3 3 1 29
1541 USB2
Slide
80
Using the HID Function Driver APIs - Inbound data -
HIDRxPacket(HID_EP,(BYTE*) &ReceivedDataBuffer,64);
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. All Rights Reserved.
1541 USB2
Slide
81
HID Receive Usage void ProcessIO(void) { ... if(!HIDRxHandleBusy(USBOutHandle)) { /* Process received buffer */ //Re-arm the OUT endpoint for the next packet USBOutHandle = HIDRxPacket(HID_EP,(BYTE*) &ReceivedDataBuffer,64); } }
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
82
Using the HID Function Driver APIs - Outbound data -
HIDTxHandleBusy(USBInHandle
Is endpoint available?
HIDTxPacket(HID_EP, (BYTE*)&ToSendDataBuffer,64);
Puts data on the endpoint for transport to host
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
83
HID Transmit Usage case 0x81: //Get push button state ToSendDataBuffer[0] = 0x81; if(sw2 == 1) ToSendDataBuffer[1] = 0x01; else ToSendDataBuffer[1] = 0x00;
if(!HIDTxHandleBusy(USBInHandle)) USBInHandle = HIDTxPacket(HID_EP,(BYTE*)&ToSendDataBuffer,64); break;
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
84
HID Class DLL
.NET Assembly “HID class.dll” Encapsulates the Win32 HID Data transfer APIs Namespace HIDClass::MCHPHIDClass Four Basic Functions:
void bool bool bool
HIDClassInit(VID, PID, len); HIDWriteReport(buffer, len); HIDReadReport(buffer); HIDIsConnected(); (optional)
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
85
Initializing the Methods void HIDClassInit (VID, PID, len, timeout);
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. All Rights Reserved.
1541 USB2
Slide
86
Polled Connection Detection bool HIDIsConnected();
Checks to see if the VID & PID set by HIDClassInit has been enumerated Returns true or false OS inquiry only. Does NOT communicate with device
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
87
Writing A Report bool HIDWriteReport (buffer, len);
Buffer to transmit len – Length of valid data in buffer. 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. All Rights Reserved.
1541 USB2
Slide
88
Reading a Report bool HIDReadReport (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
Documentation
C:\Microchip Solutions\Microchip\Help\ HID Class DLL.chm
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
90
Lab 1 HID Class Thermometer
Lab 1
- 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. All Rights Reserved.
1541 USB2
Slide
92
HID Summary
- Benefits/Drawbacks
Easy installation
no .inf file driver built into OS
Throughput limited to 64 KB/sec HID class.dll provides methods to simplify connection to HID-class devices Must use “generic HID” report descriptor to use the methods in “HID class.dll”
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
93
Building a Custom Class Thermometer using WinUSB
Outline
- 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. All Rights Reserved.
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/user.c
Synchronous model
© 2011 Microchip Technology Incorporated. All Rights Reserved.
Accepts commands from host Returns results Waits for next command
1541 USB2
Slide
96
Custom Class Function Driver APIs
USBGenWrite(ep,pSrc,len);
USBGenRead(ep,pSrc,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. All Rights Reserved.
1541 USB2
Slide
97
Inbound data
USBGenRead(ep,pSrc,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.e. still waiting for the host) Returns FALSE if the transfer is complete
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
98
Vendor Class Receive Usage void ProcessIO(void) { ... if(!USBHandleBusy(USBGenericOutHandle)) { switch(OUTPacket[0]) { case 0x81: //Get push button state ... break; } //Re-arm the OUT endpoint for the next packet USBGenericOutHandle = USBGenRead(USBGEN_EP_NUM,(BYTE*)&OUTPacket,USBGEN_E P_SIZE); } }
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
99
Outbound Data
USBGenWrite(ep,pSrc,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.e. still sending to the host) Returns FALSE if the transfer is complete (i.e. the IN endpoint buffer is available)
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
100
Vendor Class Transmit Usage case 0x81: //Get push button state INPacket[0] = 0x81; if(sw2 == 1) INPacket[1] = 0x01; else INPacket[1] = 0x00;
if(!USBHandleBusy(USBGenericInHandle)) USBGenericInHandle = USBGenWrite(USBGEN_EP_NUM,(BYTE*)&INPacket,USBGEN_ EP_SIZE); break;
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
101
Descriptor Table Settings File usb_descriptors.c /* Device Descriptor */ ROM USB_DEVICE_DESCRIPTOR device_dsc= { 0x12, // Size of this descriptor in bytes USB_DESCRIPTOR_DEVICE, // DEVICE descriptor type 0x0200, // USB Spec Release Number in BCD format 0x00, // Class Code 0x00, // Subclass code 0x00, // Protocol code USB_EP0_BUFF_SIZE, // Max packet size for EP0, see usb_config.h 0x04D8, // Vendor ID 0x0053, // Product ID: Microchip WinUSB Demo 0x0100, // Device release number in BCD format 0x01, // Manufacturer string index 0x02, // Product string index 0x03, // Device serial number string index 0x01 // Number of possible configurations };
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
102
Endpoint Descriptors File usb_descriptors.c /* Endpoint Descriptor */ 0x07, USB_DESCRIPTOR_ENDPOINT, _EP01_OUT, _BULK, USBGEN_EP_SIZE,0x00, 1,
/*sizeof(USB_EP_DSC)*/ //Endpoint Descriptor //EndpointAddress //Attributes //size //Interval
0x07, USB_DESCRIPTOR_ENDPOINT, _EP01_IN, _BULK, USBGEN_EP_SIZE,0x00, 1
/*sizeof(USB_EP_DSC)*/ //Endpoint Descriptor //EndpointAddress //Attributes //size //Interval
_BULK, _CTRL or _INT
(Interrupt)
USBGEN_EP_SIZE defined in usb_config.h #define USBGEN_EP_SIZE 64
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
103
WinUSB Overview & APIs
WinUSB
Before Windows® Vista®, all USB device drivers had to operate in kernel mode WinUSB architecture :
Kernel-mode driver (winusb.sys) User-mode dynamic link library (winusb.dll)
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
105
WinUSB Architecture
No need to write your own driver FULL speed Works with XP and Vista/7 One .inf file
Application
WinUSB DLL User mode
WinUSB.SYS
Vendor Component
USB Stack
USB Device (PIC18F14K50)
© 2011 Microchip Technology Incorporated. All Rights Reserved.
Kernel mode Microsoft Existing Component
1541 USB2
Microsoft New Component
Device
Slide
106
WinUSB features
WinUSB supports:
Device I/O control requests Bulk, control, and interrupt transfers Selective suspend Remote wake No isochronous transfers!
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
107
Key WinUSB APIs
winusb.dll exposes user mode client routines*:
WinUsb_Initialize WinUsb_WritePipe WinUsb_ReadPipe WinUSB_Free
*See http://msdn.microsoft.com/en-us/library/ff540046(v=VS.85).aspx#winusb for the complete list of WinUsb routines. © 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
108
WinUsb_Initialize
Creates a WinUSB handle for the device specified by a file handle
BOOL __stdcall WinUsb_Initialize( __in HANDLE DeviceHandle, __out PWINUSB_INTERFACE_HANDLE InterfaceHandle );
DeviceHandle [in] The handle to the device that CreateFile returned. InterfaceHandle [out] The WinUSB handle for the device. All other WinUSB routines require this handle as input.
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
109
WinUsb_WritePipe
Writes data to a pipe
BOOL __stdcall WinUsb_WritePipe( __in WINUSB_INTERFACE_HANDLE InterfaceHandle, __in UCHAR PipeID, __in PUCHAR Buffer, __in ULONG BufferLength, __out_opt PULONG LengthTransferred, __in_opt LPOVERLAPPED Overlapped );
InterfaceHandle [in] WinUSB handle, for the device, which is returned by WinUsb_Initialize. PipeID [in] An 8-bit value that consists of a 7-bit address and a direction bit. Buffer [in] A caller-allocated buffer that contains the data to write. BufferLength [in] The number of bytes to write. This number must be less than or equal to the size, in bytes, of Buffer. LengthTransferred [out, optional] A pointer to a ULONG variable that receives the actual number of bytes that were written to the pipe. Overlapped [in, optional] An optional pointer to an OVERLAPPED structure, which is used for asynchronous operations. If this parameter is specified, WinUsb_WritePipe immediately returns, and the event is signaled when the operation is complete.
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
110
WinUsb_ReadPipe
Reads data from the specified pipe
BOOL __stdcall WinUsb_ReadPipe( __in WINUSB_INTERFACE_HANDLE InterfaceHandle, __in UCHAR PipeID, __out PUCHAR Buffer, __in ULONG BufferLength, __out_opt PULONG LengthTransferred, __in_opt LPOVERLAPPED Overlapped );
InterfaceHandle [in] WinUSB handle, for the device, which is returned by WinUsb_Initialize. PipeID [in] An 8-bit value that consists of a 7-bit address and a direction bit. Buffer [in] A caller-allocated buffer that receives the data that is read. BufferLength [in] The maximum number of bytes to read. This number must be less than or equal to the size, in bytes, of Buffer. LengthTransferred [out, optional] A pointer to a ULONG variable that receives the actual number of bytes that were copied into Buffer. Overlapped [in, optional] An optional pointer to an OVERLAPPED structure, which is used for asynchronous operations. If this parameter is specified, WinUsb_ReadPipe returns immediately rather than waiting synchronously for the operation to complete before returning. An event is signaled when the operation is complete. © 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
111
WinUsb_Free
Releases all of the resources that WinUsb_Initialize allocated
BOOL __stdcall WinUsb_Free( __in WINUSB_INTERFACE_HANDLE InterfaceHandle );
InterfaceHandle [in] WinUSB handle, for the device, which is returned by WinUsb_Initialize
All WinUsb BOOL functions return TRUE if the operation succeeds. Otherwise, this routine returns FALSE, and the caller can retrieve the logged error by calling GetLastError() .
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
112
Obtaining & Using WinUSB
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.microsoft.com/enus/subscriptions/default.aspx
Default folder:
C:\WinDDK\buildnumber
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
114
Building a .NET Application using WinUSB APIs
1. Set the compilation mode enabling managed code with native types:
Click ProjectPropertiesConfigurat ion PropertiesGeneralCommon Language Runtime Support/clr:pure
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
115
Building a .NET Application using WinUSB APIs
2. Add WDK include paths to MSVC++
Click ToolsOptions+Projects and SolutionsVC++ DirectoriesShow Directories for: "Include files" Then click the Folder icon (new line) and then the "..." button and add these directories to the bottom of the list:
C:\WinDDK\7600.16385.0\inc\ddk C:\WinDDK\7600.16385.0\inc\api
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
116
Building a .NET Application using WinUSB APIs
2.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.16385.0\inc\ddk C:\WinDDK\7600.16385.0\inc\api
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
117
Building a .NET Application using WinUSB APIs
3. Include the header files
#include
#include
Provides definitions for common Win32 types
Provides definitions for SetupDixxx() functions we use to find our device
#include
Provides definitions for WinUSB APIs
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
118
Building a .NET Application using WinUSB APIs
4. Use P/Invoke to create a prototype of each WinUSB API function you will use
using namespace System::Runtime::InteropServices; [DllImport("setupapi.dll" , CharSet = CharSet::Seeifdef, EntryPoint="SetupDiGetClassDevs")] extern "C" HDEVINFO SetupDiGetClassDevsUM( LPGUID ClassGuid, //Input: Supply the class GUID here. PCTSTR Enumerator, //Input: Use NULL here, not important HWND hwndParent, //Input: Use NULL here, not important DWORD Flags); © 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
119
WinUSB – Using the APIs
4-Step Procedure: 1.
2.
3.
4.
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. All Rights Reserved.
1541 USB2
Slide
120
WinUSB - Sample 1
2
GetDevicePath ((GUID) & GUID_DEVICE, // GUID declared in .inf devicePath, // pointer to device path sizeof(DeviceName)); // size of device path deviceHandle = CreateFile (devicePath, ………);// obtain the handle
3
WinUsb_Initialize(deviceHandle, &interfaceHandle); // pass the deviceHandle and you get the Interface Handle
4
WinUSB_WritePipe( interfaceHandle, 0x01, // endpoint address for bulk out output, // output buffer sizeof ( output ), // output buffer length &transferredBytes, // bytes transferred NULL); // optional OVERLAPPED structure
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
121
How to Install winusb.dll & winusb.sys
Create a package**:
WinUSBCoInstaller2.dll (Installs WinUSB files on the target system) WdfCoInstaller01009.dll* and WUDFUpdate_01009.dll* (Kernel-mode coinstallers) .inf file that installs winusb.sys as the device’s function driver
*The actual name might vary. The name is given for version 1.9
** XP Only. Windows Vista/7 already comes with the .dll & .sys - only requires the .inf © 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
122
Sample .inf
A sample WinUSB .inf file is provided
C:\Masters\1541\Lab2\Host\Driver and inf\MCHPWinUSBDevice_v2.inf
You can modify it
Put your VID and PID Device description Disk name
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
123
.inf File Modifications
Modifiable sections in MCHPWinUSBDevice.inf
[Manufacturer] %MFGNAME% = MyDevice_WinUSB,NTx86,NTamd64 [MyDevice_WinUSB.NTx86] %DESCRIPTION% =USB_Install, USB\VID_04D8&PID_0053 [MyDevice_WinUSB.NTamd64] %DESCRIPTION% =USB_Install, USB\VID_04D8&PID_0053
[Dev_AddReg] HKR,,DeviceInterfaceGUIDs,0x10000,"{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. All Rights Reserved.
1541 USB2
Slide
124
.inf File Modifications
Modifiable sections in MCHPWinUSBDevice.inf
[Strings]
MFGNAME="Microchip Technology, Inc." DESCRIPTION="Microchip WinUSB Device" USB\MyDevice.DeviceDesc="WinUSB Demo" WinUSB_SvcDesc="WinUSB Device" DISK_NAME="WinUSB Device Install Disk" DEVICEMANAGERCATEGORY="Custom USB Devices"
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
125
Lab 2 Custom Class Thermometer Using WinUSB
Lab 2
Custom Class Thermometer Using WinUSB
Modify the default WinUSB demo firmware to read BMA150 temperature data In the PC Host App, 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. All Rights Reserved.
1541 USB2
Slide
127
WinUSB - Conclusion
WinUSB allows full-speed USB communication No custom driver needed. Create an *.inf and you have your own driver. Works with XP, Vista & 7 Reference:
C:\Masters\1541\Users Guides and Data Sheets\WinUsb_HowTo.pdf
WinUSB User‐Mode Client Support Routines http://msdn.microsoft.com/enus/library/ff540046(v=VS.85).aspx#winusb
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
128
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
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, 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. All Rights Reserved.
1541 USB2
Slide
132
A Device’s deviceinstanceID Before/After adding a Serial Number
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
133
Device Information in the Registry
Regedit applet available to view the registry
StartRunRegedit
Enumeration key identifies a specific device instance:
\HKLM\SYSTEM\CurrentControlSet\Enum\USB\ \
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
134
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\\
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
135
What is a GUID?
A 128-bit random number
Globally Unique Identifier
Uniquely identifies all Windows classes or entities 2128 or 3.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. All Rights Reserved.
1541 USB2
Slide
136
How to Create a GUID
Any licensed Visual Studio distribution Free tool found with WDK Free tools available on the internet :
http://www.guidgen.com/ http://www.newguid.net/
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
137
Defining a GUID #include // declare/initialize a HID device // interface class GUID GUID InterfaceClassGuid = {0x4d1e55b2, 0xf16f, 0x11cf, 0x88, 0xcb, 0x00, 0x11, 0x11, 0x00, 0x00, 0x30};
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
138
Detecting Devices
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.
1541 USB2
Slide
140
Finding Your Device - What we need to find -
Searching for the device’s path Required to open a “handle” to the device
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
141
Finding Your Device - Procedure -
Obtain your device interface GUID and deviceinstanceID for your device Get a pointer to a “device information set”, for all devices plugged in having the same device interface GUID Enumerate through each “device information element” in the set, looking for a matching deviceinstanceID
On a match, extract the device’s path (to be used in CreateFile())
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
142
Device Information Sets
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
143
Obtain Your Device Interface GUID
Get it from the .inf file you used to install your device ... [Dev_AddReg] HKR,,DeviceInterfaceGUIDs,0x10000,"{58D0 7210-27C1-11DD-BD0B-0800200C9a66 ...
HID devices can use HidD_GetHidGuid() Declare/Define it in your PC code GUID MyInterfaceClassGuid = {0x58d07210, 0x27c1, 0x11dd, 0xbd, 0x0b, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66};
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
144
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";
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
145
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, __in_opt PCTSTR Enumerator, __in_opt HWND hwndParent, __in DWORD Flags );
Usage HDEVINFO hDevInfo = SetupDiGetClassDevs( &InterfaceClassGUID, 0, 0, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE );
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
146
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, __in DWORD MemberIndex, __out PSP_DEVINFO_DATA DeviceInfoData );
Usage
while(SetupDiEnumDeviceInfo(hdevinfo, MemberIndex, &DeviceInfoData)) { /* call SetupDiGetDeviceInstanceID() to query the device information element for it’s deviceinstanceID and look for a match....*/
} © 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
147
SetupDiGetDeviceInstanceID
Retrieves the deviceinstanceID that is associated with a device information element BOOL SetupDiGetDeviceInstanceId( __in HDEVINFO DeviceInfoSet, __in PSP_DEVINFO_DATA DeviceInfoData, __out_opt PTSTR DeviceInstanceId, __in DWORD DeviceInstanceIdSize, __out_opt PDWORD RequiredSize );
Usage
SetupDiGetDeviceInstanceId(hDevInfo, &DeviceInfoData, DeviceInstanceId, RequiredSize, NULL); // Look for a match between found and desired DeviceInstanceIDs if(!wcscmp(DeviceInstanceId, MyDeviceInstanceId)) { wprintf(L"Found Device!\n\n"); FoundDevice = true; break; } © 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
148
SetupDiEnumDeviceInterfaces
Enumerates the device interfaces that are contained in a device information set
Can enumerate interfaces in a single device information element, or the whole info set
BOOL SetupDiEnumDeviceInterfaces( __in HDEVINFO DeviceInfoSet, __in_opt PSP_DEVINFO_DATA DeviceInfoData, __in const GUID *InterfaceClassGuid, __in DWORD MemberIndex, __out PSP_DEVICE_INTERFACE_DATA DeviceInterfaceData );
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
149
SetupDiGetDeviceInterfaceDetail
Returns details about a device interface
BOOL SetupDiGetDeviceInterfaceDetail( __in HDEVINFO DeviceInfoSet, __in PSP_DEVICE_INTERFACE_DATA DeviceInterfaceData, __out_opt PSP_DEVICE_INTERFACE_DETAIL_DATA DeviceInterfaceDetailData, __in DWORD DeviceInterfaceDetailDataSize, __out_opt PDWORD RequiredSize, __out_opt PSP_DEVINFO_DATA DeviceInfoData );
Pointer to a structure containing the device path
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
150
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. All Rights Reserved.
1541 USB2
Slide
151
FindMyDevice
Written for this class Retrieves the device path for a specific device instance, if present Uses SetupDixxx APIs 2 files, FindMyDevice.cpp & .h BOOL FindMyDevice( __in PCWSTR MyDeviceInstanceId, __in const GUID MyInterfaceClassGuid, __out LPWSTR MyDevicePath );
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
152
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. Record the device instance ID
Host
Build/Run a Win32 console project that searches for the device instance, and if found, prints the device path Project uses function FindMyDevice()
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
153
Lab 3a
Solution (main.cpp) #include #include #include “FindMyDevice.h”
// Wide char versions of printf(), strcmp() etc..... // Win32 types etc // Prototype for FindMyDevice(0
int main( int argc, char *argv[ ], char *envp[ ] ) { // Interface Class GUID from the MCHP WinUSB .inf file const GUID MyInterfaceClassGuid = {0x58d07210, 0x27c1, 0x11dd, 0xbd, 0x0b, 0x08, 0x00,0x20, 0x0c, 0x9a, 0x66}; // Specific Device Instance ID to to search for PCWSTR MyDeviceInstanceId = L"USB\\VID_04D8&PID_0053\\1234"; // Wide char array to hold the device path WCHAR MyDevicePath[256]; if(FindMyDevice(MyDeviceInstanceID, MyInterfaceClassGuid, (LPWSTR)&MyDevicePath)) { wprintf(L"Found Device!\n\n"); wprintf(L"Path:[%s]\n\n",&MyDevicepath); return 0; } else { wprintf(L"No Device Found!\n\n"); return 0; } } © 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
154
Lab 3a
Result (device attached)
Result (device detached)
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
155
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
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, does what’s needed, returns control to OS
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
160
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, this message processing is normally hidden
You don’t see the method
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
161
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. All Rights Reserved.
1541 USB2
Slide
162
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. All Rights Reserved.
1541 USB2
Slide
163
Registering for Device Notifications
Applications use the RegisterDeviceNotification(..) 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, 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
164
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. Can be 2 possible values: DEVICE_NOTIFY_WINDOW_HANDLE DEVICE_NOTIFY_SERVICE_HANDLE
Must #include © 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
165
P/Invoke Signature [DllImport(“User32.dll" , CharSet = CharSet::Unicode, EntryPoint="RegisterDeviceNotificationW")] extern "C" HDEVNOTIFY WINAPI RegisterDeviceNotificationUM( HANDLE hRecipient, // Input: The window that will receive the notification. LPVOID NotificationFilter, // Input: Pointer to a DEV_BROADCAST_DEVICEINTERFACE structure DWORD Flags // Input: Indicate whether the handle is for a window or // service status );
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
166
Calling the Function #include #include ... [DllImport... ... GUID InterfaceClassGuid = {0x4d1e55b2, 0xf16f, 0x11cf, 0x88, 0xcb, 0x00, 0x11, 0x11, 0x00, 0x00, 0x30}; DEV_BROADCAST_DEVICEINTERFACE MyDevBroadcastInterface; MyDevBroadcastInterface.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; MyDevBroadcastInterface.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE); MyDevBroadcastInterface.dbcc_reserved = 0; //Reserved says not to use... MyDevBroadcastInterface.dbcc_classguid = InterfaceClassGuid; RegisterDeviceNotificationUM((HANDLE)this->Handle, &MyDevBroadcastInterface, DEVICE_NOTIFY_WINDOW_HANDLE);
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
167
Processing the Message
Override default WndProc() method
Receives a Message Structure m Test m.msg for WM_DEVICECHANGE Test m.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. All Rights Reserved.
1541 USB2
Slide
168
Lab 3b
WinUSB Thermometer Using WM_DEVICECHANGE
Device
Use same .hex file as Lab3a
Host
Create simple .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. All Rights Reserved.
1541 USB2
Slide
169
Lab 3b
Form Design “Event Triggers” WM_DEVICECHANGE on/off
Timer tick event
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
170
Handling Attach/Detach Events - Conclusion -
USB Attach/Detach is asynchronous by nature
Windows applications are event-driven (A .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. All Rights Reserved.
1541 USB2
Slide
171
Detecting Devices - Summary -
Finding Your Device
Obtaining a Handle
SetupDixxx(..) CreateFile(..)
Handling Attach/Detach Events
RegisterDeviceNotification(..) WndProc()
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
172
Summary/Resources
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
173
USB Transfer Recap
HID class – It just works WinUSB – Flexibility, Speed, Microsoft Support
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
174
Summary
Today we covered:
The benefits/limitations of the HID, 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, connection detection and device communications
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
175
Additional Resources
Books
Weblinks
www.usb.org/phpbb/ forum.microchip.com
3rd Party Training (.NET Languages)
www.microchip.com/usb www.microsoft.com/whdc/connect/usb/winusb_howto.mspx www.usb.org (USB Spec, class definitions) www.lvr.com (USB Examples) www.beyondlogic.org/usbnutshell/usb1.htm (Tutorial)
Forums
“USB Complete, 4/E” – Jan Axelson (C# & VB Example Code) “Microsoft Windows Internals, 5/E” – Mark Russinovich “Foundations of C++/CLI: The Visual C++ Lanaguage for .NET 3.5” – Gordon Hogenson “Pro Visual C++/CLI & the .NET 3.5 Platform” – Stephen Fraser “Expert C++/CLI: .NET for Visual C++ Programmers ” – Marcus Heege
www.softwaretrainingacademy.com
App Notes
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
176
Trademarks •
•
•
• • •
The Microchip name and logo, the Microchip logo, dsPIC, KeeLoq, KeeLoq logo, MPLAB, PIC, PICmicro, PICSTART, PIC32 logo, rfPIC and UNI/O are registered trademarks of Microchip Technology Incorporated in the U.S.A. and other countries. FilterLab, Hampshire, HI-TECH C, Linear Active Thermistor, MXDEV, MXLAB, SEEVAL and The Embedded Control Solutions Company are registered trademarks of Microchip Technology Incorporated in the U.S.A. Analog-for-the-Digital Age, Application Maestro, chipKIT, chipKIT logo, CodeGuard, dsPICDEM, dsPICDEM.net, dsPICworks, dsSPEAK, ECAN, ECONOMONITOR, FanSense, HI-TIDE, In-Circuit Serial Programming, ICSP, Mindi, MiWi, MPASM, MPLAB Certified logo, MPLIB, MPLINK, mTouch, Omniscient Code Generation, PICC, PICC-18, PICDEM, PICDEM.net, PICkit, PICtail, REAL ICE, rfLAB, Select Mode, Total Endurance, TSHARC, UniWinDriver, WiperLock and ZENA are trademarks of Microchip Technology Incorporated in the U.S.A. and other countries. SQTP is a service mark of Microchip Technology Incorporated in the U.S.A. All other trademarks mentioned herein are property of their respective companies. © 2011, Microchip Technology Incorporated, All Rights Reserved.
© 2011 Microchip Technology Incorporated. All Rights Reserved.
1541 USB2
Slide
177
View more...
Comments