USB Made Easy
USB Made Easy
Class Objectives
When you finish this class you will be able to:
Describe the basics of USB, and how to apply
them in an embedded application
Identify Microchip’s USB MCUs, development
boards, and USB software frameworks relevant to
your project
Analyze the capabilities and limitations of the
CDC device class, and implement basic
communications using the CDC device framework
on PIC18/24/32 MCUs
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 2
Agenda
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 3
USB Fundamentals
Universal Serial Bus
Data Analysis,
Data Logging,
Firmware Updates,
Diagnostics,
Embedded Applications!
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 5
USB Basics
USB is a “Single Master + Multiple Slaves” polled bus
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 7
Embedded Host
Embedded Host connects to a fixed number of USB
Peripheral Devices – USB Drivers fixed in firmware
Advantage: Smaller, less complex embedded firmware
Example: Remote Temperature Data Logger
Download data to USB Flash Drive
Act as Host when connected to Flash Drive but …
Not connected directly to PC Host
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 8
USB Peripheral Device
Responds to Host, cannot initiate transactions
Requires drivers to be recognized by the Host
Hardware/Firmware to respond to Host
Microchip’s PIC® MCUs are used in USB
Peripheral Devices
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 9
USB On-The-Go (OTG) and Dual Role
USB On-The-Go (OTG) allows Application to operate as
Host or Device:
PDA (Device) connected to PC (Host)
PDA (Host) connected to Thumb drive (Device)
PDA in Dual Role Mode
PDA connected to PDA, host and device roles can switch
PDA in OTG mode
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 10
Physical Bus Topology
Host (Tier 1)
USB Host Controller
& Root Hub
Tier 5 Hub
PIC18 USB devices are
designed to be peripherals.
Tier 6 Hub PIC24/PIC32 can function as
either embedded host or
Tier 7 Data Logger peripheral.
Hub
Up to 126 peripherals...
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 11
Physical Interface
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 12
Standard Connectors
- USB 2.0 Specification -
“A”
USB Host
“B” “mini-B”
FS, HS FS, HS
Device Device
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 13
Standard Connectors
- Micro-USB Specification -
Micro-A/B receptacle
Only allowed on OTG products
Micro-A plug
Indicates who is initially the host (OTG)
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 14
The “Logical” Device
Device
(Manufacturer: Microchip Technology)
(Product: Mouse in a Circle Demo)
Configuration
Interface
Analog/Digital I/O
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 15
Endpoints: Source/Destination
of USB Data in a Peripheral
Data Bucket
USB PIC MCU
®
Function Layer
Client Software Function
Client Software Interface
Client Software
Buffers Interface-specific
Layer
USB Device
USB Device
zero
Bus Interface
Bus Interface
Layer
Layer
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 18
Sending/Receiving on the Device
Only high level access
Example: CDC Class RS-232 Emulation
BOOL USBUSARTIsTxTrfReady(void);
void putUSBUSART(char *data, BYTE Length);
BYTE getsUSBUSART(char *buffer, BYTE len);
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 19
Transactions
An Endpoint is a Buffer
Data Bucket
IN Transaction RAM
Endpoint 1 IN “Caps-Lock”
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 21
USB Transaction
USB Transaction
Token Packet
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 22
USB Transaction – IN
USB Transaction
IN Token Packet
Data Packet
Handshake Packet
Acknowledge - ACK
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 23
IN Transaction ACK
USB Traffic USB PIC® MCU
USB Transaction
IN Token Packet
(to EP1 IN)
Serial If (
UO RAM
SFR EP1 OUT BD
(UOWN, Length,
WN
Endpoint 1 OUT
== Pointer)
Interface 1)
SFR EP1 IN BD
Data Packet SIE Sends Data RAM
(UOWN, Length,
Engine Endpoint 1 IN
0
Pointer)
W N=
ts UO
Se
Keystrokes
Update BD
Handshake Packet
putsUSBUSART( )
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 24
IN Transaction NAK
USB Traffic USB PIC® MCU
USB Transaction
IN Token Packet
(to EP1 IN)
Serial If (
UO RAM
SFR EP1 OUT BD
(UOWN, Length,
WN
Endpoint 1 OUT
== Pointer)
Interface 0)
SFR EP1 IN BD
RAM
(UOWN, Length,
Handshake
Engine Endpoint 1 IN
Pointer)
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 25
OUT Transaction ACK
USB Traffic USB PIC® MCU
USB Transaction
OUT
Token Packet If (
(to EP1 OUT) Serial UO
WN
==
1 )
Interface RAM
SFR EP1 OUT BD
Data Packet SIE Deposits Data
Endpoint 1 OUT
(UOWN, Length,
Pointer)
Engine WN
= 0
h, UO
RAM
SFR EP1 IN BD
gt
Handshake LenEndpoint 1 IN
(UOWN, Length,
s
Set
SIE Sends ACK Pointer)
Packet
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 26
OUT Transaction NAK
USB Traffic USB PIC® MCU
USB Transaction
OUT
Token Packet If (
(to EP1 OUT) Serial UO
WN
==
0 )
Interface RAM
SFR EP1 OUT BD
Data Packet Endpoint 1 OUT
(UOWN, Length,
SI Pointer)
Engine
E
Di
sc SFR EP1 IN BD
ar RAM
Handshake ds (UOWN, Length,
D Endpoint 1 IN
SIE Sends NAK at Pointer)
Packet a
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 27
Transfer: A Group of Related
Transactions
MPUSBWrite(EP7, Pointer, Size = 129, Timeout)
Transfer
Key:
Transaction 1
64 Byte Payload OUT Token Packet
Data Packet
Transaction 2
64 Byte Payload ACK Handshake Packet
Transaction 3
1 Byte Payload
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 28
Data Transfer Types
- Full Speed USB -
1400
1216
1200
1023
1000 832
800
KByte/s
600 Low
400 Full
200 64
24 0.8
0
Control Interrupt Bulk Iso
Transfer Type
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 31
Transfer Types – Examples
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 32
USB Device Classes
Floppy
Data Glove Drive
Ethernet
Adapter
Mouse
External
Hard Drive
PICkit™ 3
Starter Kit Modem
Mass Storage Device
Joystick Class (MSD)
Communication Device
Class (CDC) MPLAB®
Keyboard REAL ICE™
in-circuit emulator
Custom Class
(Vendor Class)
Human Interface Device Class
(HID)
Many more classes….
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 33
Considerations When Using
Standard Classes
The Logical USB Device is pre-defined
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 COM port
Main Benefit: Cross-platform use
Custom OS driver is not required!
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 34
USB Driver Choices
- Windows® PC Host -
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 35
Enumeration
The Enumeration Process
POWERED
Power Bus
(self/bus) reset
ATTACHED DEFAULT
DETACHED ADDRESS
Get
Descriptors
CONFIGURED
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 37
Auto-Detection: Full-Speed
Peripheral Device
USB PIC® MCU
VUSB 3.3 V
Full Speed Identification
D+ line pull-up
1.5 k±5%
+5V
D+
Transceiver
D-
GND
USB
Connector
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 38
Auto-Detection: Low-Speed
Peripheral Device
USB PIC® MCU
VUSB 3.3 V
Low Speed Identification
D- line pull-up
1.5 k±5%
+5V
D+
Transceiver
D-
GND
USB
Connector
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 39
On-chip Pull-up Resistors
Peripheral Device
USB PIC® MCU
VUSB 3.3 V
On-chip pull-up
resistors available!
+5V
D+
Transceiver
D-
GND
USB
Connector
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 40
Address and Configuration: EP0
See Chapter 9 in USB 2.0 Spec for more info.
USB PIC® MCU
Endpoint 0 OUT
(Control Data)
Control Transfers
Endpoint 0 IN
(Control Data)
Descriptors
Other Endpoints
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 41
Descriptors
String 0 Device
String 1
To other Configurations if any
String N Configuration 1
To other
Interfaces if any
Interface 0 Interface 1
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 42
Descriptors - Example
USB 2.0, VID = 0x04D8,
Manu. String Device PID = 0x0007, Num. Configurations,
Strings?
Microchip
Configuration #1: Bus-Powered,
Configuration 1 Remote Wakeup, 500mA, Num.
Prod. String Interfaces
PICDEM™ USB
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 43
Power Planning
- Architecture -
Function Controller +
Function
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 44
Power Planning
- Architecture -
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 45
Power Planning
- Architecture -
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 46
Power Planning
- Do I Need Self-Power? -
Device will need to provide self
power if:
It needs to function when not attached to
the bus
It needs more than 500 mA
It needs to function when connected to
battery powered PCs, or bus-powered hubs
i.e. needs to function during Suspend mode
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 47
VID & PID
Vendor ID (VID): 16-bit number
Required to market your product
http://www.usb.org/developers/vendor
USD $2,000
Technical & Legal trouble if not using an
approved VID
Product ID (PID): 16-bit number
Microchip’s Sub-licensing Program
Every product line is required to have a unique
combination of VID and PID
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 48
USB Compliance
Compliance Testing
Must pass to use USB logo
Test fee: USD ~$1,500
Tests device for conformance to USB Device
Framework and Class standard control requests
USB Protocol Analyzer
“USBCV” USB Command Verifier
www.usb.org/developers/tools
Electrical Signal Quality
Power Management
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 49
Compliance Testing
Built in Pullups
+5V
D+
Transceiver
D-
GND
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 53
Microchip’s USB PIC® MCUs
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 54
PIC18 USB Product Offerings
128KB
128K/4K
128K/4K 128K/4K
128K/4K
PIC18F67J50 PIC18J87J50
96KB
96K/4K
96K/4K 96K/4K
96K/4K
PIC18F66J55 PIC18F86J55
64K/4K
64K/4K 64K/4K
64K/4K
32KB 64KB
PIC18F66J50 PIC18F86J50
32K/2K
32K/2K 32K/2K
32K/2K 32K/4K
32K/4K 32K/4K
32K/4K
PIC18F2455 PIC18F4455
PIC18F2458 PIC18F4458
16K/768
16K/768 16K/768
16K/768 16K/768
16K/768
8KB 16KB
PIC18F13K50
512K/32K
512K/32K
4ch
4chDMA
DMA++USB
USB
DMA
DMA+Trace
+Trace
PIC32MX460F512L
256KB
256K/16K
256K/16K 256K/32K 256K/16K
256K/16K 256K/16K
256K/16K 256K/32K
256K/32K
256K/32K 4ch
4chDMA
DMA++USB
USB
4ch
4chDMA
DMA++USB
USBDMA
DMA DMA
DMA+Trace
+Trace
PIC24FJ256GB106 PIC32MX440F256H PIC24FJ256GB108 PIC24FJ256GB110 PIC32MX460F256L
192KB
192K/16K
192K/16K 192K/16K
192K/16K 192K/16K
192K/16K
PIC32MX440F128L
PIC24FJ128GB106 PIC24FJ128GB108 PIC24FJ128GB110
64K/16K
64K/16K 64K/16K
64K/16K 64K/16K
64K/16K
64 Pin PIC24F
80 Pin PIC32
100 Pin
PIC24F PIC32
*Source: Vendor Published Specifications
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 56
USB Module
Peripheral Device Board
3.3 V Regulator
Bus Pull-Up
Resistors
D+/D- Transceiver
Data RAM
Program
USB RAM Memory
SIE Control
Registers
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 57
PIC18F14K50 Low Pin Count USB MCU
Features Peripherals
8-bit, 16Mips ECCP
Voltage 1.8 to 5.5V SPI/I²C™
16 KB Flash USART
512 Bytes SRAM 9 ch. x 10-bit A/D
256 Bytes DPRAM 1 x 8-bit, 3 x 16-bit timers
256 Bytes EEPROM 2 x Comparators
20 – pins USB 2.0 Full Speed
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 58
Serial Interface Engine
SIE ...
Serializes and deserializes PIC18 USB MCU
USB data
Encodes and decodes NRZI
data
Handles bit stuffing
D+/D- Transceiver
Data RAM
Checks CRC to validate data
packet Program
Detects bus signaling events USB RAM Memory
and notifies the CPU through SIE Control
interrupts Registers
Handles USB transactions
Handles handshaking
protocol
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 59
Clock Configuration Example
Peripheral Device Board
Divide by 2
Accept 4 MHz Input Only
32 MHz :
8 MIPs
PIC®
SIE MCU
Core
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 60
PICDEM™ Full-Speed
USB Demo Kit
Contains everything you need to get started quickly
Use with any of the PIC18F4550 family microcontrollers
Includes self-directed class and lab material
The Demo Kit provides all of the hardware and software
needed to demonstrate and develop a complete USB
communication solution
Priced from $59.99
Part Numbers
DM163025
Available Now
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 61
PIC18FXXJ50 Full-Speed
USB Plug-In Module (PIM)
Contains everything you need to get started quickly
Use with any of the PIC18F87J50 or PIC18F46J50 family
microcontrollers
Can be plugged into PICDEM™ HPC Explorer Board or
PICDEM PIC18 Explorer Board
Can be operated as a stand-alone board
Priced from $40.00
Part Numbers
MA180021 - PIC18F87J50 FS USB PIM
MA180024 - PIC18F46J50 FS USB PIM
DM183022 - PICDEM HPC EXPLORER BOARD
DM183032 - PICDEM PIC18 EXPLORER BOARD
Available Now
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 62
Low Pin Count
USB Development Kit
Contains everything you need to get started quickly
Use with new 20-pin PIC18F USB microcontrollers –
PIC18F13K50, PIC18F14K50
Includes self-directed class and lab material
Quickly implement common USB functions:
RS-232 to Serial
Keyboard/Mouse, etc…
Priced from $39.99
Part Numbers
DV164126 (w/PICkit™ 2)
DM164127
Available Now
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 63
PIC18 Starter Kit
Functions as a USB mouse, joystick or mass storage
device all using the on-board capacitive touch sense pads
Includes a MicroSD™ memory card, potentiometer,
acceleration sensor, and OLED display
On-board debugger/programming
Completely USB-powered
Demonstrates PIC18 Family
USB communication
Priced from $59.98
Part Numbers
DM180021
Available Now
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 64
Easy To Get Started with
PIC18 Starter Kit!
Connect the USB cable from the PC to
the demo board
Use the OLED display and touch pads to
select from demo applications
Demo software included with the kit
enables it to:
Read from the memory card (MSD)
Function as a USB Mouse or Joystick (HID)
Function as a simple COM port (CDC)
Scroll through the demo code options
using the touch buttons
A CD is included with the MPLAB® IDE,
Free C Compiler, demo code, and User’s
Guide
No need for an external debugger or
programmer – customize your PIC18
code
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 65
Microchip USB Frameworks
- www.microchip.com/usb -
MCHPFSUSB Framework
PIC18F & PIC24F & PIC32 USB MCUs
C18/C30/C32 Compatible
MPLAB® IDE Project Centric
Device Stacks
Audio, HID, CDC, MSD, Custom
Polling or Interrupt driven
Embedded Host Stack
PIC24F & PIC32 USB MCUs
Polling or Event-driven Scheme
Client drivers for CDC, Charger, Custom, HID, MSD, Printer
On-The-Go (OTG) Support
PIC24F & PIC32 USB MCUs
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 66
www.microchip.com/usb
Microchip USB Design Center
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 68
Demo
- Capturing a Transaction -
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 69
Application Overview (Thermometer)
Microchip USB Framework (MCHPFSUSB)
MCHPFSUSB v2.x Framework
General Structure
/Your application
/main.c
/usb_descriptors.c
/hardware profile.h
/usb_config.h
/Microchip
/Include
/USB
/IRDA
/…
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 72
MCHPFSUSB v2.x Framework
- Stuff to Change -
usb_descriptors.c
Descriptors
VID & PID
Class Specific
/* Device Descriptor */
ROM USB_DEVICE_DESCRIPTOR device_dsc=
{ 0x12, // Size of this descriptor in bytes
USB_DESCRIPTOR_DEVICE, // DEVICE descriptor type
0x0110, // USB Spec Release Number
0x00, // Class Code
0x00, // Subclass code
0x00, // Protocol code
EP0_BUFF_SIZE, // Max packet size for EP0,
0x0000, // Vendor ID
0x0000, // Product ID
…
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 73
MCHPFSUSB v2.x Framework
- More Stuff to Change -
main.c
UserInit()
Main Loop
USBDeviceTasks()
Polled or Interrupt-driven
ProcessIO()
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 74
MCHPFSUSB v2.x
- Device Side Program Flow (POLLED) -
main()
Cooperative
Multitasking!!
USBDeviceTasks() usb_device.c
No blocking
functions.
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 75
Cooperative Multitasking
Main Loop
State Machine
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 76
MCHPFSUSB v2.x
- Device Side Program Flow (INTERRUPT) -
main()
USB Interrupt
Context ProcessIO()
You edit in
USBDeviceTasks() main.c/user.c
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 77
Building a HID Class Thermometer
Outline
- HID Class Thermometer -
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 79
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”
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 80
HID limitations
Interrupt transfers only
Up to 64 bytes per transfer (FS)
No more than one transfer per frame.
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 81
Doing the Math
~16 seconds/MB
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 82
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
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 83
Mouse Report Descriptor
ROM struct{BYTE report[HID_RPT01_SIZE];}hid_rpt01={
{0x05, 0x01, /* Usage Page (Generic Desktop) */
0x09, 0x02, /* Usage (Mouse) */
0xA1, 0x01, /* Collection (Application) */
0x09, 0x01, /* Usage (Pointer) */
0xA1, 0x00, /* Collection (Physical) */
0x05, 0x09, /* Usage Page (Buttons) */
0x19, 0x01, /* Usage Minimum (01) */
0x29, 0x03, /* Usage Maximum (03) */
0x15, 0x00, /* Logical Minimum (0) */
0x25, 0x01, /* Logical Maximum (1) */
0x95, 0x03, /* Report Count (3) */
0x75, 0x01, /* Report Size (1) */
0x81, 0x02, /* Input (Data, Variable, Absolute) */
0x95, 0x01, /* Report Count (1) */
0x75, 0x05, /* Report Size (5) */
0x81, 0x01, /* Input (Constant) ;5 bit padding */
0x05, 0x01, /* Usage Page (Generic Desktop) */
0x09, 0x30, /* Usage (X) */
0x09, 0x31, /* Usage (Y) */
0x15, 0x81, /* Logical Minimum (-127) */
0x25, 0x7F, /* Logical Maximum (127) */
0x75, 0x08, /* Report Size (8) */
0x95, 0x02, /* Report Count (2) */
0x81, 0x06, /* Input (Data, Variable, Relative) */
0xC0, 0xC0}
};
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 84
Usage Tables
Don’t have to start from scratch
USB Usage tables
Report descriptors for everything from a
mouse to aircraft cockpit
www.usb.org/developers/hidpage
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 85
Descriptor Tool
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 86
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
0xA1, 0x01, // Collection
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
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 87
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
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 88
HID Receive Usage
void ProcessIO(void)
{
...
if(!HIDRxHandleBusy(USBOutHandle)) {
switch(ReceivedDataBuffer[0]) {
case 0x81: //Get push button state
...
break;
}
//Re-arm the OUT endpoint for the next packet
USBOutHandle =
HIDRxPacket(HID_EP,(BYTE*)&ReceivedDataBuffer,64);
}
}
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 89
Using the HID Function Driver APIs
- Outbound data -
HIDTxHandleBusy(USBInHandle
Is endpoint is available?
HIDTxPacket(HID_EP,
(BYTE*)&ToSendDataBuffer,64);
Puts data on the endpoint for transport to
host
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 90
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;
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 91
MCHPHID PC DLL
MCHPHIDClass
Encapsulates the HID Data transfer
Four Functions:
Bool USBHIDClassInit(VID, PID, len);
Bool USBWriteReport (buffer);
Bool USBReadReport (buffer);
Bool USBIsConnected (); (optional)
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 92
HID Class Init
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 93
Write Report
bool USBHIDWriteReport (buffer,
len);
Buffer to transmit
len – Length of valid data in buffer. Remainder
of buffer padded to actual HID buffer length
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 94
Read Report
bool USBHIDReadReport (buffer);
Buffer – Returned data
Non-blocking function
returns true if data received within 1
second.
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 95
IsConnected
bool USBHIDIsConnected();
Checks to see if the VID & PID set by
USBHIDClassInit has been enumerated.
OS inquiry only. Does NOT communicate
with device.
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 96
PC Application Calls
Definitions to unmanaged code:
using namespace System::Runtime::InteropServices;
Connect to device:
OS calls Create file to get handles for read and write
Load Buffer to write
WriteFile
(handle, buffer, length, bytes written, overlapped)
ReadFile
(handle, buffer, length, bytes read, overlapped)
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 97
Bridge to Unmanaged
using namespace System::Runtime::InteropServices;
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 98
Building a Custom Class Thermometer using WinUSB
Outline
- Custom Class Thermometer Using WinUSB -
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 100
Vendor Class
Firmware Structure
main()
USB Interrupt
Context ProcessIO()
You edit in
USBDeviceTasks() main.c/user.c
Synchronous model
Accepts commands from host
Returns results
Waits for next command
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 101
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)
Checks to see if the In or Out handle is busy
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 102
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
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 103
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_EP_SIZE);
}
}
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 104
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)
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 105
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;
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 106
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
0x0000, // Device release number in BCD format
0x01, // Manufacturer string index
0x02, // Product string index
0x00, // Device serial number string index
0x01 // Number of possible configurations
};
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 107
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
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 108
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)
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 110
WinUSB Architecture
No need to write
your own driver
Application WinUSB
FULL speed DLL
User mode
Vista WinUSB.SYS
Microsoft
Existing
Component
Vendor
One .inf file Component
Microsoft
USB Stack New
Component
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 111
WinUSB features
WinUSB supports:
Device I/O control requests
Bulk, control, and interrupt transfers
Selective suspend
Remote wake
No isochronous transfers!
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 112
WinUSB APIs
winusb.dll exposes user mode client
routines*:
WinUsb_Initialize
WinUsb_WritePipe
WinUsb_ReadPipe
WinUsb_QueryInterfaceSettings
WinUsb_QueryDeviceInformation
WinUSB_Free
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 113
WinUsb_Initialize
Retrieves a handle for the interface that is associated with the
indicated device.
BOOL WinUsb_Initialize (deviceHandle , interfaceHandle);
deviceHandle
The handle to the device that CreateFile created
interfaceHandle
The interface to the Handle that WinUSB_Initialize returns
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 114
WinUsb_WritePipe
The WinUsb_WritePipe function writes data to a pipe.
BOOL WinUsb_WritePipe (interfaceHandle
,pipeID,Buffer,BufferLength, BytesTransferred, Overlapped);
interfaceHandle
The interface to the Handle that WinUSB_Initialize returns.
pipeID
An 8-bit value that consists of a 7-bit address and a direction bit.
Buffer
A caller-allocated buffer that contains the data to write.
BufferLength
The number of bytes to write.
BytesTransferred
A pointer to a ULONG variable that receives the actual number of
bytes that were written to the pipe.
Overlapped
An optional pointer to an OVERLAPPED structure.
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 115
WinUsb_ReadPipe
The WinUsb_ReadPipe function reads data from a pipe.
BOOL WinUsb_ReadPipe (interfaceHandle
,pipeID,Buffer,BufferLength, BytesTransferred, Overlapped);
interfaceHandle
The interface to the Handle that WinUSB_Initialize returns.
pipeID
An 8-bit value that consists of a 7-bit address and a direction bit.
Buffer
A caller-allocated buffer that contains the data to read.
BufferLength
The number of bytes to read.
BytesTransferred
A pointer to a ULONG variable that receives the actual number of bytes that
were copied into Buffer .
Overlapped
An optional pointer to an OVERLAPPED structure.
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 116
WinUsb_QueryInterfaceSettings
Returns the interface descriptor for the specified alternate interface settings
for a particular interface handle.
BOOL WinUsb_WritePipe (interfaceHandle,
AlternateSettingNumber,
UsbAltInterfaceDescriptor);
interfaceHandle
The interface to the Handle that WinUSB_Initialize returns.
AlternateSettingNumber
A value that indicates which alternate settings to return. A value of 0
indicates the first alternate setting, a value of 1 indicates the second
alternate setting, and so on.
UsbAltInterfaceDescriptor
A pointer to a caller-allocated USB_INTERFACE_DESCRIPTOR
structure that contains information about the interface that
AlternateSettingNumber specified.
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 117
WinUsb_QueryDeviceInformation
Returns information about the physical device that is associated with a
WinUSB .
BOOL WinUsb_QueryDeviceInformation (interfaceHandle,
InformationType, BufferLength, Buffer);
interfaceHandle
The interface to the Handle that WinUSB_Initialize returns.
• InformationType
A value that specifies which interface information value to
retrieve.On input, InformationType must have the following value:
DEVICE_SPEED (0x01).
On output, InformationType has one of the following values:
LowSpeed (0x01), FullSpeed (0x02), or HighSpeed (0x03).
• BufferLength
• The maximum number of bytes to read.
• Buffer
• A caller-allocated buffer that receives the requested value.
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 118
WinUsb_Free
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 119
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
http://connect.microsoft.com
See Appendix D for detailed instructions
MSDN Subscriber Download
http://msdn.microsoft.com/en-us/subscriptions/de
fault.aspx
Default folder:
C:\WinDDK\buildnumber
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 121
How to Build a WinUSB Application
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 122
How to Build a WinUSB Application
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 123
How to Build a WinUSB Application
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 124
How to Build a WinUSB Application
[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);
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 125
WinUSB – Using the APIs
4-Step Procedure:
1. Use the GUID + VID_PID to get the device path
2. Use the device path to get a handle to the device
3. Use the device handle to initialize WinUSB and
receive an interface handle
4. Use the interface handle to communicate with the
endpoints
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 126
WinUSB - Sample
GetDevicePath ((GUID) & GUID_DEVICE, // GUID declared in .inf
1 devicePath, // pointer to device path
sizeof(DeviceName)); // size of device path
deviceHandle = CreateFile (devicePath, ………);// obtain the handle
2 WinUsb_Initialize(deviceHandle, &interfaceHandle);
// pass the deviceHandle and you get the Interface Handle
3
WinUSB_WritePipe( interfaceHandle,
0x01, // endpoint address for bulk out
output, // output buffer
4 sizeof ( output ), // output buffer length
&transferredBytes, // bytes transferred
NULL); // optional OVERLAPPED structure
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 127
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 co-
installers)
.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 already comes with the .dll & .sys - only requires the .inf
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 128
Sample *.inf
A sample WinUSB .inf file is provided
C:\RTC\COM3201\Lab2\Host\Driver and
inf\MCHPWinUSBDevice_v2.inf
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 129
.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,"{58D07210-
27C1-11DD-BD0B-0800200C9a66}"
GUID must be identical with the one declared in the PC
Host Application
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 130
.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"
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 131
GUIDs
GUID
A random number
Stands for Globally Unique Identifier
2128 or 3.8*1038 possible combinations
Every ID is unique
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 133
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/
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 134
Lab 2. Custom Class Thermometer Using WinUSB
Lab 2
Custom Class Thermometer Using WinUSB
Modify the default WinUSB demo firmware to
read TC72 temperature data
In the PC Host App, add the function to create
a WinUSB handle
Add the function to initialize WinUSB
Communicate with endpoints
Use the Beagle 12 to look at the packets (refer
to Appendix C)
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 136
WinUSB - Conclusion
WinUSB allows full-speed USB communication
No custom driver needed. Create an *.inf and
you have your own driver.
Works with XP and Vista
Reference:
C:\RTC\COM3201\Users Guides and Data
Sheets\WinUsb_HowTo.pdf
WinUSB User‐Mode Client Support Routines
http://go.microsoft.com/fwlink/?LinkId=98300
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 137
Summary/Resources
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 144
Summary
Today we covered:
The benefits/limitations of the HID, Custom
and Mass Storage USB device classes for
generic data transfer
How to use the Microchip USB Framework in
your own project
Connection Detection
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 145
Additional Resources
Books
“USB Complete, 4/E” – Jan Axelson
“Serial Port Complete, 2/E” – Jan Axelson
“Windows System Programming, 3/E” – Johnson Hart
“Microsoft Windows Internals, 4/E” – Mark Russinovich
Weblinks
www.microchip.com/usb
www.usb.org (USB Spec, class definitions)
www.lvr.com (USB Examples)
www.beyondlogic.org/usbnutshell/usb1.htm (Tutorial)
Forums
www.usb.org/phpbb/
forum.microchip.com
App Notes
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 146
Trademarks
The Microchip name and logo, the Microchip logo, Accuron, dsPIC, KeeLoq,
KeeLoq logo, MPLAB, PIC, PICmicro, PICSTART, PRO MATE, rfPIC and
SmartShunt are registered trademarks of Microchip Technology Incorporated in
the U.S.A. and other countries.
FilterLab, Linear Active Thermistor, MXDEV, MXLAB, SEEVAL, SmartSensor
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, CodeGuard, dsPICDEM,
dsPICDEM.net, dsPICworks, dsSPEAK, ECAN, ECONOMONITOR, FanSense,
In‑Circuit Serial Programming, ICSP, ICEPIC, Mindi, MiWi, MPASM, MPLAB
Certified logo, MPLIB, MPLINK, mTouch, PICkit, PICDEM, PICDEM.net, PICtail,
PIC32 logo, PowerCal, PowerInfo, PowerMate, PowerTool, REAL ICE, rfLAB,
Select Mode, Total Endurance, UNI/O, 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.
© 2008, Microchip Technology Incorporated. All Rights Reserved.
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 147