Winusb-no longer write drivers for your USB device

Source: Internet
Author: User
Tags guid generator

[Blog.csdn.net/lanmanck]

Once upon a while, we found a job as a driver engineer, with a low monthly salary. The Code of people we have never touched cannot be understood at all.

Today is good. If we do not want to pursue differentiation, we can allow the system to communicate with USB devices without drivers. Linux will not talk about it. libusb is very useful. Now we will talk about windows.

Winusb is a kind of middleware similar to libusb and USB device communication provided by Microsoft from the XP-SP2, through which we do not need to pay for the research and write USB driver. This is a few resources. First, we will repost a detailed blog post to give you a thorough understanding. It's just E, so be careful.

Resource:

1. libusb Introduction: http://www.libusb.org/wiki/windows_backend

2. Jan's blog: Ghost

3. Microsoft teach you how to install inf: http://blogs.msdn.com/ B /usbcoreblog/archive/2012/09/26/how-to-install-winusb-sys-without-a-custom-inf.aspx

4, another buddy write. Net-winusb control and source code: http://www.asyncop.com/MTnPDirEnum.aspx? Treeviewpath = [O] + open-source \ winusb + component

5, Microsoft official description: http://msdn.microsoft.com/zh-cn/library/ff540196.aspx

6, Microsoft teach you how to communicate: http://msdn.microsoft.com/library/windows/hardware/gg487341

7, a buddy to do the stm32 communication, to the wall: http://searchingforbit.blogspot.com/2012/04/winusb-communication-with-stm32-part-1.html

Okay, I want to post an introduction to winusb in E, or a professional written by foreigners:

Explore USB with winusb

This article originally appeared in Nuts & volts.

If you're developing a device that needs to talk to a PC, the chances are good that USB will be involved. for each USB device, the PC assigns a software driver. windows provides drivers for devices that fit into defined USB classes such as human interface,
Printer, or mass storage. If your device doesn't fit a defined class, Microsoft's winusb driver is an option.

In this article, I'll show how to program and access winusb devices. The winusb driver requires a PC with Windows XP SP2 or later, including Windows Vista and Windows 7.

A transfer type for every purpose

Every USB data transfer is between a PC or other USB host computer and a device endpoint. A device endpoint is a buffer that stores ed data or data to transmit. every device must support endpoint zero, which is bidirectional. additional, optional endpoint
Addresses each have a number (1-15) and a direction (in or out ).

Even though endpoints reside on devices, the USB specification defines endpoint ction from the view of the host PC. an in endpoint sends data to the PC, and an out endpoint between es data from the PC. this naming convention can be confusing when writing
Code for the device side!

One reason why USB is so versatile is its support for four transfer types, each with different strengths. winusb supports control, bulk, and interrupt transfers. control transfers use endpoint zero. the other transfer types can use endpoints one and higher.

Control transfers provide a structured way to send requests and data and receive responses. control transfers are the only type that can pass information in both directions ctions in a single transfer. after device attachment, in a process called enumeration,
Host computer uses control transfers to learn about the device.

Winusb devices can also use control transfers to send and receive data in vendor-defined requests. for example, you can define a request to set or read a switch, send data to configure device operation, or receive a sensor reading.

A control transfer has two or three stages. to learn about a newly attached device, the host computer uses control transfers to request data structures called descriptors from the device. in the setup stage, the host sends the request. in the data stage,
The device sends the requested descriptor. in the status stage, the host acknowledges copying ing the descriptor. A host can also use control transfers to send information to a device in the Data stage, with the device acknowledging in the status stage. some
Requests have no data stage.

A usb host reserves a portion of the bus bandwidth for control transfers: 10% for low-and full-speed endpoints and 20% for high-speed endpoints. if the bus isn' t busy, control transfers can use more than the reserved bandwidth. but all devices must share
The bus, so on a busy bus, a control transfer may have to wait.

The other transfer types don't have multiple stages and can transfer data for any purpose. on an otherwise idle bus, bulk transfers are the fastest. but bulk transfers have no guaranteed bandwidth, so on a busy bus, bulk transfers must wait. common uses
For bulk transfers are printers and scanners, where quick transfers are nice but not essential.

For interrupt transfers, the host guarantees a maximum interval between requests for data from in endpoints or sending data to out endpoints. common uses for interrupt transfers are mice and keyboards, which need to transfer user input quickly to the host
Computer.

Isochronous transfers have a guaranteed transfer rate but unlike the other transfer types, isochronous transfers don't use them, and the specified er has no defined way to request re-transmitting upted data. common uses for isochronous transfers
Are streaming audio and video, where users won't notice or will tolerate a few packet upted or missing packets. winusb doesn' t support isochronous transfers.

Using the USB framework

My example code is for microchip technology's pic18f4550 microcontroller and mplab C6 compiler. I tested the code on Microchip's picdem FS-USB Development Board. A complete winusb project for the PIC along with companion Visual Basic and Visual C # applications
Are available from my website.

My PIC code uses Microchip's free USB framework, which is a set of source-code modules that handle low-level USB communications. Using the framework can save much time and trouble.

For each endpoint besides endpoint zero, the device provides an endpoint descriptor. This listing shows endpoint descriptors for bulk and interrupt endpoints in each direction:

// Endpoint descriptors
0x07,                    //  Descriptor size in bytesUSB_DESCRIPTOR_ENDPOINT, // Descriptor type_EP01_OUT,               //  Endpoint number and direction_BULK,                   //  Transfer type0x40, 0x00,              //  Endpoint size in bytes0x00,                    //  Ignored for bulk endpoint
0x07,                    //  Descriptor size in bytesUSB_DESCRIPTOR_ENDPOINT, // Descriptor type_EP01_IN,                //  Endpoint number and direction_BULK,                   //  Transfer type0x40, 0x00,              //  Endpoint size in bytes0x00,                    //  Ignored for bulk endpoint
0x07,                    //  Descriptor size in bytesUSB_DESCRIPTOR_ENDPOINT, // Descriptor type_EP02_OUT,               //  Endpoint number and direction_INT,                    //  Transfer type0x08, 0x00,              //  Endpoint size in bytes0x0A,                    //  Endpoint interval
0x07,                    //  Descriptor size in bytesUSB_DESCRIPTOR_ENDPOINT, // Descriptor type_EP02_IN,                //  Endpoint number and direction_INT,                    //  Transfer type0x08, 0x00,              //  Endpoint size in bytes0x0A                     //  Endpoint interval

The USB Framework defines constants that help make the code more readable and easier to maintain. for example, in Listing 1, usb_descriptor_endpoint is the constant 0x05, which the USB specification defines as the value that identifies an endpoint descriptor.

Other descriptors include the device descriptor, which contains the device's vendor ID (VID) and product ID (PID) and one or more interface descriptors that specify an interface number and how many endpoints belong to the interface. the USB 2.0 specification
Defines the fields in the descriptors.

Bulk and interrupt transfers

To read and write to endpoints, program code accesses an endpoint's buffer Descriptor (BD). To program USB framework communications on pics, you need to understand BDS.

A bd consists of four byte-wide registers that hold information about an endpoint's most recent data transfer or the next data transfer. the microcontroller core and the USB Module share ownership of the BD. the microcontroller core is the CPU that executes
The code, or firmware, That you program into the device. the USB Module, also called the Serial Interface Engine (SIE), provides hardware support for USB communications. A usb_handle is a pointer to an endpoint's BD.

The key to accessing a BD is its uown bit. when uown = 0, the microcontroller core owns the buffer, and firmware can read and write to the BD. when uown = 1, the USB Module owns the BD, and firmware can read uown but shoshould not read or write to other locations
In the BD.

This listing shows code for reading stored ed data on a bulk out endpoint.

#define WINUSB_BULK_EP 1#define WINUSB_BULK_IN_EP_SIZE 64#define WINUSB_BULK_OUT_EP_SIZE 64
WORD bulk_bytes = 0; USB_HANDLE USBWinUsbBulkOutHandle;unsigned char winusb_bulk_in_buffer[WINUSB_BULK_IN_EP_SIZE];unsigned char winusb_bulk_out_buffer[WINUSB_BULK_OUT_EP_SIZE];
// Set up the endpoint to enable receiving data.
USBWinUsbBulkOutHandle = USBGenRead(WINUSB_BULK_EP,     (BYTE*)&winusb_bulk_out_buffer, WINUSB_BULK_OUT_EP_SIZE);
if(!USBHandleBusy(USBWinUsbBulkOutHandle)){   // The microcontroller  core owns the endpoint.    // Check for received  data.
   bulk_bytes =  USBHandleGetLength(USBWinUsbBulkOutHandle); 
   if (bulk_bytes > 0)   {      // Data was received.       // Copy it to for  sending back to the host.
      for (count; count <=  bulk_bytes - 1; count++)      {         winusb_bulk_in_buffer[count] =          winusb_bulk_out_buffer[count];      }   }}

(Remember that an out endpoint has es data from the host .) the USB Framework's USB genread function handles contains details of preparing the endpoint to receive data. the function accepts an endpoint number, a pointer to a buffer to hold stored ed data, and
The maximum number of bytes to receive. The function sets up the transfer, sets uown = 1 to transfer BD ownership to the USB Module, and returns a pointer to the BD.

The USB Module then manages the data transfer without further intervention by firmware. when the endpoint has es an out token packet followed by data, the USB Module stores the data in the passed buffer and sets uown = 0 to transfer BD ownership back
The microcontroller core.

To check for sorted ed data, the Framework's usbhandlebusy macro first checks to see if uown = 0. if so, the usbhandlegetlength macro returns the number of bytes encoded ed. firmware can retrieve and use the specified ed data in any way. listing 2 copies the data
Into winusb_bulk_in_buffer for sending back to the host in a basic loopback test. After retrieving the data, firmware can call usbgenread again to prepare the endpoint to receive new data.

This listing shows code for sending data to the host from a bulk in endpoint:

USB_HANDLE USBWinUsbBulkInHandle;
if (!USBHandleBusy(USBWinUsbBulkInHandle)) {  // The microcontroller core owns the endpoint.   // Prepare to send data to the host.
  USBWinUsbBulkInHandle = USBGenWrite(WINUSB_BULK_EP,     (BYTE*)&winusb_bulk_in_buffer, bulk_bytes);

To send data, usbhandlebusy first checks to see if uown = 0. If so, a call to usbgenwrite prepares to send the data.

The function accepts an endpoint number, a pointer to a buffer that holds the data to send, and the number of bytes to send. the function sets up the transfer, sets uown = 1 to transfer BD ownership to the USB Module, and returns a pointer to the BD.

The USB Module then manages the data transfer without further intervention by firmware. on login ing an in token packet at the endpoint, the USB Module sends the data and sets uown = 0 to pass ownership back to the microcontroller core. firmware can then
Prepare for another transfer.

At the device, bulk and interrupt transfers are identical blocks t for the endpoint type. the only difference is in scheduling by the host. so to convert listings 2 and 3 for use with interrupt transfers, just replace every instance
BulkWithInterruptAnd set winusb_interrupt_ep = 2 (or whatever endpoint number the interrupt endpoint addresses are using) and set parameters and winusb_interrupt_out_ep_size to match the endpoint sizes in the endpoint descriptors.

Control transfers

Because of their multiple stages, control transfers are more complicated to program than bulk and interrupt transfers. the first step in responding to a control transfer is to detect the specified ed request. from information stored ed in the setup stage, firmware
Can learn whether the request is directed to the whole device or to a specific interface in the device.

This listing checks values already ed in the setup stage to find out if the request is directed to the winusb interface and if the firmware has defined the request. if so, the function examines the setup data to determine whether the host or device sends data
In the data stage and Calla function to handle the request:

// Check the Setup packet to find out if the request is  // directed to an interface, names the WinUSB interface ID,// and is a Vendor request.
if(SetupPkt.Recipient != RCPT_INTF) return;if(SetupPkt.bIntfID != WINUSB_INTF_ID) return;if(SetupPkt.RequestType != VENDOR) return;
// It’s a vendor-specific request to the WinUSB interface.// Decode the request and call a routine to handle it.
switch(SetupPkt.bRequest){  case WINUSB_REQUEST_1:
    // The Data stage is  host-to-device.
    WinusbControlWriteTransferHandler();    break;
  case WINUSB_REQUEST_2:
    // The Data stage is  device-to-host.
    WinusbControlReadTransferHandler();                break;    }   

The example handles two requests. Request 1 has a host-to-device data stage, and request 2 has a device-to-Host Data stage.

I patterned my code to handle the control-transfer requests after similar code in the USB framework. for requests where the device sends data to the host, I used the get_descriptor request as a model. code for requests where the host sends data to the device
Is less common, but I found an example in the Framework's virtual COM port example in the set_line_coding request.

Installing a device

The other side of winusb communications is the PC software that detects the device, assigns a driver, and exchanges data with the device.

An INF file is a text file that Windows uses to match a driver to a device. the inf file for a winusb device between des the vid and PID from the device descriptor and a 128-bit value called a guid, which applications use to identify a specific winusb device.
The GUID's length and the method used to generate the guid make it highly unlikely that multiple devices will have the same guid.

You can generate a guid in several ways. In Microsoft's Visual Studio Standard Edition and higher, select Tools> Create guid. Other options are Microsoft's guid generator,
Guidgen.exe, Or an online guid generator, both easily found via a Web search.

To customize my project's winusb inf file for your device, replace the guid and the vid and PID with your values. The GUID is in the [version] section's classguid item:

   ClassGUID = {36FC9E60-C465-11CF-8056-444553540000}

Replace the value between the curly brackets with your guid.

The device's vid and PID are in the INF file's [manufacturer] section in this item:

   %USB\MyDevice.DeviceDesc% = USB_Install,  USB\VID_0925&PID_1456

Replace the vid (0925 H) and PID (1456 h) with the idvendor and idproduct values in the device descriptor for your device.

To install a winusb Device on Windows XP, the PC must have three co-installer DLLs. microsoft's free Windows Driver kit (wdk) contains the files, which you can distribute with your software. you don't need to provide
The files for Windows Vista systems.

On first attachment, Windows searches for an INF file with a matching vid and PID. If needed, point the found new hardware Wizard to the location of the INF file and the co-installer files.

When the device is installed and ready for use, Windows Device Manager shows the device under
Universal Serial Bus Controllers. To view the Device Manager, right-click
My computerAnd selectManage, ThenDevice Manager.

Writing applications

You can access winusb devices with Visual Basic or Visual C #, including the free express editions. but Microsoft's. net Framework doesn' t provide a class for accessing winusb devices. instead, applications use Windows API functions and the winusb API
Detect and communicate with devices.

For each API function used, Visual Basic and Visual C # applications must provide a declaration. writing a Declaration requires translating Microsoft's declaration, written in C, to the syntax and Data Types supported by Visual Basic or Visual C #. to call
A function, you provide parameters whose data types match those in the Declaration.

API functions can find a specific device by guid value, obtain a handle for accessing the device, learn the number and type of endpoints, configure timeouts and other behavior, and exchange data using bulk, interrupt, and control transfers. if you're not
Familiar with Calling API functions, the programming can seem obscure, but my example applications show the way.

With this introduction to firmware and applications, You're ready to start experimenting with USB transfers for use in your projects.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.