You are on page 1of 100

1544 USB5

USB Made Easy with VB.Net

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

Class Objective
When you finish this class you will be able to:

Write a complete USB comm application in Windows


from scratch

Single/Multi Point Acquisition


Continuous Data Acquisition
USB Descriptor Acquisition
Retrieval of Mfg SN, Manufacturer and Product Strings

Trap and use WM_DEVICECHANGE event

Fully customize the VB.Net USB Communicator


application

Add commands to the Message Pump in VB.Net and


the Embedded software

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

Class Objective
When you finish this class you will be able to:
Add a professional look and feel to the USB
system
Understand some of the ways to improve data
rates

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

Agenda

Principles of Bidirectional USB Communication


VB.Net USB Class and Sample Application

Function explanations
Single and multiple point acquisitions
Continuous data acquisition
USB descriptor acquisition

Retrieving Device Manufacturers Serial Number


Retrieving Device Product String
Retrieving Device Manufacturers String

WM_DEVICECHANGE event (Device Enumeration)


Tracking by Windows Instance
Tracking by Serial Number

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

Class Agenda

Customizing the Application

Adding commands to message pump


Adding commands to embedded software

Improving Data Rates

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

Principles of
Bidirectional USB
Communication

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

USB Transaction
USB Transaction
Token Packet

SETUP and OUT token types


inform the target device that the
host wants to send data.

Specifies:
Target device address
Endpoint number
Direction of the data transfer

IN token type informs the target


device that the host wants to fetch
data.

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

USB Transaction - IN
USB Transaction
IN Token Packet

Data Packet

The target device returns data equal


to or less than the endpoint size
specified in the descriptor.
A special signaling is used to indicate
the End-of-Packet (EOP).
2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

USB Transaction - IN
USB Transaction
IN Token Packet

Data Packet

Handshake Packet

Acknowledge - ACK

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

USB Transactions - OUT &


SETUP
USB Transaction
OUT or SETUP Token
Packet

Data Packet

Handshake Packet

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

10

USB Transaction Isochronous Transfer


USB Transaction
Token Packet

Data Packet

Isochronous transfer
does not guarantee data
integrity. Therefore,
there is no handshake
packet.

2011 Microchip Technology Incorporated. All Rights Reserved.

Handshake Packet

1544 USB5

Slide

11

Windows Side of USB

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

12

Windows Side
Host PC

Peripheral Device

Non USB Format

USB Device Driver


Non USB Format

USB System Software

Device Specific Comm

Default
Pipe

USB Data Frames

USB Adapter/Controller

Physical Device

Logical Device
Hardware

Hardware

Driver
Specific
Pipes

Embedded System

System Software

User Code

USB Data Frames

Cable

Bus Interface

Physical Connection
Logical Connection
2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

13

Windows USB
Send/Receive Data Packet
Start

Find Device

Open Pipe

Write/Read Data

Close Pipe

SetupDiGetClassDevs

SetupDiEnumDeviceInterfaces

SetupDiGetDeviceInterfaceDetail

Retrieve Device
Information Set for all
devices of specified Class
(if device is present)

Retrieve information about device


interface

Get size of symbolic link

MPUSBIsVidPidEqual

SetupDiGetDeviceInterfaceDetail

Check for a valid VID & PID

Get size of symbolic link name

SetupDiDestroyDeviceInfoList
Clean up

2011 Microchip Technology Incorporated. All Rights Reserved.

Return Device Path


1544 USB5

Slide

14

Windows USB
Send/Receive Data Packet
Start

Find Device

Open Pipe

Write/Read Data

Close Pipe

In/Out Pipe is open using


CreateFile Windows API.

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

15

Windows USB
Send/Receive Data Packet
Start

Find Device

Open Pipe

Write/Read Data

Close Pipe

Standard File IO Windows


APIs are used for
communication:
WriteFile and ReadFile
Note: ReadFile
automatically generates the
IN Token Packet.

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

16

Windows USB
Send/Receive Data Packet
Start

Find Device

Open Pipe

Write/Read Data

Close Pipe

Clean up: The


handle to the Pipe is
closed using
CloseHandle API.

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

17

HID vs Custom
Device?

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

18

HID vs Custom Device


Features
Driver Needed
Windows APIs
Custom APIs
Driver Customization

Custom Device
Yes
Yes
Yes
Yes

HID
No
Yes
No
No

Yes
Yes
Yes
Yes
1.5 MB/s

Yes
Yes
No
No
64 kB/s

Transfer Types
Control
Interrupt

Bulk
Isochronous
Max Speed
2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

19

Disadvantages of CDC

CDC Overview

Using COM port interface


Any and every app can communicate
to COM port
COM port numbers change

No customization

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

20

Building a Custom
USB System with
VB.Net

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

21

Windows Programming
USB

Communicator
Overview
Written in VB.Net
Class-Based APP
Multithreaded

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

22

Windows Side
Host PC

Peripheral Device

Non USB Format

USB Device Driver


Non USB Format

USB System Software

Device-Specific Comm

Default
Pipe

USB Data Frames

USB Adapter/Controller

Physical Device

Logical Device
Hardware

Hardware

Driver
Specific
Pipes

Embedded System

System Software

User Code

USB Data Frames

Cable

Bus Interface

Physical Connection
Logical Connection
Ref: http://www.microsoft.com/technet/prodtechnol/wce/support/usbce.mspx
2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

23

Windows Side

User Code

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

24

Windows Side

USB Communicator App

User Code

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

25

Windows Side

USB Communicator App


Data

MPUSBClass
User Code

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

26

Windows Side

USB Communicator App


Data

MPUSBClass
User Code
Data
Data

MPUSBAPI.DLL

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

27

Windows Side
Graphical User Interface
Data Processing
Callback Processing
Responses to Windows Events
WM_DEVICECHANGE
All Decision Making

USB Communicator App


Data

MPUSBClass
User Code
Data
Data

MPUSBAPI.DLL
2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

28

Windows Side
Bridge between User APP and
MPUSBAPI.DLL
Easy to use Properties/Methods/Functions
Friendly interface to USB
Functions, such as USB Message Pump,
SendMessage, DeviceIndex, TargetVID_PID
and others.
USB Communicator App
Data

MPUSBClass
User Code
Data
Data

MPUSBAPI.DLL
2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

29

Windows Side
Bridge between User APP and Microchip USB
Driver
Low Level Functions:
USB Open/Close Pipe
Low Level Reads/Writes
GetUSBDescriptors

USB Communicator App


Data

MPUSBClass
User Code
Data
Data

MPUSBAPI.DLL
2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

30

Question

Can User App communicate directly with the driver?

Yes
What is the advantage of the APP/Class/DLL interface?

Portability

Flexibility

Code Simplicity:
1. Dim USBDevice As MPUSBClass
2. USBDevice = New MPUSBClass(TxtData, dispDelegate)
3. USBDevice.TargetVID_PID="vid_04d8&pid_000c
4. USBDevice.TargetEP=" \MCHP_EP1
5. USBDevice. DeviceSerialNumber=1033
6. USBDevice.USBListen=True
7. USBDevice.SendCommand(READ_DATA)
Device with SN 1033 will automatically be tracked on the USB bus (even
if other devices with the same VID/PID are plugged into the system.
The communication is only between the Host and this device.
Sub ProcessData is automatically called by the class when USB data
arrives.

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

31

Windows Side

USB Communicator App


Data

MPUSBClass
User Code
Data
Data

MPUSBAPI.DLL

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

32

MPUSBClass Top Level


USB Communicator App
Data

User
Code

MPUSBClass

Shared Members

Properties

Events/Delegates

DeviceCount

TargetVID_PID

DevicesAddedRemoved

EnumDevices

TargetEP

DataArrivedCallBack

GetProductString

DeviceSerialNumber

GetMfgString

DeviceInstance
USBListen

Methods
New
Dispose
SendCommand
ReceivePacket

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

33

MPUSBClass Top Level


USB Communicator App
Data

User
Code

MPUSBClass

Shared Members

Properties

Events/Delegates

DeviceCount

TargetVID_PID

DevicesAddedRemoved

EnumDevices

TargetEP

DataArrivedCallBack

GetProductString

DeviceSerialNumber

GetMfgString

DeviceInstance
USBListen

Methods
New
Dispose
SendCommand
ReceivePacket

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

34

Shared Functions

Why use shared functions?


Used to communicate to any/all
devices on USB bus
Perform enumeration, acquire USB
descriptors, etc.
Shared between all instances of
the class

Not tied to any one instance

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

35

Shared Functions
Shared Members
DeviceCount

DeviceCount Function (Integer)


Counts devices on USB Bus.
Input:
Return:

Vid_Pid - String
Returns a count of devices on USB bus that have
matching VID/PID

EnumDevices
GetProductString
GetMfgString
GetSerialNumber

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

36

Shared Functions
Shared Members
DeviceCount
EnumDevices
GetProductString
GetMfgString

EnumDevices Function (Boolean)


Enumerates devices on USB Bus.
Inputs:
Outputs:
Return:

Vid_Pid - String
EndPoint - String
Array of strings, each including: Product String +
SW Ver + Module Instance + SN
Returns True if success

GetSerialNumber

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

37

Shared Functions
Shared Members
DeviceCount
EnumDevices
GetProductString
GetMfgString
GetSerialNumber

GetProductString Function (String)


Retrieves Product String from the device.
Inputs:
Return:

Vid_Pid - String
Device Instance - Integer
Returns Device Product String

Note: This function is used internally, but can be used from


main application.

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

38

Shared Functions
Shared Members
DeviceCount
EnumDevices

GetMfgString Function (String)


Retrieves Manufacturer String from the device.

GetProductString

Inputs:

GetMfgString

Return:

GetSerialNumber

2011 Microchip Technology Incorporated. All Rights Reserved.

Vid_Pid - String
Device Instance - Integer
Returns Manufacture String

Note: This function is used internally, but can be used from


main application.

1544 USB5

Slide

39

Shared Functions
Shared Members
DeviceCount
EnumDevices
GetProductString
GetMfgString
GetSerialNumber

2011 Microchip Technology Incorporated. All Rights Reserved.

GetSerialNumber Function (Integer)


Retrieves Serial Number from the device.
Inputs:
Return:

Vid_Pid - String
Device Instance - Integer
Returns Device Serial Number

Note: This function is used internally, but can be used from


main application.

1544 USB5

Slide

40

Shared Functions
Shared Members
DeviceCount
EnumDevices
GetProductString
GetMfgString
GetSerialNumber

Additional Functions:
QueryDevice Opens In/Out pipe, sends a packet and receives
one back.
SendReceivePacket Sends/Receives a packet through open
In/Out pipes.
GetUSBDescriptor Gets USB Descriptors.
IndexFromSN Finds device with matching SN and returns its
Index.

QueryDevice
SendReceivePacket

GetUSBDescriptor
IndexFromSN
2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

41

MPUSBClass Top Level


USB Communicator App
Data

User
Code

MPUSBClass

Shared Members

Properties

Events/Delegates

DeviceCount

TargetVID_PID

DevicesAddedRemoved

EnumDevices

TargetEP

DataArrivedCallBack

GetProductString

DeviceSerialNumber

GetMfgString

DeviceInstance
USBListen

Methods
New
Dispose
SendCommand
ReceivePacket

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

42

Properties
TargetVID_PID Property (String)
Sets/Returns the VID_PID for the target device.

Properties

Default: vid_04d8&pid_000c

TargetVID_PID

TargetEP
DeviceSerialNumber
DeviceInstance
USBListen

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

43

Properties
Properties

TargetEP Property (String)


Sets/Returns the Target Endpoint.

TargetVID_PID
Default: \MCHP_EP1

TargetEP
DeviceSerialNumber
DeviceInstance
USBListen

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

44

Properties
Properties
TargetVID_PID

TargetEP
DeviceSerialNumber
DeviceInstance
USBListen

2011 Microchip Technology Incorporated. All Rights Reserved.

DeviceSerialNumber Property (Integer)


Sets/Returns the Serial Number of the target device (the
device that the MPUSBClass will track or is tracking).
Note: If DeviceSerialNumber property is set by the
user code, the DeviceInstance property will be updated
automatically to reflect the index of the target device
with a matching serial number. DeviceInstance will be
set to -1 if no device is found.

1544 USB5

Slide

45

Properties
Properties
TargetVID_PID

TargetEP
DeviceSerialNumber
DeviceInstance
USBListen

2011 Microchip Technology Incorporated. All Rights Reserved.

DeviceInstance Property (Integer)


Sets/Returns the DeviceInstance of the target device.

Returned value of -1 means no device is found.


Note: If DeviceInstance property is set by the user
code, the DeviceSerialNumber property will be updated
automatically to reflect the SN of the target (check SN
for -1 value to see if device is connected).

1544 USB5

Slide

46

Properties
Properties
TargetVID_PID

TargetEP
DeviceSerialNumber
DeviceInstance
USBListen

USBListen Property (Boolean)


Sets/Returns the state of the USB Message Pump.
Setting USBListen = True, starts the USB Message
Pump Thread, setting USBListen = False stops it
Note: USBListen will wait until the USB Message
Pump thread exits before allowing the program to
continue execution.

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

47

MPUSBClass Top Level


USB Communicator App
Data

User
Code

MPUSBClass

Shared Members

Properties

Events/Delegates

DeviceCount

TargetVID_PID

DevicesAddedRemoved

EnumDevices

TargetEP

DataArrivedCallBack

GetProductString

DeviceSerialNumber

GetMfgString

DeviceInstance
USBListen

Methods
New
Dispose
SendCommand
ReceivePacket

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

48

Events
DeviceAddedRemoved Event
Inputs:
Outputs:

Events/Delegates

None
None

Raised when devices have been added to or removed


from the USB bus (windows issued the
WM_DEVICECHANGE message).

DevicesAddedRemoved
DataArrivedCallBack

DataArrivedCallBack Call Back Subroutine


Inputs:
Outputs:

None
ArrayData() - Array of Bytes containing the
Arrived Data

Invoked when USB Message Pump receives data from


the device.
Note: The DataArrivedCallBack is invoked in the same
thread as the control passed to the New() method upon
declaration of the class-inherent variable.
2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

49

MPUSBClass Top Level


USB Communicator App
Data

User
Code

MPUSBClass

Shared Members

Properties

Events/Delegates

DeviceCount

TargetVID_PID

DevicesAddedRemoved

EnumDevices

TargetEP

DataArrivedCallBack

GetProductString

DeviceSerialNumber

GetMfgString

DeviceInstance
USBListen

Methods
New
Dispose
SendCommand
ReceivePacket

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

50

Methods
Methods

New Method
Inputs:
UpdateControl - Control used to invoke the
DataArrivedCallBack function.

New
Dispose

DisplayDelegate - DataArrivedCallBack
Delegate. Invoked when new data has
arrived on USB bus.

SendCommand
ReceivePacket

2011 Microchip Technology Incorporated. All Rights Reserved.

Used to create a new MPUSBClass instance and assign


to a newly declared variable in the main application.

1544 USB5

Slide

51

Methods
Methods
New
Dispose
SendCommand
ReceivePacket

2011 Microchip Technology Incorporated. All Rights Reserved.

Dispose Method

Inputs:
Outputs:

None
None

Release all resources associated with a specific


MPUSBClass instance.

1544 USB5

Slide

52

Methods
Methods
New
Dispose
SendCommand

SendCommand
ReceivePacket

Inputs:
Outputs:

cmdToSend() - Data Byte Array


None

Returns 1 if successful, 0 if failed.

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

53

Methods
Methods
New
Dispose
SendCommand

ReceivePacket

ReceivePacket

Inputs:
Outputs:

None
cmdToReceive () - Data Byte Array

Returns 1 if successful, 0 if failed.

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

54

Methods
Methods
New
Dispose
SendCommand
ReceivePacket
USBListenServer
MsgArrived

Private Methods
(Accessible from within the MPUSBClass only)
USBListenServer - The USB Message Pump
MsgArrived - Used to Track WM_DEVICECHANGE
InitializeClass - Called by New Method
DisposeClass - Called by Dispose Method

InitializeClass
DisposeClass

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

55

MPUSBAPI.DLL

USB Communicator App


Data

MPUSBClass
User Code
Data
Data

MPUSBAPI.DLL

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

56

MPUSBAPI.DLL
MPUSBAPI.DLL
MPUSBGetDLLVersion

MPUSBGetDLLVersion
Input:

None

Output: 32-Bit Revision Level MMMMmmmm


Returns mpusbapi.dll revision levelvr.

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

57

MPUSBAPI.DLL
MPUSBAPI.DLL

MPUSBGetDeviceCount

MPUSBGetDLLVersion

Input:

MPUSBGetDeviceCount

Output: Returns the number of devices with


matching VID & PID.

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

VIDPID - String

Slide

58

MPUSBAPI.DLL
MPUSBAPI.DLL
MPUSBGetDLLVersion
MPUSBGetDeviceCount

MPUSBOpen

MPUSBOpen
Input:
Instance - Device Instance
pVID_PID - String
pEP - String
dwDir - Direction (Read/Write)
dwReserved - Future Use
Returns the handle to the Endpoint Pipe with
matching VID & PID.

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

59

MPUSBAPI.DLL
MPUSBAPI.DLL
MPUSBGetDLLVersion
MPUSBGetDeviceCount

MPUSBOpen
MPUSBRead

MPUSBRead
Input:
handle - Handle to Open Pipe
dwLen - Bytes to Read
dwMilliseconds - Time-out
Output: pData - Data Buffer
pLength - Data Read Length
Returns 0 if failed, 1 if success.

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

60

MPUSBAPI.DLL
MPUSBAPI.DLL
MPUSBGetDLLVersion
MPUSBGetDeviceCount

MPUSBOpen
MPUSBRead

MPUSBWrite
Input:
handle - Handle to Open Pipe
pData - Data Buffer
dwLen - Bytes to Write
dwMilliseconds - Time-out

MPUSBWrite

Output: pLength - Data Written Length


Returns 0 if failed, 1 if success.

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

61

MPUSBAPI.DLL
MPUSBAPI.DLL
MPUSBGetDLLVersion
MPUSBGetDeviceCount

MPUSBOpen
MPUSBRead

MPUSBClose
Input:
handle - Handle to Open Pipe

MPUSBWrite
Closes a given handle.
MPUSBClose

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

62

MPUSBAPI.DLL
MPUSBAPI.DLL
MPUSBGetDLLVersion
MPUSBGetDeviceCount

MPUSBOpen
MPUSBRead
MPUSBWrite
MPUSBClose
MPUSBGetDeviceDescriptor

MPUSBGetDeviceDescriptor
Input:
handle - Handle to Open Pipe
pDscParam - Pointer to
GET_DESCRIPTOR_PARAMETER

dscLen - Size of Data in pDscParam


dwLen - Size of Memory Allocated for
Output (expected returned data
size)
Output: pDevDsc - Pointer to Device Descriptor
Structure
pLength - Number of Bytes Write to
Device Descriptor Structure
Returns 0 if failed, 1 if success.

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

63

MPUSBAPI.DLL
MPUSBAPI.DLL

MPUSBReadInt
Input:
handle - Handle to Open Pipe
dwLen - Bytes to Read
dwMilliseconds - Time-out

MPUSBGetDLLVersion
MPUSBGetDeviceCount

MPUSBOpen
MPUSBRead
MPUSBWrite
MPUSBClose
MPUSBGetDeviceDescriptor

MPUSBReadInt

2011 Microchip Technology Incorporated. All Rights Reserved.

Output: pData - Data Buffer


pLength - Data Read Length
Returns 0 if failed, 1 if success.
Note: pEP has to be in \\MCHP_EPz_ASYNC
format. This option is only available for an IN
interrupt endpoint. A data pipe opened with the
_ASYNC keyword would buffer the data at the
interval specified in the endpoint descriptor up to
the maximum of 100 data sets. Any data received
after the driver buffer is full will be ignored. The
user application should call MPUSBReadInt() often
enough so that the maximum limit of 100 is never
reached.
1544 USB5

Slide

64

Getting Started with


USB and VB.Net

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

65

Single Point Acquisition

Program Requirements

Form with 1 Button and 1 Text Box

Button Text set to Read Pot


Form Text USB Reader 1

Upon Button Press:

Request Potentiometer Data


Check for Valid Packet Transmission

Convert and display Pot value (in kOhms)


Display Error if packets are not sent/received

Use "vid_04d8&pid_000c" and "\MCHP_EP1"

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

66

Windows USB
Single Point Acquisition

Start

Declare USBDevice as
MPUSBClass;
Initialize USBDevice (set
equal to New
MPUSBClass)

Wait For User


Input

Initialize: VID/PID, EP,


Instance

Display Data
2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Send/Receive
Packet
Slide

67

Single Point Acquisition


USB Communicator App
Data

User
Code

MPUSBClass

Shared Members

Properties

Events/Delegates

DeviceCount

TargetVID_PID

DevicesAddedRemoved

EnumDevices

TargetEP

DataArrivedCallBack

GetProductString

DeviceSerialNumber

GetMfgString

DeviceInstance
USBListen

Methods
New
Dispose
SendCommand
ReceivePacket

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

68

Single Point Acquisition

Variable Declarations

Array Declaration

Dim DataArray(0) as Byte


DataArray(0) =
MPUSBClass.USB_CMD_LIST.RD_TEMP

Class Declaration/Usage

Dim MyDev as MPUSBClass


MyDev = New MPUSBClass(TextBox1,AddressOf
DataArrived)

TextBox should already exist on the main form


Sub DataArrived(data() as byte)

MyDev.CustomProperty = Value
MyDev.SendInformation (DataArray)

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

69

Single Point Acquisition

Pot Value:

10-bit

LowByte is in Data(1)
HiByte is in Data(2)

Data Returned

Byte (0) = Requested command echoed back


Byte (163) = Data

Displaying Data in Ohms:


Label1.Text = Utils.toOhms(DataBytes)

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

70

Lab 1
Sequential Single
Point Acquisition
30 Minutes
2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

71

Sequential Single Point


Acquisition

Advantages/Disadvantages of Sequential
Send/Receive Packet?

Advantages

Easy to use
Easy to debug
Easy to understand

Disadvantages

Low Data Throughput

Pipes are opened and closed with every SendCommand


Pipes are opened and closed with every ReceivePacket

Suspends app while waiting for device response

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

72

Multithreaded Data
Acquisition

Program Requirements

Form with 1 Button and 1 Text Box

Button Text set to Read Temp


Form Text USB Reader 1

Upon Button Press:

Request Temperature Data


Check for Valid Packet Transmission

Convert and display Pot value (in kOhms)


Display Error if packets are not sent/received

Use "vid_04d8&pid_000c" and "\MCHP_EP1"

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

73

Windows USB
Multithreaded Data Acquisition

Start

Initialize Class;
Setup VID/PID,
Instance, EP

Send
Packet

Wait for User


Input

Display
Data

Process Data

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Start USB
Listener
USB Listener Thread

Slide

74

Multithreaded Data
Acquisition
USB Communicator App
Data

User
Code

MPUSBClass

Shared Members

Properties

Events/Delegates
DevicesAddedRemoved

DeviceCount

TargetVID_PID

EnumDevices

TargetEP

GetProductString
GetMfgString

DeviceSerialNumber

4
5

DeviceInstance
USBListen

DataArrivedCallBack

Methods
1

New

Dispose

SendCommand
ReceivePacket

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

75

Multithreaded Data
Acquisition

Helpful Hints

Class Declaration/Initialization

Dim MyDev as ExampleClass


In the code:

MyDev=New ExampleClass(Textbox1, AddressOf ProcessData)

Array Declaration

Use Form1_FormClosing

Subs

Use Form1_Load

Finalization

Dim DataArray(0) as MPUSBClass.USB_CMD_LIST


DataArray(0 )= MPUSBClass.USB_CMD_LIST.RD_TEMP

Initialization

Note, DataSub should already be declared as sub ProcessData (DataArray() as byte)

Sub ProcessData(DataArray() as Byte)

Data Returned

Byte (0) = Requested command echoed back


Byte (163) = Data

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

76

Lab 2
Multithreaded Data
Acquisition
30 Minutes
2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

77

Multiple Devices
Communication

What if:

There are multiple devices on USB bus


Device selection capability needed (User)
Data needs to be sent to a specific device

Solutions

Device Enumeration
Device Serial Number

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

78

Multiple Devices
Communication

Device Enumeration with MPUSBClass

MPUSBClass.DeviceCount Number of
devices with matching VID/PID on USB bus
MPUSBClass.EnumDevices Enumerates
devices, Outputs Product String + SW Ver (if
avail) + Module Instance + SN
Example:

PICDEM FS USB Demo Board 2004 V1.0 (I=0,SN=1033)

Note: EnumDevices returns True if successful


Use var.length to determine the size of output array

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

79

Multiple Devices
Communication

Program RequirementsCombo Box:


Form.Text=Lab 3

Displays a list of Devices with


Vid_Pid="vid_04d8&pid_000c
(Use Ep="\MCHP_EP1)
Button:
Sets USBDevice.DeviceIndex to
ComboBox1.SelectedIndex

Displays Device Serial Number in TextBox1


(Set TextBox1.Text property)

Label

TextBox1:
TextBox

Button:

Resistance

Requests Data from Device

2011 Microchip Technology Incorporated. All Rights Reserved.

Displays Device Serial Number

1544 USB5

Slide

80

Multiple Devices
Communication
Check DeviceCount
EnumDevices
Populate ComboBox

Start

Setup VID/PID,
Instance, EP

Send
Packet

Wait for User


Input

Start USB
Listener

Process Data

USB Listener Thread

Update Device Instance/SN


Turn on USBListener if
Device Changed

Display Data
2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

81

Multiple Devices
Communication

Helpful Hints

Class Declaration/Initialization

Dim MyDev as ExampleClass


In the code:

Array Declaration

Sub ProcessData(DataArray() as Byte)

Data Returned

Use Form1_FormClosing

Subs

Use Form1_Load

Finalization

Dim DataArray(0) as MPUSBClass.USB_CMD_LIST


DataArray(0) = MPUSBClass.USB_CMD_LIST.RD_TEMP

Initialization

MyDev=New ExampleClass(Textbox1, AddressOf DataSub)

Byte (0) = Requested command echoed back


Byte (163) = Data

ComboBox

Use ComboBox1.Clear to clear the combo box


Use ComboBox1.AddRange(StringArray) to add array of strings to the combo box (output of
EnumDevices)

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

82

Lab 3
Multiple Devices
Communication

40 Minutes
Save all your work after you are finished.
Lab 3 code will be reused in Lab 4.
2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

83

Multiple Devices
Communication

Tracking WM_DEVICECHANGE Message


1.

Create a sub (No Inputs/Outputs)

2.

Sub DevicesChangedMessage()

Add the event handler initialization to Form1_Load

AddHandler USBDevice.DevicesAddedRemoved, AddressOf


DevicesChangedMessage

DevicesChangedMessage() sub will be called every time a new


device was added/removed to the system.

Lab 4: Copy and paste the device enumeration code into


DevicesChangedMessage(). Test the auto-enumeration feature
of your program.

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

84

Multiple Devices
Communication

Start

Setup VID/PID,
Index

Send
Packet

Wait for User


Input

Check DeviceCount
EnumDevices
Populate ComboBox

Start USB
Listener

Update Device
Instance/SN
Re Enum
Devices

Display Data
2011 Microchip Technology Incorporated. All Rights Reserved.

DevicesAddedRemoved
Event
(WM_DEVICECHANGE )

Process Data
1544 USB5

USB Listener Thread


Slide

85

Lab 4
Automatic Device
Enumeration
(Multiple Devices
Communication)

10 Minutes
2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

86

Adding Commands to
USB Communicator

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

87

Adding Commands

Step 1 Embedded Software

User.H

User.C

Contains ServiceRequests function


Code for new commands should be added to
switch(dataPacket.CMD) statement

Step 2 Windows Side

Add new command declaration to USB_CMD_LIST enumerator

Contains declaration for DATA_PACKET


New commands should be added to CMD enumerator inside
DATA_PACKET

"Enum/Struct/Const Declarations Region of MPUSBClass

Add code to handle new command to ProcessData sub of FrmMain


class

Step 3

Test command

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

88

Lab 5

ADD Command to Toggle LED4

Use mLED_4_Toggle() inside the


embedded code

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

89

Customizing Device
usb_descriptors.c

EP Type (Bulk or Int)

CFG01 structure

Use _INT for Int type, _BULK for bulk type

VID/PID

USB_DEV_DSC

Serial Number

sd000 structure

Note: If SN is longer then 1 word, string[1] should be updated accordingly.

Manufacture String

sd001 structure

Look for Vendor ID and Product ID comments

Note: string[x] should be updated to reflect the new array size.

Product String

sd002 structure

Note: string[x] should be updated to reflect the new array size.

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

90

Data Rate

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

91

Data Rate Ideas

USB Data Rate (USB Communicator APP)

64 Kbytes/sec max in INT mode

Use BULK transfer

Modify USBListenServer to use MPUSBReadInt function


Missed reads on 1 ms intervals result in at least 1 packet
transmission miss (1 ms latency)
Or
Increase MAX_READBUFFER_SIZE to 6400 bytes (RxTimeout
should also increase to over 100 ms)
Both In and Out EPs must be BULK (embedded software)

Avoid/minimize updating form controls/converting large


amounts of data to string from within the data callback
function

Example: Commenting out the 4 lines inside DisplayData sub


marked as Start Speed Test End Speed Test improves
throughput from 17 Kbytes/sec to 32 Kbytes/sec (Int mode)

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

92

Data Rate Ideas

USB Data Rate (USB Communicator APP)

Request Reads for Multiple Data Packets

i.e., read 6400 bytes instead of 64 bytes

Use Overlapped Reads

Number of callbacks/sec are limited by system resources, larger


data reads will minimize number of callbacks
Example: Going from 64 to 6400 reads in Bulk mode improves
data throughput from 32 Kbytes/sec to 172.8 Kbytes/sec (change
MAX_READBUFFER_SIZE constant to 6400 and keep the Speed
Test lines commented out)

Multiple data read requests setup to execute consecutively,


upon completion of the current read operation (minimizes
idle time between reads)

Use Ping-Pong Buffers in Conjunction with


Overlapped Reads

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

93

Summary

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

94

Summary

Principles of Bidirectional USB Communication


VB.Net USB Class and Sample App

Function Explanations
Single and Multiple Point Acquisitions
Continuous Data Acquisition
USB Descriptor acquisition

Retrieving Device Manufacturers Serial Number


Retrieving Device Product String
Retrieving Device Manufacturers String

WM_DEVICECHANGE Event (Device Enumeration)


Tracking by Windows Instance
Tracking by Serial Number

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

95

Summary

Customizing the Application

Adding commands to message pump


Adding commands to embedded software

Improving Data Rates

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

96

Dev Tools Used


in This Class

USB Demo Board

PICDEM FS USB Board

PN: DM163025

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

97

References

PICDEM FS USB Demonstration


Board Users Guide (DS51526)
Microchip MPLAB C18 C Compiler
(Student Edition Free)

Microchip MPLAB IDE free


download:

http://www.microchip.com/C18

http://www.microchip.com/mplabide

http://www.microsoft.com

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

98

Questions?

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

99

Trademarks

The Microchip name and logo, the Microchip logo, dsPIC, KeeLoq, KeeLoq
logo, MPLAB, PIC, PICmicro, PICSTART, PIC32 logo, rfPIC and UNI/O are
registered trademarks of Microchip Technology Incorporated in the U.S.A.
and other countries.
FilterLab, Hampshire, HI-TECH C, Linear Active Thermistor, MXDEV,
MXLAB, SEEVAL and The Embedded Control Solutions Company are
registered trademarks of Microchip Technology Incorporated in the U.S.A.
Analog-for-the-Digital Age, Application Maestro, chipKIT, chipKIT logo,
CodeGuard, dsPICDEM, dsPICDEM.net, dsPICworks, dsSPEAK, ECAN,
ECONOMONITOR, FanSense, HI-TIDE, In-Circuit Serial Programming,
ICSP, Mindi, MiWi, MPASM, MPLAB Certified logo, MPLIB, MPLINK,
mTouch, Omniscient Code Generation, PICC, PICC-18, PICDEM,
PICDEM.net, PICkit, PICtail, REAL ICE, rfLAB, Select Mode, Total
Endurance, TSHARC, UniWinDriver, WiperLock and ZENA are trademarks
of Microchip Technology Incorporated in the U.S.A. and other countries.
SQTP is a service mark of Microchip Technology Incorporated in the
U.S.A.
All other trademarks mentioned herein are property of their respective
companies.
2011, Microchip Technology Incorporated, All Rights Reserved.

2011 Microchip Technology Incorporated. All Rights Reserved.

1544 USB5

Slide

100

You might also like