1541 USB2
USB: Bridging the gap between
PC application and end device
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 2
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
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 3
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
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 4
Agenda (Continued)
Matching a Driver to a Device
Detecting Devices
Finding Your Device
Lab 3a – Find 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 5
PIC18F
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
Migration
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
16-bit
8-bit
Pe
rfor
mance
32-bit
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
~40 USB PIC
MCUs
The industry’s strongest
scalable product, family
and software migration
path
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 6
Class Folders
C:\Masters\1541
\Development Tools
\Lab1..Lab3
\Device
\Device Solution
\Host
\Host Solution
\Microchip
\Presentation and Handouts
\Users Guides & Data Sheets
Application Overview
(Thermometer)
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 8
Outline
Application Overview
-
Application Requirements
Demonstrate moving data between PC
Application and end device via USB
The data is Temperature
Commands (see Appendix E in lab
manual):
0 – get Version
1 – get Temperature
2 – get Potentiometer
Platform: PIC18F Starter Kit 1 (DM180021)
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 9
Board Key Components
On Board Debugger
(provides SYS CLK)
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 10
Board Key Components
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 11
Board Key Components
Capacitive Touch Buttons
and Scroll Bar
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 12
Board Key Components
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 13
Board Key Components
3 Axis Acceleration Sensor
(BMA150)
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 14
Board Key Components
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 15
Board Key Components
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 16
Board Key Components
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 17
Board Key Components
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 18
Board Key Components
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 19
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 21
Full-Speed USB Basics
USB is a “Single Master + Multiple Slaves” polled bus
In/Out WRT host
Mouse
Speaker
Printer
USB Host Controller (Master)
and Root Hub
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 22
Logical Device
Up to 16 bidirectional pipelines
“End Points”
Data CRC-32 protected
Bad packets auto resent*
Host
Device
EP0
EP1-16
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 23
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 24
Transfer types
Control
Bus configuration
Interrupt
Low rate/bounded latency
Bulk
Guaranteed integrity
Isochronous
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 25
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
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 26
USB Device Classes
Joystick
Mouse
External
Hard Drive
ICD2
COM Port
MCP2200
Thumb
Drive
Data Glove
Keyboard
Ethernet
Adapter
Human Interface Device Class
(HID)
Mass Storage Device
Class (MSD)
Communication Device
Class (CDC)
Custom Class
(Vendor Class)
Many more classes….
PICkit™ 2
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 27
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
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 28
USB Driver Choices
Features
HID
CDC
mchpusb.sys
(v1.0.0.6)
WinUSB
LibUSB
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
**
Transfer Types
Control
Yes
No
Yes
Yes
Yes
Interrupt
Yes
No
Yes
Yes
Yes
Bulk
No
Yes
Yes
Yes
Yes
Microchip USB Framework
(MCHPFSUSB)
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 30
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 31
Default Install Directory
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 32
Default Install Directory
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 33
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 34
Generic USB Project
General structure
./USB/Your application
main.c
usb_descriptors.c
HardwareProfile.h
usb_config.h
./Microchip
/Include
/USB
/Common
/…
Editable files
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 35
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 36
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
// Input
#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
// Input
#if defined
(USE_USB_BUS_SENSE_IO)
#define
USB_BUS_SENSE PORTAbits.RA1
#else
#define
USB_BUS_SENSE 1
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 37
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 38
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 39
MCHPFSUSB Framework
Polled Program Flow
-Reset
main()
InitializeSystem()
while(1)
Your application
code
USBDeviceTasks()
ProcessIO()
USB Stack
Cooperative
Multitasking!!
No blocking
functions.
Use state
machine.
You edit UserInit()
Function
Services
CDCTxService()
MSDTasks()
Re-arm OUT Endpoint
(HID & Generic)
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 40
Reset
main()
InitializeSystem()
while(1)
Your application
code
ProcessIO()
You edit
UserInit()
USB Interrupt
Context
USBDeviceTasks()
MCHPFSUSB Framework
Interrupt Program Flow
-USBDeviceAttach()
Function
Services
Notifies the stack
when the device is
attached
CDCTxService()
MSDTasks()
Re-arm OUT Endpoint
(HID & Generic)
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 41
Cooperative Multitasking
Task B - 100us
Task A
900us
Max Loop Time
500us VS. 1000us
Task A.1 - 200us
State Machine
Task A.2 - 400us
Task A.3 - 300us
Main Loop
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 42
#include
“./USB/usb.h”
#include
“./USB/usb_function_cdc.h”
#include
“HardwareProfile.h”
void
UserInit(
void
){
…
…
}
void
ProcessIO(
void
){
if
((USBDeviceState < CONFIGURED_STATE)||(USBSuspendControl==1))
return
;
…
…
CDCTxService();
}
static void
InitializeSystem(
void
){
#if define …
#endif
UserInit();
USBDeviceInit();
}
int
main(
void
){
InitializeSystem();
while
(1){
USBDeviceTasks();
ProcessIO();
}
}
Code Example
Main.c
Needed (usb_config.h is called by usb.h)
Put your initzialization code here
Put your application code (state machine) here
No need to change
Conditional compiling
(No need to change)
USBDeviceTasks()
is executed into an ISR
(High Priority PIC18,
_USB1Interrupt()
© 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
Modify that callback function to take
appropriate actions for each of these
conditions
Bottom of main.c
MAIN
PROGRAM
LIBRARY
FUNCTION
CALLBACK
FUNCTION
Application Layer
USB firmware
stack
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 45
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)
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 46
Hardware Protocol Analyzer
Image © USB Complete: The
Developer’s Guide by Jan Axelson
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 47
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 Slide 48
Using the Beagle 480
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 50
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
© 2011 Microchip Technology Incorporated. 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. 1541 USB2 Slide 52
What is the .NET Framework?
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
Microsoft .NET
Framework
Novell’s Mono Project
Windows
Linux
Common Language Runtime
Framework Class Library
Common Language Specification
Microsoft Visual
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 53
Common Language Runtime (CLR)
A virtual machine
Loads .NET
assemblies,
Verifies that the IL
code is “safe” to
execute.
Argument type
checking
Invokes a JIT
compiler to compile
the IL to native code
before execution
Garbage collection
Windows
Linux
Common Language Runtime
Framework Class Library
Common Language Specification
Microsoft Visual
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 54
Framework Class Library (FCL)
A set of thousands of
classes that provide
system services
Wrap Win32 APIs &
more
Examples
System::IO
Classes for
File/Stream IO
System::Windows::
Forms
Classes for Windows
GUI apps
Windows
Linux
Common Language Runtime
Framework Class Library
Common Language Specification
Microsoft Visual
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 55
Using Class Libraries (1/2)
.NET projects must have “references” to the
Class Library DLLs so that their code can be
linked in
or
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 56
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 58
Common Language Specification (CLS)
CLS represents the
basic functionality
each .NET language
should implement if
they are to
interoperate with each
other
Class written in one
language can inherit
from a class written in
another
Common type system
Prohibit use of
pointers
Support
inter-language debugging
Windows
Linux
Common Language Runtime
Framework Class Library
Common Language Specification
Microsoft Visual
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 59
Common Type System
Some basic .NET types and their language keywords
Base Class
Visual Basic
2008
C#
C++/CLI
System::Byte
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 60
Compilation in the .NET Framework
VB.NET
C#
VC++ .NET
vbc Compiler
csc Compiler
cpp Compiler
MSIL
Unmanaged
Code
Common Language Runtime JIT Compiler
CLR Services
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 61
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
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 62
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
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 63
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
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 64
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
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 65
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 66
Visual C++ Compilation Modes
Compiler Switch
Produces
-none-
Native mode executable. Compiles
classic C/C++ code+libraries (no
C++/CLI features)
/clr
Mixed mode assembly (contains native
and MSIL code). Compiles classic C/C++
& C++/CLI code
/clr:pure
MSIL-only assembly (no native code).
Compiles classic C/C++ & C++/CLI code.
Can use classic types compiled to MSIL
/clr:safe
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 67
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
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 68
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 69
P/Invoke Example
Create a managed entry point for calling
Win32 API
RegisterDeviceNotification(..)
Step 1.
Set compilation mode to \clr, \clr:pure
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 70
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 71
P/Invoke Example
Step 3.
#include the windows header file(s) & import
the namespace containing the DllImport
method
#include <Windows.h>
using namespace
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 72
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 73
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
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 75
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
© 2011 Microchip Technology Incorporated. 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”
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 77
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
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 78
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 79
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 Slide 80
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
0x00
#define HID_EP
1 Leave at 1
#define HID_INT_OUT_EP_SIZE
3
#define HID_INT_IN_EP_SIZE
3
#define HID_NUM_OF_DSC
1
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 81
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 82
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 83
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
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 84
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 85
HID Class DLL
.NET Assembly “HID class.dll”
Encapsulates the Win32 HID Data transfer
APIs
Namespace HIDClass::MCHPHIDClass
Four Basic Functions:
void HIDClassInit(VID, PID, len);
bool HIDWriteReport(buffer, len);
bool HIDReadReport(buffer);
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 86
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)
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 87
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
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 88
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 89
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 90
Documentation
C:\Microchip Solutions\Microchip\Help\
Lab 1
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 92
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
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 93
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
Building a Custom Class
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 95
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
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 96
Vendor Class
Firmware Structure
Reset
main()
InitializeSystem()
main()
You edit in
main.c/user.c
ProcessIO()
USB Interrupt
Context
You Edit
UserInit()
USBDeviceTasks()
Synchronous model
Accepts commands from host
Returns results
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 97
Custom Class Function Driver APIs
-
USBGenWrite(ep,pSrc,len);
Copies data from user’s buffer to the IN Ep buffer
Returns a USBGenericInHandle
USBGenRead(ep,pSrc,len)
Copies data from the OUT Ep buffer to the user’s
buffer
Returns a USBGenericOutHandle
USBHandleBusy(USBGenericInHandle)
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 98
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)
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 99
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 100
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 101
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 102
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 103
Endpoint Descriptors
File usb_descriptors.c
/* Endpoint Descriptor */
0x07, /*sizeof(USB_EP_DSC)*/
USB_DESCRIPTOR_ENDPOINT, //Endpoint Descriptor
_EP01_OUT, //EndpointAddress
_BULK
, //Attributes
USBGEN_EP_SIZE
,0x00, //size
1, //Interval
0x07, /*sizeof(USB_EP_DSC)*/
USB_DESCRIPTOR_ENDPOINT, //Endpoint Descriptor
_EP01_IN, //EndpointAddress
_BULK
, //Attributes
USBGEN_EP_SIZE
,0x00, //size
1 //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 105
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
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 106
WinUSB Architecture
No need to write
your own driver
FULL speed
Works with XP and
Vista/7
One .inf file
Application
USB Stack
User mode
Kernel mode
USB Device
(PIC18F14K50)
Device
WinUSB.SYS
Microsoft
Existing
Component
Vendor
Component
Microsoft
New
Component
WinUSB
DLL
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 107
WinUSB features
WinUSB supports:
Device I/O control requests
Bulk, control, and interrupt transfers
Selective suspend
Remote wake
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 108
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
© 2011 Microchip Technology Incorporated. All Rights Reserved. 1541 USB2 Slide 109
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 110
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 111