100% found this document useful (2 votes)
371 views141 pages

USB Made Easy

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
371 views141 pages

USB Made Easy

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 141

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

Introduction to Full-Speed USB


Introduction to Microchip’s USB
Offerings
Part 3:
Using the Microchip CDC Class Device
Framework (RS-232 Replacement)

© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 3
USB Fundamentals
Universal Serial Bus

Extend the functionality of


your computer!

Data Analysis,
Data Logging,
Firmware Updates,
Diagnostics,
Embedded Applications!

• Auto detection & configuration (Plug&Play)


• Easy expansion using hubs
Serial
• Bus power Parallel
• Data CRC protected, bad packets resent PS/2
• Three speeds:
Low- 1.5, Full- 12, High- 480 Megabits / second

© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 5
USB Basics
USB is a “Single Master + Multiple Slaves” polled bus

USB Host Controller (Master)


and Root Hub

Mouse Printer Speakers


Start Of Frame Mouse Packets Speakers Packets Printer Packets

Frame Frame Frame


© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 6
USB Host
Manages and controls the Bus
Initiates all Transactions
Automatically detects all Device insertions and
extractions
Enumerates all Devices connected and matches
them with drivers

© 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

PC Host PDA OTG Host PDA OTG Host

PDA OTG Device Thumb Drive PDA OTG Device

© 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 2 Keyboard Speaker Hub

Tier 3 Logic Hub: Max Chaining = 5


Analyzer
Hub

Tier 4 Printer 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

VBUS VBUS ~ 5.0 V


D+ D+
~ 3.3 V
D- D-
GND GND

Half Duplex with NRZI Data Encoding


Bus Power to each device:
4.40-5.25V Must use external
Guaranteed 100 mA power if more is
500 mA maximum through negotiation required

© 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 -

Objective: Define a smaller footprint, USB 2.0


compliant connector for very small devices (i.e.
cell phones)
Plugs and Receptacles
Micro-B plug and receptacle
Allowed on OTG and non-OTG products

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

USB Device-Specific Pipe(s) IN (Endpoint x) HID TX/RX Functions


(Human Interface Device) (MCHPFSUSB FW)
OUT (Endpoint x)

These settings are


IN (Endpoint 0) represented by a
USB System Software Device Descriptor
(default control pipes) OUT (Endpoint 0) Table, stored in
firmware.

© 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
®

USB framed data RAM


Endpoint 1 OUT LED

USB framed data RAM


Endpoint 1 IN “Caps-Lock”

 Maximum number of endpoints per device specified by USB


specification:
 16 OUT endpoints + 16 IN endpoints = 32 endpoints
 PIC18F87J50, PIC18F4550, PIC24F, PIC32MX supports up to 32
endpoints
 PIC18F14K50 supports up to 16 endpoints
 EP0 = Default Communication Pipe
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 16
USB Device Framework
- Software View of Hardware -
Host System Peripheral Device
Pipe Bundle
Function Layer

Function Layer
Client Software Function
Client Software Interface
Client Software

Buffers Interface-specific

USB System USB Logical

Layer
USB Device
USB Device

Software Default Pipe (EP0) Device


Endpoint
Layer

zero

Transfers Data per Endpoint

Bus Interface
Bus Interface

USB Bus Interface USB Bus Interface

Layer
Layer

Host Transactions USB Cable


SIE SIE
Controller

Physical Communication Path


Logical Communication Path (“Pipe”)
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 17
Sending/Receiving
on the PC
Only High Level Access
Four Basic Function Types
Example:
Microchip General Purpose USB Device Driver
MPUSBOpen(…);
MPUSBRead(…);
MPUSBWrite(…);
MPUSBClose(…);
Microsoft® WinUSB driver
WinUSB_Initialize(…);
WinUsb_ReadPipe(…);
WinUsb_WritePipe(…);
WinUSB_Free(…);

© 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);

You are not directly reading/writing


to the peripheral SFRs anymore!

© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 19
Transactions
An Endpoint is a Buffer

Data Bucket

OUT Transaction RAM


Endpoint 1 OUT LED

IN Transaction RAM
Endpoint 1 IN “Caps-Lock”

 Maximum number of endpoints per device specified by


USB specification:
 16 OUT endpoints + 16 IN endpoints = 32 endpoints
 PIC18F87J50, PIC18F4550 supports up to 32 endpoints
 EP0 = Default Communication Pipe

© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 21
USB Transaction

USB Transaction

Token Packet

SETUP and OUT token types


inform the target device that Specifies:
the host wants to send data. • Target device address
• Endpoint number
• Direction of the data transfer
IN token type informs the
target device that the host
wants to fetch data.

© 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)

SIE Sends NAK


Packet

© 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 -

Control-> Signal and Interrupt ->


setup Guaranteed and timely

Isochronous -> Timely but Bulk -> Guaranteed


may be corrupted (or missed) but can be untimely
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 29
Summary - Data Transfer Types
Transfer/ Polling Interval % Reserved Max. # Data Data
Endpoint BW/Frame for Bytes/Frame/Endpoint Integrity
Type all transfers of (Max# transactions per frame
this type @ Max Ep Size)*
Interrupt Fixed, Periodic 90 64 (1 x 64) Yes

Isochronous Fixed, Periodic 90 1023 (1 x 1023) No

Bulk Variable, Uses 0 1216 (19 x 64) Yes


Free Bandwidth

Control Variable 10 832 (13 x 64) Yes

*Assumes transfers use maximum packet sizes allowed per Ep type


© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 30
Theoretical Maximum Transfer
Rate Per Endpoint

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

Mouse Printer Speaker


Control Control Control
+ + +
Interrupt Bulk Isochronous

© 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 -

Features HID CDC MCHPUSB WinUSB LibUSB


Driver support Yes Need .inf No Need .inf No
built into Windows
64-bit PC Support Yes Yes Yes Yes Yes

XP Ready Yes Yes Yes Yes Yes


Vista Ready Yes Yes Yes Yes 32 bit

Transfer Types for user’s data


Control No No Yes Yes Yes
Interrupt Yes No Yes Yes Yes
Isochronous No No Yes No Yes
Bulk No Yes Yes Yes Yes
Max Speed 64 KB/s ~80 kB/s ~1.0 MB/s ~1.0 MB/s ~1.0 MB/s

© 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

Cable Get Device


Connecte Descriptor
d SUSPENDED

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

Dual Port/Access RAM

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

Endpoint Endpoint Endpoint Endpoint

 Descriptors are typically stored in non-volatile/Flash memory

© 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

Interface 0 Interface #0: HID Class, Num.


Other String Endpoints
Go USB!
Endpoint 1 IN, Interrupt Transfer Type,
Endpoint
64-byte buffer, Poll every 3 ms
Unicode
Characters

© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 43
Power Planning
- Architecture -

“Low Power” bus-powered function


Draws up to 100 mA (1 ‘unit load’) from the bus

Function Controller +
Function

© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 44
Power Planning
- Architecture -

“High Power” bus-powered function


Draws 100-500 mA from the bus
Must be able to enumerate at low power (100 mA)
Device requests bMaxPower
Host enables configuration with appropriate
Set_Configuration request

© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 45
Power Planning
- Architecture -

“Self Powered” device


Can optionally draw up to 100 mA from the bus
(if unsuspended) + as much as is available from
its own supply

© 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

For USB Compliance Testing:


Download “Peripheral Checklist”
www.usb.org/developers/compliance/peripheral_low
Use certified USB receptacle and cable for testing
Know the TID (Test ID) of your components
Find USB PIC® MCUs TID number on www.microchip.com/usb
For USB Compliance certification:
Independent Test Labs (see www.usb.org for a list)

It’s a good idea to take a look at the


checklist before starting your design!
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 50
Quiz!

Maximum number of devices USB


can support?
Number of pins in a standard USB
connector?
What is FS USB data rate?
Which direction is Data-IN?
USB data transfer types?
What is USB Enumeration?
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 51
Microchip Offerings
Microchip’s USB PIC® MCUs
Support USB 2.0 Low and Full Speed
On Chip USB/OTG Transceivers, Voltage Regulator and pull
up resistors
On Chip PLL for USB Clock
USB Dual Access RAM
Easy hardware hookup from PIC MCU to USB port

PIC USB Microcontroller

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

8, 16, and 32 bit Architecture MCUs offered


20 - 100 Pin devices
8 Kb up to 512 Kb Flash Program Memory
512 bytes to 32 Kb Data Ram
Voltage of Operation:1.8V to 5.5V
Wide Range of Peripherals for Real World
Applications
A/D converters, Comparators
SPI, I2C™, UART
PWMs, Timers and I/O lines

© 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

PIC18F2550 PIC18F4550 PIC18F65J50 PIC18F85J50


PIC18F2553 PIC18F4553
24K/2K
24K/2K 24K/2K
24K/2K
24KB

PIC18F2455 PIC18F4455
PIC18F2458 PIC18F4458
16K/768
16K/768 16K/768
16K/768 16K/768
16K/768
8KB 16KB

PIC18F14K50 PIC18F2450 PIC18F4450


8K/512
8K/512

PIC18F13K50

20 Pin 28 Pin 48 Pin 64 Pin 80 Pin


*Source: Vendor Published Specifications
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 55
USB OTG Product Offerings
512KB

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

PIC24FJ192GB106 PIC24FJ192GB108 PIC24FJ192GB110

128K/16K 128K/16K 128K/16K 128K/32K


128K/32K
128K/16K 128K/16K 128K/16K 4ch
4chDMA
DMA++USB
USBDMA
DMA
64KB 128KB

PIC32MX440F128L
PIC24FJ128GB106 PIC24FJ128GB108 PIC24FJ128GB110

64K/16K
64K/16K 64K/16K
64K/16K 64K/16K
64K/16K

PIC24FJ64GB106 PIC24FJ64GB108 PIC24FJ64GB110

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

Designed to be main MCU in Peripheral Device Applications

© 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

20 MHz EC Divide by 5 96 MHz PLL Divide by 3

Divide by 2
Accept 4 MHz Input Only
32 MHz :
8 MIPs
PIC®
SIE MCU
Core

SIE Clock = 48 MHz : Full-Speed Mode

© 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

Buy USB Development Boards and Kits from microchipDIRECT


www.microchipdirect.com
Detailed Product Information at:
www.microchip.com/pic32
www.microchip.com/pic24
www.microchip.com/pic18
© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 67
Demo
- Capturing a Transaction -

To read the potentiometer value, the PDFSUSB GUI


application continually sends command “0x37”
Device Returns Command Code + 10-bit
Potentiometer ADC value:
<0x37><ADRESL><ADRESH>

© 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) -

Reset main() InitializeSystem()


You Edit
UserInit()

main()
Cooperative
Multitasking!!
USBDeviceTasks() usb_device.c
No blocking
functions.

Use state ProcessIO()


machine. You edit in
main.c/user.c

© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 75
Cooperative Multitasking

Main Loop
State Machine

Task A.1 - 200 us

Task A Task A.2 - 400 us

900 us Task A.3 - 300 us

Max Loop Time


1000 us V.S. 500 us
Task B - 100 us

© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 76
MCHPFSUSB v2.x
- Device Side Program Flow (INTERRUPT) -

Reset main() InitializeSystem()


You Edit
UserInit()

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 -

The HID Device Class


The HID Report Descriptor
Using the HID Function Driver APIs
MCHPHID DLL Implementation
HID Summary – Benefits/Drawbacks

© 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

64 bytes per frame


x 1000 frames/second
64,000 bytes/second

~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

bool USBHIDClassInit (VID, PID,


len);
VID – Vendor ID assigned by USBIF
PID – Product ID assigned by VID holder
Len – Buffer length (normally 64)

© 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;

[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 98
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
GUIDs
Lab 2 – Custom Class Thermometer using
WinUSB
WinUSB Conclusion

© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 100
Vendor Class
Firmware Structure

Reset main() InitializeSystem()


You Edit
UserInit()

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

_BULK, _CTRL or _INT (Interrupt)

USBGEN_EP_SIZE defined in usb_config.h


#define USBGEN_EP_SIZE 64

© 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

Works with XP and Kernel mode

Vista WinUSB.SYS
Microsoft
Existing
Component
Vendor
One .inf file Component

Microsoft
USB Stack New
Component

USB Device Device


(PIC18F14K50)

© 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

*See http://go.microsoft.com/fwlink/?linkid=98300 for the complete list of


routines.

© 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

Frees all of the resources that WinUsb_Initialize allocated.


BOOL WinUsb_Free (interfaceHandle);
The interface to the Handle that WinUSB_Initialize returns.

All BOOL functions return TRUE if the operation succeeds.


Otherwise, this routine returns FALSE, and the caller can retrieve the logged
error by calling GetLastError().

© 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

1. Add WDK include paths to MSVC++


Click ToolsOptions+Projects and
SolutionsVC++ DirectoriesShow
Directories for: "Include files"
Then click the Folder icon (new line) and then the "..."
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

© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 122
How to Build a WinUSB Application

2. Add WDK library paths for winusb.lib to


MSVC++
Click ToolsOptions+Projects and
SolutionsVC++ DirectoriesShow
Directories for: “Library files"
Then click the Folder icon (new line) and then the "..."
button and add these directories as required:
XP:
C:\WinDDK\7600.16385.0\lib\wxp\i386
Vista:
C:\WinDDK\7600.16385.0\lib\wlh\i386
C:\WinDDK\7600.16385.0\lib\wlh\ia64
C:\WinDDK\7600.16385.0\lib\wlh\amd64

© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 123
How to Build a WinUSB Application

3. Include the header files


#include <windows.h>
Provides definitions for common Win32 types
#include <setupapi.h>
Provides definitions for SetupDixxx() functions we use to
find our device
#include <winusb.h>
Provides definitions for WinUSB APIs

© 2008 Microchip Technology Incorporated. All Rights Reserved. Insert Class Code Here Slide 124
How to Build a WinUSB Application

4. (for run-time linking to DLLs in .NET)

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);

© 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

You can modify it


Put your VID and PID
Device description
Disk name

© 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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy