Wishing you all a Happy and Prosperous New Year 2009


Dec 26, 2008

Have you came across MojoPac?





I came across this interesting tool today. This software claims (to a large extent it is true) and allows you to carry your entire PC (actually every software and documents including iTunes) on a USB Flash disk.

But, there is a catch in this otherwise very nice technology. To use this software the steps are as following.

1. First install the MojoPac software on your USB Drive.
2. Then install all the other software on the same USB Drive.

Now this USB thumb drive will allow you to use the software anywhere. It is like one of the portableApps applications.

But MojoPac helps you to achieve one more level user friendly behaviour. It allows you to have the same look and feel accross various Windows XP PCs.



How do I burn DVDs onto USB/Thumb ?

I saw this question in one of the forums.

The funny part of the question is how to burn DVDs on USB. There is an answer also given there.

But in case if any one got such a doubt I suggest one simple answer. Just copy the files to the Thumb Drivethat "you want to burn" from the DVDs. The only catch is if you have a thumb drive that is of smaller size, then it can be problem.

In that case you can convert the DVD videos into other formats like DivX, WMA or VCD etc..

The main purpose of doing this to view the videos in your computer while travelling.

 

A Jewelry Box with USB and Fingerprint Authentication and Security

Syba has manufactured a sophisticated jewelry box called BioMirage Coffer which can only be opened via fingerprint identification or a USB key.

This secure jewelry box provides two security measures: fingerprint authentication and a USB key. 

While the finger sensor is inherently more convenient, the USB key serves as a failsafe measure and additional protection in case the sensor loses its effectiveness or your fingerprint becomes unrecognizable.

I could not find an image for this Jewelry Box to show you. If anybody finds it, please leave a comment.

Also it is interesting to see what all ways USB can be used.

Dec 24, 2008

USB Drivers for DOS - USBASPI.SYS

If your system BIOS does not support booting from USB Disks, or you are using an old PC and willing to access some information from MS-DOS (If you are still using it) then there are few options that came to my notice that can be helpful to you.

The USBASPI.SYS is driver file you need to do this. This file is also known as "Panasonic v2.06 ASPI Manager for USB mass storage".

This driver is capable of mapping only map mass storage devices like external hard disks, cd- roms, cd-rw, dvd-rom, zip, jaz, ls-120, and flash memory to ASPI devices.

The driver switches you can use are: device=(path)USBASPI.SYS [/e] [/o] [/u] [/w] [/v] [/l[=n]] [/f] /r] [/slow] [/nocbc] [/norst] [/noprt]

You should be editing your config.sys and autoexec.bat files and add required changes to start using this driver.

[config.sys]

DOS=HIGH,UMB 
lastdrive=Z 
device=HIMEM.SYS 
rem The following line loads Panasonic's universal USB- controller driver 
devicehigh=USBASPI.SYS /v /w /e 
rem the following is an aspi mass storage driver for usb- connected HDs and compactflash memory cards 
devicehigh=DI1000DD.SYS 
rem The following one loads CD-ROM driver 
devicehigh=USBCD.SYS /d:USBCD001

[autoexec.bat] 
@echo off 
REM the following line adds a drive letter to the usb cd(rom/r/rw) mounted 
LH MSCDEX /d:USBCD001


A very detailed explanation on how to use this driver and various options available with driver are nicely explained at http://www.theinquirer.net/inquirer/news/069/1046069/yes-there-are-usb-drivers-for-dos.


There is another interesting document explaining the USB Driver for DOS at FreeDOS Documentation. The details on how to are provided here.  

If the pages don't open correctly better do a google search.

Alternatively, There is one more USB DOS Driver from Cypress. The link for Cypress USB Stack driver for DOS is here.(http://www.pocketec.net/downloads/duse_4_4.zip


How to Use the NTFS File System With USB Drives

Why you want to use the NTFS File System with USB Drives?

For users of computers that run Windows 2000, XP or Vista though, the preferred file system is often NTFS. The advantages over FAT32 include the ability to:

1. Create files larger than 4 GB in size
2. Encrypt documents for better security
3. Deny or limit permissions to individual files or folders


Read more about how to create an NTFS File System with USB Drives at the following link.

http://computer-drives-storage.suite101.com/article.cfm/how_to_use_the_ntfs_file_system_on_a_usb_drive

However there is one thing that one should take care of when changing to NTFS file system:
Backup your files from your USB Drive before staring to CONVERT and FORMAT.

XEM3050 - Xilinx Spartan-3 FPGA Integration Module

The XEM3050 FPGA Module promises to help in cutting design times and verification times of heavy electronic engineering projects.

In addition to a high gate-count FPGA, the XEM3050 utilizes the high transfer rate of USB 2.0 for configuration downloads, enabling an almost instant reprogramming of the FPGA.

Opal Kelly's FrontPanel software handles all the interaction between your software and the FPGA internals, dramatically reducing the time and effort required to interface to a design.

The XEM3050 is ideally suited for product prototyping and integration into OEM devices where a USB interface, flexible hardware solution, or PC software interface would be useful. The XEM3050 can easily be added to a new board design to provide turnkey USB integration with the convenience of Opal Kelly's software programmer's interface and existing USB drivers.

Download Portable Office Suite (Openoffice 3.0) to your USB Thumb Drive/ USB Flash Disk

Openoffice 3.0 is a an open source Office software and with version 3.0 it is very much like Microsoft Office. The two interesting things about it is it supports both Microsoft Office file formats as well as Google Docs file formats and it is free.

It is developed in Java and supported be Sun Microsystems.

It is a complete office suite that is free. Now you can now carry it on your thumb drive too. 

File size of Portable Openoffice 3.0 is about 86.4 MB.

Download Portable Openoffice.org 3.0 for your USB Flash Drive.

Dec 23, 2008

USB Cup Warmer

I have already posted about USB Chiller here. This post is about the USB Gas Stove Cup Warmer. Yet another interesting use of USB :-).

Image 1 of the USB Cup Warmer.





Image 2 of the USB Cup Warmer.



The USB Gas Stove Cup Warmer is a fairly small and cozy object, and its reduced footprint is most likely to make it easy to integrate on almost any desk. This toy sports 140mm x 125mm x 28mm, and comes in either orange or blue finish.

Links to some more USB Cup Warmers are given below.


Dec 16, 2008

Intel Developers Demo USB 3.0 Throughput On Linux

USB 3.0 is on it's way. Intel has demonstrated the USB 3.0 transfer speeds upto 3.5 times faster than the USB 2.0.

See the following video:



Free program to create protected partitions on USB drives


Now USB flash drives are cheap and available everywhere. So, securing the drive's contents has become a major issue. To avoid this problem. There is a free software called Rohos Mini Drive  helps in solving this problem. 

This software is a Windows application. It lets you create a password-protected, encrypted, and hidden partition on any USB flash drive.

This clever application works when you plug the USB drive with a Rohos hidden partition into your PC. You will only see the unprotected partition. If Rohos is installed on the computer you can right click the icon in the system tray to connect the hidden partition. If you're using a computer without Rohosinstalled, you can run the "Rohos mini.exe" program in the main partition on your flash drive and enter your password to unlock the hidden partition. 
 

Freescale Semiconductor’s MC9S08JM16

Freescale Semiconductor’s MC9S08JM16 8-bit microcontrollers integrates on-chip USB 2.0 Full-Speed device support.







Features include:
   - 48-MHz S08 core
   - Bus Frequency of 24 MHz
   - Upto 16-KB Flash Memory
   - 1 - KB SRAM
   - 256-Bytes USB RAM
   - Operating Voltage Range of 2.7 V to 5.5 V
   - Other Peripherals :  2x SCI, I²C, 2x SPI, a 7-channel keyboard interface (KBI), a 2-channel 16-bit timer, a 4-channel 16-bit timer, a 12-bit 8-channel ADC, and a real-time clock.

Package Options:  48-pin QFN, 44-pin LQFP, and 32-pin LQFP.

Software Support: Freescale's USB-LITE stack. 

Dec 12, 2008

25 Miles USB Cable??? Do you think it is possible? See below.

This is an interesting Idea though. If such a cable exists we can following easily. We can break away with the 5 meter USB cable limit.

Working from home by connecting your USB Monitor, USB Keyboard and USB Mouse to your computer at office which at a distance of 25 Miles.

You can monitor activity in your backyard, or you can also monitor what your kid is doing at school and what the teacher is doing at school with an USB Camera and an USB Microphone. Outrageous right. But it is possible too.

The main benefit with such a cable according to wired blog is "one of the selling points of the system is that governments can use it to run secure connections to distant cameras. For us, more modest extensions over USB's five-foot limit mean we can tuck unsightly peripherals away in hidden corners."

The image on right hand side shows the Icron's ThinkLogical setup, ExtremeUSB .

ThinkLogical setup doesn't use the actual USB protocol to transfer the USB Data. They provide interface boxes and you need to plug them in. Each box converts the USB signal to or from a Icron's proprietary signal and sends this over the wire (or the air, or the powerline). The trick is, to the computer and other devices, the whole thing looks like a regular USB hub. A twenty five mile long USB hub, but a hub nonetheless(Wired.com).

See the "ExtremeUSB" site for more details details.

That's an useful and impressive solution.

Dec 11, 2008

USB Guard Dog - Desktop Rex - Funny Device

USB Guard Dog - Desktop Rex


It really does not protect you and your PC if some is logging in with your Password. But one thing the USB Guard Dog does is, he makes menacing growl each time someone comes too close. So, they even cannot touch your keyboard, till they know that he just growls.

Works with USB, basically draws power from USB or with three AA batteries too. Funny is in't it?

It's pricing can be found on this site.

Dec 10, 2008

USB Based Data Recovery Software and Tools

Selkie Freedom is the first data recovery product in the Selkie Software line to allow users to back-up their data to a USB key. 

Selkie Freedom is network independent so it doesn’t require a second computer. 

“Not everyone has a second computer to receive their recovered data. This product allows the user to push their data to a USB key, do a re-install on their broken machine, restore the data from the key and be up and running again in no time at all,” says Philip Fleischer, CTO. 

Selkie Freedom is available in three data recovery categories,  Selkie Freedom Photographer, Selkie Freedom Multimedia and Selkie Freedom Office.

Find out more about Selkie Freedom at www.SelkieFreedom.com or www.SelkieSoftware.com


The Rechargeable USB AA Cell




























A pack of these two Rechargeable USB AA cells cost around $19.95.

Nordic Semiconductor nRF24LU1+ USB dongle single chip system

Nordic Semiconductor has released the nRF24LU1+ USB dongle single chip for ultra-low power (ULP) wireless peripherals.

The nRF24LU1+ combines Nordic’s nRF24L01+ 2.4GHz radio transceiver with the nRF24LU1 USB dongle single chip device.

This solution includes an integrated voltage regulator that allows the chip to be powered directly from a USB bus, removing the requirement for an external voltage regulator. 

In addition, on-chip flash memory eliminates the need for an external E2PROM memory. The only external components the nRF24LU1+ chip requires are a low cost 16MHz crystal, decoupling, matching network and antenna.

More details can be found here.

Dec 9, 2008

Super Speed USB Logo and Cable Details - USB 3.0

 USB 3.0 uses different cable. But the connectors remains same. USB 3.0 cable carries 6 signals. The SuperSpeed USB carries 4 different signals, and can provide upto 50 percent more power for unconfigured or suspended devices, and 80 percent more power for configured devices.

USB 3.0 will support data rates as high as 5.0 Gb/sec— which is 10 times faster than USB 2.0 (High Speed USB). 

USB over IP Capabilities for your USB device. Silex introduced SDKs for network sharing of USB devices. It is called Silex Virtual Link SDKs.

For more information and features of this SDK visit here.


A USB Beverage Chiller?


Hmm.. that's an interesting Idea. 

This product is available here for 24.99 USD. But the web site also says it is out of stock.

Looks useful. Is in't it?

At Amazon also it is available. Here is the link.

What to do with small memory size USB Flash Drives

Today I found out an interesting article posted by Michael Kwan here that explains how to get benifit from existing USB Drives.

Here I will give the synopsis.
1. If you are using Windows Vista you can convert your USB drive to a Computer Lock. The process of doing this is explained here by Lifehacker.

2. There are versions of Linux that you can carry in the Thumb Drive. Visit http://www.pendrivelinux.com for the possibilities.

3. Again you can load portable Apps. This helps you when you go to internet cafe as suggested by Michael Kwan. You can find some USB portable Apps here(http://portableapps.com/). 

If you also have any more Ideas feel free to add them here.





Acer and DisplayLink unleases a new 22-inch USB Monitor

Acer, and DisplayLink, announced the availability of a new USB computer LCD monitor which still supports Windows Vista’s Aero Glass interface as well as other 3D functions. 

The B223 USB LCD Monitor comes with the following features:

22″ LCD display, 1,680 x 1,050 resolution, DisplayLink DL-160 network display chip, USB 2.0 connectivity, 5ms response time, 32-bit, true-color graphics. 

The B223’s height, rotation and swivel angles can be adjusted for your optimal viewing comfort. It’s already available in Europe. Priced around $430.

DisplayLink plug-and-play technology helps you to quickly connect the screen without having to install any drivers in Windows; DisplayLink offers separate Mac drivers for USB monitors but hasn’t said whether the B223 is supported.

PC and USB based Relay and Control Products

http://www.j-works.com/ is manufacturer of PC and USB based  Relay.  DPDT,  SPDT, Temperature, Thermocouple, I/O, Digital, FPGA, Counter, WDT, Encoder, USB Switch, Analog, Opto IO, Monitor, USB IO, USB DIO, USB ADC, USB DAC, USB Measurement and Control Products.

They have whole portfolio of USB Opto I/O Modules, USB WatchDog Timers Modules, USB Relay modules, USB Digital I/O (DIO) modules, USB Analog Measurement modules, USB AC Monitor Modules, USB Counter  Modules, and USBTemperature modules.

They recently released their J-Works JSB291-03 USB controlled SPDT 20 Amp relay module now and it is in full production.

Wow, this is one company that is fully into control systems and USB.

Amazing Tiny 8GB Pico USB drive

This Tiny USB Drive has 8GB capacity. This family of USB drives are available in the range of 1 GB to 8GB.

Visit http://www.supertalent.com/ and here to get more details on this device.

It is USB 2.0 compliant and the gold plated one is around $39.95.

LaCie USB Speakers

Look at their ergonomics. These USB speakers look different.



And here is a good review on these speakers.


Nov 25, 2008

Agilent Technologies Announces USB 3.0 SuperSpeed Physical Layer Compliance Test Application

Agilent Technologies Inc today announced Super Speed USB 3.0 comprehensive test equipment. This solution will mainly help in testing and making USB devices compliant with USB-IF requirements.

Agilent demonstrated their solution at the First USB 3.0 Developers Conference in San Jose, CA. 

The Super Speed USB or USB 3.0 can deliver upto 10 times speeds as compared with USB 2.0 and makes power usage more efficient. SuperSpeed USB will be necessary for data-storage devices transferring more than 25 Gbps.

-- Infiniium DSO/DSA91304A 13-GHz oscilloscope for transmitter testing;
-- Agilent USB 3.0 transmitter compliance test application;
-- Agilent USB 3.0 test fixtures;
-- J-BERT N4903A, a high-performance serial BERT with complete jitter tolerance test for characterizing USB 3.0 SuperSpeed serial communication links;
-- Agilent ADS simulation software for creating and analyzing USB 3.0 channels;
-- Agilent VNA/PNA network analyzer N5230C-245 for measuring and analyzing USB 3.0 channels.
Additional information about Agilent's USB compliance test solution is available at www.agilent.com/find/N5416A.
For other USB Analyzers that can be used with USB 2.0 click here.




Nov 24, 2008

Using MPUSBAPI.CPP directly instead of MPUSBAPI.DLL

Related Links
1. For learning how to Usie MPUSBAPI.DLL with VC++ 6.0 click here
2. For main.c file used in this example click here.

1. Introduction

All the time, we are trying to use the MPUSBAPI.DLL in various development environments. We tried to use the .DLL in Load-time Linking and Run-time Linking methods. Even Microchip provided samples that show how to use the .DLL in both methods.

After trying few things I realized that the _mpusbapi.cpp file can be added to the project directly. The two important pointes to be noted are:
   - When using along with Borland C++ Builder, _mpusbapi.cpp can be used without modifications.
   - When using with other environments few changes are required.

The project is created in Visual C++ 6.0. But almost the same steps/concepts can be adopted while developing your project in other C++ environments also. 

2. Steps to use the _mpusbapi.cpp instead of mpusbapi.dll in Visual C++ 6.0

  1. Create a Win32 Console application as an Empty Project.
  2. Create main.cpp file and add it to the project.
  3. Now, using Windows Explorer copy the files _mpusbapi.cpp, _mpusbapi.h and Ioctls.h files into your project folder. These files are available in C:\MCHPFSUSB\Pc\Mpusbapi\Dll\Borland_C\Source folder.
  4. Go back to VC++ environment, and add the files to the newly created project. For this select the FileView tab in Workspace window. This window provides options to add the files in 3 sections. Source Files (.CPP) and Header Files(.H) and Resource Files(.RES). In our example we do not have .RES files. Add _mpusbapi.cpp under Source Files section and _mpusbapi.h & _Ioctls.h in Header Files Section.
    NOTE: If you compile the project at this point, it will throw errors. We havn't added any code in main.cpp. And some libraries are missing in the project settings at this point of time.
    Errors:
          Compiling...
          main.cpp
          _mpusbapi.cpp
          C:\VCExamples\test\_mpusbapi.cpp(53) : warning C4068: unknown pragma
          Linking...
             Creating library Debug/test.lib and object Debug/test.exp
          _mpusbapi.obj : error LNK2001: unresolved external symbol __imp__SetupDiGetDeviceInterfaceDetailA@24
          _mpusbapi.obj : error LNK2001: unresolved external symbol __imp__SetupDiEnumDeviceInterfaces@20
          _mpusbapi.obj : error LNK2001: unresolved external symbol __imp__SetupDiDestroyDeviceInfoList@4
          _mpusbapi.obj : error LNK2001: unresolved external symbol __imp__SetupDiGetClassDevsA@16
          LIBCD.lib(crt0.obj) : error LNK2001: unresolved external symbol _main
          Debug/test.exe : fatal error LNK1120: 5 unresolved externals
          Error executing link.exe.

          test.exe - 6 error(s), 1 warning(s)
  5. The next step is fixing these errors.
       - unknown pragma : This warning comes because the file is originally built for Borland C++ and Borland C++ prgrams can not be understood by VC++. So remove the line #pragma argsused from _mpusbapi.cpp file.

       - error LNK2001: unresolved external symbol : This error came because we need to add setupapi.lib file to the libararies list in the project settings. The functions missing are from this library. So, goto << Project menu->Settings (Alt+F7)->Link Tab >>. Under Object/Library Modules add setupapi.lib and click on ok.

       - error LNK2001: unresolved external symbol _main : This error came as we did not add any code to main.cpp. We will do that at the end.

  6. The next step is setting the byte alignment to 1 byte. For this goto << Project menu->Settings (Alt+F7)->C/C++ Tab >>. Under Category List box select Code Generation. Selecting this displays four more list boxes. Under Struct member alignment select 1 byte.

    Then from same tab, this time from Category List box select Precompiled Headers. Then select Not using precompiled headers and click on OK. If you create some other type of project, then make sure if the precompiled headers agree for 1-byte struct alignment. Normally the compiler throws a warning in case of any differences. If not change the setting to "Not using precompiled headers".
  7. Now open to main.cpp file by selecting it from << Workspace Window->FileView tab>>.
    Copy&Paste the content from C:\MCHPFSUSB\Pc\Mpusbapi\Example Applications\Borland_C\Example 01 - Load-time Linking\console.cpp.
    Dont forget to remove the pragma "#pragma argsused" from this file also.

    NOTE:I added some more code to main.c used in this article. The link to the file is available in the resources box(top-right hand side of screen).
  8. Connect your demo board in the usual way and build and run this application.


In _MPUSBAPI.CPP file there is a DllEntryPoint entry function. To my knowledge the compiler will consider this function as a normal function rather than an entry point as we are not building a DLL here. For exe files main() is the entry point.

If get into trouble because of this function, then you can remove it. Other functions can be called straight away like how we do in Load-time linking.

To use the functions like MPUSBOpen, MPUSBRead etc.. you can follow the same syntax as Load-time linking. All then you need to do is writing a #include "_mpusbapi.h" on top of your source code. Before that you also need to include windows.h. 
   
         

Interacting with Microchip Full Speed USB Demo board using Visual Basic.NET

Source Files
1. Download the Visual Basic.NET Example with _cdecl.
2. Download the Visual Basic.NET Example with _stdcall.


1. What you need to know.


VB 6.0 allows to invoke functions from DLLs with _stdcall only. But VB.NET allows to invoke functions _cdecl calling convention also.

In this article I provided 2 project files for interacting with the Microchip Full Speed USB Demo Board. These projects interact with the Microchip general purpose USB Driver. MPUSBAPI.DLL with _cdecl can be downloaded from Microchip directly. The other example uses _stdcall calling convention. For this the MPUSBAPI.DLL need to be rebuilt with _stdcall convention. Also refer to the previous article for more information on how to use the _stdcall DLL in VB 6.0. Also previous articles gives an idea from where to download the files.

NOTE: The _cdecl DLL contains underscore(_) prefixed to the funtion names. Where as the _stdcall DLL will not contain the underscore(_) prefixed.

To interact with Microchip USB demo board from a PC MPUSBAPI.DLL need to be used.

2. How Visual Basic.NET and Visual Basic 6.0 access DLLs, differences:

Visual Basic.NET is a complete new development environment that is based on the .NET framework. The VB.NET is a complete Object Oriented Programming language and it supports modernization of code extensively. Most of the basic keywords remained same, but there are many additional keywords. Being a full object oriented language, VB.NET supports features like inheritance, polymorphism, abstraction, and encapsulation. As far as declaring the functions to access functions in .DLL file is same as VB 6.0 syntax. The major difference with respect to VB 6.0 version of the example code is in place of VarPtr the member functions of System.Runtime.InteropServices.Marshal need to be used. Marshaling is a mechanism used for converting/representing data between various platforms or environments in way that the content will never be lost. The System.Runtime.InteropServices.Marshal is a .NET class that is used for this purpose.

The UnsafeAddrOfPinnedArrayElement is used for obtaining the base address of the buffer that is used in MPUSBRead and MPUSBWrite function calls.

The other differences are language and environment specific differences. From the VB 6.0 example, .BAS file and .FRM files are converted to their respective .VB files.

3. VBMPUSBAPI.vb:

This file also provides the same set of functions which provided in the previous example.
  • Initialize: Used for initializing the variables.
  • OpenMPUSBDevice: Used for opening the data pipes of the Demo application.
  • CloseMPUSBDevice: Used for closing the opened data pipes.
  • SendReceivePacket: Used for performing the complete Demo application transfer. You can observe that SendData and ReceiveData are passed as Byte arrays. Inside the function the address of the first elements of the Byte arrays are passed to the Read and Write functions in the DLL.


4. VB6PICUSBDemo.vb:

This is the source code file that is generated when VB6PICUSBDemo.frm is ported to VB.NET. This file contains the actual example code on how to use the above functions. This ends the 3 article series on Visual Studio.NET. There is already one article available at www.piccoder.co.uk. So I am not touching the C# aspect.

Interacting with Microchip Full-Speed USB Demo Board using Visual Basic

This is MPUSBAPI Visual Basic 6.0 Example.

Source Code available here.

Modified _stdcall MPUSBAPI.DLL Files available here.


The previous article shows how to connect to the PICDEM FS Demo Board using Visual C++ and Win32 API. The previous article also explains from where to get the required files. So, take a look at it if you are starting from scratch. And this article uses an example application with similar functionality and User Interface as application written in VC++ in the previous article. 

In this article I will explain, how this can be done in Visual Basic 6.0. The Visual Basic.NET takes a different approach which I will explain in the next article. 

The MPUSBAPI.DLL that is provided along with package MCHPFSUSB.ZIP is a dynamic-link library(DLL) that provides a set of public functions for communicating with the Demo Board with the custom driver. And both Visual Basic 6.0 and Visual Basic.NET provides mechanisms to access the Win32 DLL directly even though there is no .LIB file available. For using a DLL in VB one does not need to use the LoadLibrary() API function set. 

But there is a catch. The DLL functions can only be used in VB provided they are implemented using the Standard Calling convention. i.e functions declared with _stdcall. This places a limitation on the usage of a number DLLs in Visual Basic that are developed using Visual C++ or Borland C++ tools if the _cdecl or any other calling convention methods are used while declaring or defining the functions. 

Please refer to http://support.microsoft.com/default.aspx?scid=kb;en-us;Q153586 for more information on how DLL need to build for using in Visual Basic. 

The DLL provided by Microchip is implemented using the _cdecl calling convention. This may be for achieving higher performance. So, we can not use it directly in Visual Basic. The DLL Source project need to be re-compiled by changing the declarations of the exported function to _stdcall. The modified source code of the MPUSBAPI.DLL can be downloaded here. Download this source code and re-build it using Borland C++ Builder tools. 

NOTE
The DLL need to be recompiled by adding _stdcall in place of _cdecl to all exported functions. 

Ok, lets move on now.


First things first, Visual Basic 6.0 does not support pointers. Which means that it is not supporting HANDLEs. HANDLEs are used in Win32 API to access system level objects. The HANDLEs in VC++ are represented as pointers. When it comes to VB, there is no way to declare pointers. But pointer is nothing but a variable that stores in address. An address is a numeric value of 32 bit length in WIN32 Operating Systems. That means variables of type Long datatype can be used for representing HANDLEs in VB. 

Similarly corresponding VB data types which can hold the data need to be identified for each argument and return types of the functions in the DLL. 

For more information on how these functions work, take a look at the previous article. 

Now the task at hand is creating a .BAS file which will hold references to the above listed functions in the syntax that is followed in VB 6.0. 

Ok, it is time to learn some theory.

Next step is creating .BAS file in the Visual Basic with the list of exported (public) functions in the DLL. The MPUSBAPI.DLL has following functions(This DLL is created with the _stdcall and notice that the underscores prefix of the functions are gone.)


  • DWORD MPUSBGetDLLVersion(void)
  • DWORD MPUSBGetDeviceCount(PCHAR pVID_PID)
  • HANDLE MPUSBOpen(/*Input */ DWORD instance, /* Input */ PCHAR pVID_PID, /* Input */ PCHAR pEP, /*Input*/ DWORD dwDir, /*Input*/ DWORD dwReserved);
  • DWORD MPUSBRead(/*Input*/ HANDLE handle, /*Output*/ PVOID pData, /* Input */DWORD dwLen, /* Output */PDWORD pLength, /*Input*/ DWORD dwMilliseconds);
  • DWORD MPUSBWrite(/*Input*/ HANDLE handle, /*Input*/ PVOID pData, /*Input*/ DWORD dwLen, /*Output*/ PDWORD pLength, /*Input*/ DWORD dwMilliseconds);
  • DWORD MPUSBReadInt(/*Input*/ HANDLE handle, /*Output*/ PVOID pData, /* Input */DWORD dwLen, /* Output */PDWORD pLength, /*Input*/ DWORD dwMilliseconds);
  • DWORD MPUSBClose(/*Input*/ HANDLE handle);

  • Keywords used in VB 6.0 for declaring API functions: 

    1. Public:  This keyword is used to indicate that the function declared is public function which can accessed through out the VB program.
    2. Declare:  Used at module level to declare references to external procedures in a dynamic-link library (DLL).
    3. Function/Sub:  Function indicates that the procedure returns a value that can be used in an expression. Sub indicates that the procedure does not return a value.
    4. Lib:  Indicates that a DLL or code resource contains the procedure being declared. The Lib clause is required for all declarations when using a DLL.
    5. Alias:  Indicates that the procedure being called has another name in the DLL. This is useful when the external procedure name is the same as a keyword. You can also use Alias when a DLL procedure has the same name as a public variable, constant, or any other procedure in the same scope. Alias is also useful if any characters in the DLL procedure name are not allowed by the DLL naming convention.

    Syntax used in VB 6.0 for declaring API functions:

    Public | PrivateDeclare { Sub | Function } name Lib "libname" [ Alias "aliasname] [(arglist])] [ As type 

    Example: 
    Public Declare Function LoadLibrary Lib "kernel32" Alias "LoadLibraryA" ( ByVal lpLibFileName As String ) As Long 

    The example shows the LoadLibrary function which we used extensively in previous article when used in VB 6.0. The "kernel32" represents the KERNEL32.DLLfile which is a system Win32 API file and one of the core DLLs of the operating system. Actually the function LoadLibraryA is implemented in this DLL. But we are using the Alias keyword to change the name to LoadLibrary

    This API function takes 1 argument and returns a value. So it is declared as function in VB. As it takes a string as argument, the datatype of the argument is declared as String. As it returns a HANDLE as return value, the return value data type is selected as Long. Similarly public exported functions available in other Windows System DLLs as well as User DLLs can be accessed. If the function name to be used in Visual Basic is same as the function name in the DLL the use ofAlias is not required. 

    The MPUSBAPI.DLL functions looks in the following manner when declared in Visual Basic 6.0. When these declarations are made, make sure that the DLL is in a directory which is listed in the system path. 

    • Public Declare Function MPUSBGetDLLVersion Lib "mpusbapi" () As Long
    • Public Declare Function MPUSBGetDeviceCount Lib "mpusbapi" (ByVal pVID_PID As String) As Long
    • Public Declare Function MPUSBOpen Lib "mpusbapi" (ByVal instance As Long, ByVal pVID_PID As String, ByVal pEP As String, ByVal dwDir As Long, ByVal dwReserved As Long) As Long
    • Public Declare Function MPUSBRead Lib "mpusbapi" (ByVal handle As Long, ByVal pData As Long, ByVal dwLen As Long, ByRef pLength As Long, ByVal dwMilliseconds As Long) As Long
    • Public Declare Function MPUSBWrite Lib "mpusbapi" (ByVal handle As Long, ByVal pData As Long, ByVal dwLen As Long, ByRef pLength As Long, ByVal dwMilliseconds As Long) As Long
    • Public Declare Function MPUSBReadInt Lib "mpusbapi"(ByVal handle As Long, ByVal pData As Long, ByVal dwLen As Long, ByRef pLength As Long, ByVal dwMilliseconds As Long) As Long
    • Public Declare Function MPUSBClose Lib "mpusbapi"(ByVal handle As Long)As Long


    When we take a look at the above declarations which are used in Visual Basic, one can observe that the data types of the arguments in each function almost match the data types of their C language prototypes. But, few are not matching. Out of these one important argument is pData which is originally an array of bytes. But here in VB it is declared as Long. The reason for this declaration is when the data is passed from VB, we are actually passing the address of first element in the array. As we know, the address is an unsigned numerical value, which can be represented in VB with Long type. Once the address is available to a function, the function can do any with the data available in that address. When see the source code files provided along with this project, you can observe that the address of first byte is passed from a Byte array. 

    The VB 6.0 Example code can be downloaded from here

    The (VBMPUSBAPI.BAS) contains all the code related to MPUSBAPI.DLL and also additional functions and data definitions required to communicate with the demo firmware that comes with the demo board. 

    It implements following functions:
    • Initialize: Used for initializing the variables.
    • OpenMPUSBDevice: Used for opening the data pipes of the Demo application.
    • CloseMPUSBDevice: Used for closing the opened data pipes.
    • SendReceivePacket: Used for performing the complete Demo application transfer. You can observe that SendData and ReceiveData are passed as Byte arrays. Inside the function the address of the first elements of the Byte arrays are passed to the Read and Write functions in the DLL.


    The (VB6PICUSBDemo.frm) is VB Form file, which contains the event handles for two check boxes and one command button. These function in-turn calls the functions declared in the .BAS file as per the requirement. The section 7.2 in the previous article shows how the sequence is to be followed. The event handles in this file also follows similar sequence.

        Private Sub Check1_Click()
          [Step A - Declarations]
          Dim send_buf(0 To 64) As Byte
          Dim receive_buf(0 To 64) As Byte
          Dim RecvLength As Long

          [Step B- Open the USB End-points]
          OpenMPUSBDevice

          [Step C- Check the Handles of the End-points to see if the are opened properly]
          If myOutPipe <> INVALID_HANDLE_VALUE And myInPipe <> INVALID_HANDLE_VALUE Then 

              [Step D- Initialize the command to be transmitted to demo firmware]
              RecvLength = 1
              send_buf(0) = 50 '0x32 - SET_LED 
              send_buf(1) = 3 ' LED Number
              'Set LED value based on the check box state
              If Check1.Value = 1 Then
                send_buf(2) = 1
              ElseIf Check1.Value = 0 Then
                send_buf(2) = 0
              End If

              [Step E- Call SendReceivePacket to send the command and to receive the response ]
              If (SendReceivePacket(send_buf, 3, receive_buf, RecvLength, 1000, 1000) = 1) Then

                [Step F- The received data confirms that the command is executed properly ]
                If (RecvLength <> 1 Or receive_buf(0) <> 50) Then
                  MsgBox "Failed to update LED"
                End If

              End If

          End If

          [Step G- Once the operation is completed, close all the open handles ]
          CloseMPUSBDevice

        End Sub

    In the next article I will explain how to use the Visual Basic .NET.

    List of USB Protocol Analyzers available in market

    What does USB Protocol Analyzers do?

    USB Protocol Analyzer is like any other protocol analyzer. It basically hooks onto the bus and probes the signal patterns, and from the signal patterns re-creates the user understandable data or packet formats as per the USB 2.0 specifications.
    There are two types of Protocol Analyzers for USB. 1) Hardware+Software Toolset 2) Only Software. This document explains only the Hardware Type Protocol Analyzers.
    The Hardware type protocol analyzers are costly to procure, and the price is directly proportional to the trace buffer available in the hardware. But these analyzers come with great powers, the collected data can be viewed and formatted in many formats and helps users to pin point the problems quickly and help in debugging the application.
    Some of the typical capabilities are:
    • Triggers - Specify when to start the data collection from the bus
    • Prefetch - How many packets need to be recorded before the trigger
    • Postfetch - How many packets need to be recorded after the trigger
    • Trigger Types - Manual, Automatic, Content Based (Based on what is there inside a packet), Transaction Based
    • Buffer Size Control - For managing the available trace buffers
    • Reporting & Filtering Options - Flexibility to view specific trasactions and specific packets
    • Save & Reload operations
    • Simulation & Transmission of User Defined Packets on the bus - In this case user can transfer a packet to see how the device driver or the device responds to specific packets. Activity is intiated by user, but the analyzer pretends as if the host or the device has generated the packet
    The above is a partial list of most common features. For more information one should check the documents of each of the Analyzers.




    List of USB Protocol & Bus Analyzers (that come in form of Hardware+Software)

    Analyzer Description Image(If Available)

    MQP Electronics Packet-Master USB480+
    Description:


    • On-the-Go(OTG) analysis

    • Analyse High-Speed, Low-Speed, Full-Speed USB Device in any combination of speeds

    • 32 Mbyte FIFO

    • Advanced hardware event triggering as standard

    • Up to 4Mbyte Pre-Trigger Data Buffer

    • Highest Specification for the Lowest Cost

    • Integral Capture Start and Stop buttons and Capture Indicator USB through-connectors for device under test

    • High Speed USB uplink for unlimited capture

    • BNC Connector for Trigger Input or Output

    • Feature connector provides signals for oscilloscope or logic analyser

    • Comprehensive event filtering, highlighting, searching and bookmarking

    • ncludes Free Class Analysis package

    • ~$1500 USD (special educational pricing available)



    MQP Electronics Packet-Master USB480+ Front View


    MQP Electronics Packet-Master USB480+ Back View


    MQP Electronics Packet-Master USB480
    Description:


    • On-the-Go(OTG) analysis

    • Analyse High-Speed, Low-Speed, Full-Speed

    • 32 Mbyte FIFO

    • Hardware triggering

    • BNC trigger input

    • Highly cost-effective development solution

    • Integral Capture Start and Stop buttons and Capture Indicator USB through-connectors for device under test

    • Automatically detects speed of link under test

    • High Speed USB (480 Mbit/s) connection to host PC

    • Feature connector provides signals for oscilloscope or logic analyser

    • Comprehensive event filtering, highlighting, searching and bookmarking

    • ~$1400 USD (special educational pricing available)



    MQP Electronics Packet-Master USB480 Front View


    MQP Electronics Packet-Master USB480 Back View


    MQP Electronics Packet-Master USB12
    Description:


    • Analyses Low Speed, Full Speed or a mixture of both(No High Speed)

    • Power Indicator & Activity indicator shows presence of data exchanges

    • Integral Capture Start and Stop buttons and Capture Indicator

    • Economically priced

    • Bus-powered for convenience of use, Optional external power input supply

    • High Speed USB uplink for unlimited capture time

    • Comprehensive event filtering, highlighting, searching and bookmarking

    • ~$750 USD (special educational pricing available)



    MQP Electronics Packet-Master USB12

    Ellisys USB Explorer 200
    Description:


    • Supports Low Speed (1.5Mbits/s), Full Speed (12Mbits/s) and High Speed (480Mbps)

    • Measurement of USB bus states and low level protocols

    • Device Bus Powered. No need for external adaptor.

    • Speedy USB2.0 Uplink with Internal 32MB FIFO Memory.

    • Intutive, Easy to use Interface.

    • High level decoding of requests and descriptors, making diagnosing problems a breeze.

    • Filtering and Highlighting of Events.

    • Dimensions: 150 x 120 x 65 mm, Weight 850g.

    • ~$2600 USD and includes a 2 years of limited warranty.


    Ellisys USB Explorer 200

    Ellisys USB Tracker 110 Recommended
    Description:


    • Supports Low Speed (1.5Mbits/s) and Full Speed (12Mbits/s)

    • Unlimited capture time.

    • USB2.0 Uplink (Backwards compatible with 1.1).

    • Device Bus Powered. No need for external adaptor.

    • Power and Activity LEDs. Activity flashes green on receipt of DATA0/1 packet but not captured and red if captured.

    • Realtime statistics during capture.

    • Filtering and Highlighing of Events.

    • Dimensions: 85 x 80 x 45 mm, Weight 75g.

    • ~$850 USD and includes a 2 years of limited warranty.


    Ellisys USB Tracker 110

    Wireless USB Explorer 300 Wireless USB Protocol Analyzer
    Description:


    • Displays UWB and Wireless USB protocols in an easy-to-use hierarchical view

    • Supports speeds up to 480 Mbps

    • Non-intrusively captures traffic from any MB-OFDM UWB link.

    • Automatically determines the speed of each frame and decodes it accordingly.

    • Highlights protocol errors and interoperability issues

    • Supports the latest WiMedia and Wireless USB specifications.

    • Free viewer software to exchange recorded traffic with others, Free lifetime software maintenance.

    • Powered by USB, no need for a bulky external power supply.

    • Dimensions: 150 x 120 x 65 mm (5.91 x 4.72 x 2.56'') , Weight 850 g (1.9 lbs).

    • 2 years of limited warranty.


    Wireless USB Explorer 300

    USB Ver.2.0 Bus Protocol Analyzer SB-2020
    Description:


    • Automatic detection of USB 2.0 at high, full, and low speed

    • Trigger function

    • Powerful filtering function.

    • Built-in 512 MB capture memory.

    • Capturing of log data up to 20 GB.

    • Display descriptor tree.

    • Bus state display.

    • Display communication speed.

    • Dimensions: 150 x 120 x 65 mm (5.91 x 4.72 x 2.56'') , Weight 850 g (1.9 lbs).

    • 2 years of limited warranty.


    USB Ver.2.0 Bus Protocol Analyzer SB-2020

    CATC USBTracer/Trainer™ Protocol Verification System
    Description:


    • CATC Trace Analysis Software System

    • OTG (On-The-Go) Support

    • Traffic Generation/Device Emulation.

    • 512 MByte Recording Capacity

    • Non-intrusive High Impedance Probe

    • Advanced Triggering

    • Extensive Decodes to display Device Class Specific information.

    • Real-Time Statistics & Hardware Filtering

    • Hi-Speed USB Port

    • 3 years of limited warranty.


    USBTracer/Trainer™ Protocol Verification System

    CATC Advisor™ Protocol Analyzer
    Description:


    • CATC Trace Analysis Software System

    • Records USB 2.0 traffic - Supports all three USB speeds (High (480Mbps), Full (12Mbps) and Low (1.5Mbps))

    • 128 MByte Recording Capacity.

    • BusEngine Protocol Processor technology

    • Dual Recording Channels

    • Advanced Triggering

    • Intelligent Reporting

    • Real-Time Statistics & Hardware Filtering

    • Hi-Speed USB Port

    • 3 years of limited warranty.


    Advisor™ Protocol Analyzer

    CATC USBMobile™ Protocol Analyzer
    Description:


    • PC Card form factor - Personal analyzer. Low-power, portable operation with any notebook PC

    • CATC Trace Analysis Software System

    • Records USB 2.0 traffic - Supports all three USB speeds (High (480Mbps), Full (12Mbps) and Low (1.5Mbps))

    • OTG (On-The-Go) Support

    • 64 MByte Recording Capacity.

    • 2 Mini AB USB ports and cables.

    • Extensive Decodes to display Device Class Specific information.

    • BusEngine Protocol Processor technology

    • Advanced Triggering

    • Intelligent Reporting

    • Real-Time Statistics & Hardware Filtering

    • Hi-Speed USB Port

    • 3 years of limited warranty.


    USBMobile™ Protocol Analyzer

    Beagle™ USB 12 Protocol Analyzer
    Description:


    • The Beagle USB 12 Protocol Analyzer is a bus-powered, high-speed USB 2.0 device. Being small, lightweight, and portable in size (89 x 41 x 25 mm) it is the ideal tool for engineers in the field.

    • Non-intrusive Full-/Low-Speed USB monitoring of a USB bus in real time. The capture is nearly limitless as data is constantly streamed to the analysis computer.

    • Share your captured data with your colleagues with ease. The Beagle Data Center is our free GUI monitoring software which can be downloaded from the Total Phase website.

    • The Beagle USB 12 Protocol Analyzer is only $400 in single-unit quantities. Additional volume discounts are available. At this price, every engineer can have their own analyzer.

    • The Beagle USB 12 Protocol Analyzer is available for purchase through the Total Phase website. Small orders of 25 units or less normally ship within 24-48 hours. If you are located outside the United States, please consult the list of international distributors on our website.



    Beagle™ USB 12 Protocol Analyzer

    Beagle USB 480 Protocol Analyzer
    Description:


    • Non-intrusive High-speed USB 2.0 monitoring (up to 480 Mbps)

    • Two capture modes: real-time and delayed-download

    • High-speed USB chirp detection

    • Hardware-based packet suppression

    • Digital inputs and outputs for synchronizing with external logic

    • Real-time capture and delayed-download capture

    • Free software and API available. Compatible to Linux & Windows.

    • The Beagle USB 480 Protocol Analyzer comes complete with software for an introductory price of $1200.



    Beagle™ USB 12 Protocol Analyzer

    CATALYST Conquest™ Series USB Protocol Analyzers
    Description:


    • Three Variants: Conquest Classic; Conquest Standard; Conquest Advanced

    • Low Speed (1.5 Mb/s); Full Speed (12 Mb/s); [ High Speed (480 Mb/s) Available in Standard, Advanced]

    • 128 MB Trace Memory.

    • Search on Errors and Data Payload

    • Snapshot Capture

    • Upper-level USB Device Class Decodes in Standard, Advanced

    • Trigger on Protocol Errors & Transactions in Standard, Advanced

    • Multi-level Event Triggering (Advanced mode)

    • Classic starts at $995.



    Conquest™ Series USB Protocol Analyzers

    CATALYST SBAE Series, Universal Serial Bus (USB)
    Description:


    • Too many features, see company website :-)

    • Analyzer, Exerciser, Device Emulator, OTG, DC Compliance

    • DC Compliance Test Suite

    • Protocol Error Detection

    • Performance Analysis & Performance Characterization

    • SBAE30B USB 2.0 Protocol Analyzer System (SBAE30B-2X-ADC)

    • SBAE30B USB 2.0 Protocol Analyser / Exerciser System (SBAE30B-2X-EDH)



    SBAE Series, Universal Serial Bus (USB)

    USB2 SnooperTM (USB 2.0 Bus Analyzer)
    Description:


    • Compatible to USB2.0 & USB1.1 specs

    • Supports HS, FS and LS speeds

    • Provides USB-ON-THE-GO ( OTG ) support

    • Non-intrusive snooping

    • Self powered. Does not consume power from USB cable

    • Provides Packet View, Transaction View, Control transfer view, Summary view, Raw bit view for effective packet analysis.

    • Comes as a PCI add-on card for fast transfer to PC memory. Optimizes the usage of PC's available memory. Works faster.

    • External Trigger input & external trigger outputs are for enhanced capture & trigger Oscilloscopes to observe electrical condition on the Bus

    • Time stamping for each captured packet with 16.67ns resolution.

    • Provides very high capture buffer depending on the PC memory. On Windows 2000 one can easily go up to 540MB of capture buffer depending on Memory support



    USB2 SnooperTM

    Nov 22, 2008

    Interacting with Microchip Full-Speed USB Demo Board using Visual Studio Tools - VC++ 6.0

    While going through the USB forums I found out that there are many questions on how to develop PC applications for Microchip Full-Speed Demo boards by using MPUSBAPI.DLL. To answer one of the questions on Microchip USB forum, I developed a small application in VC++ which uses MPUSBAPI.DLL.

    In this article, I will explain the technical aspects associated behind this application. And in subsequent articles I will explain how to use the MPUSBAPI.DLL library in Visual Basic.NET and C#.NET.

    The Microchip Full Speed USB Demo Board is a great tool to learn USB and even for developing prototypes. The board comes with a PIC18F4550 device which is a USB part from Microchip. The board can be self-powered or bus-powered. It has a temperature sensor and potentio meter. It also comes with an expandable bus architecture (PIC-Tail Plus), which helps in prototype development.

    Apart from these hardware features the board also comes along with a set of firmware examples and PC application examples. And the famous Demo Tool GUI which supports Bootloader features and Demo features. The board comes with a default factory hex file which has these two operations implemented. The Bootloader feature is always tempting for the end users like me. By using Bootloader I can reduce the cost of buying an ICD. The Demo Tool GUI is good enough to start with. But, I wanted to develop my own GUI and integrate the Boot example in my application. I am still on the learning curve on how to use it and develop GUI for the bootloader. In future I will post an article on it once I am done :-).

    But, before that, I will explain how to interact with the Demo portion of the default factory hex file. Which is nothing but Demo option in the PICDEMFS Demo Tool.

    How to develop an application that interacts with Demo firmware?

    1. Download the MCHPFSUSB.ZIP from Microchip USB site and install it. This installation will have following directory structure.
    Microchip Fullspeed USB Directory Structure

    2. The PICDEM FS board should have been programmed with either the factory HEX (which is available in C:\MCHPFSUSB\fw\_factory_hex) or with the HEX file from Demo firmware example (which will be available in C:\MCHPFSUSB\fw\Demo\_output after compiling the Demo project).

    3. The functionality provided in the C:\MCHPFSUSB\Pc\Mpusbapi\Dll\Borland_C\mpusbapi.dll need to be understood and learnt. To learn this file, refer to the file C:\MCHPFSUSB\Pc\Mpusbapi\Dll\Borland_C\Source\_mpusbapi.cpp. The developer of this DLL had put lot of effort in explaining each of function and how to use it. We will see more about these functions later.

    4. And finally you should understand the code provided in the C:\MCHPFSUSB\fw\Demo folder. This code has two parts, USB Stack(All other files related to USB) and the USER application (user.c and user.h in C:\MCHPFSUSB\fw\Demo\user\) code. If you go through the code little more, you can see how the endpoints are defined, how the hardware is configured etc.. But, as this article is concentrating only on the PC application development with Visual Studio we will be learning more about user.c.

    Ok, it is time to learn some theory.

    Windows Basics:
    1. Libraries in Windows Operating System

    A Software Library is a collection of functions, data and resources(bitmaps, string tables etc..) in object code format. The libraries provide modularization and re-usability of code. So, by developing a library we can group related code together and use this code whenever any application requires that kind of functionality. The code in the libraries are added to application code during the process of LINKING.

    The compiler tool chains used by Embedded Systems developers will implement a technique called, Static Linking to link libraries to the application. In this technique, all the libraries + source code object files are combined together and a final single HEX file will be generated, which will be used to program the device or board.

    But, in a OS like Windows where Multi-tasking is implemented, two or more copies of same application can be executed. And more than two copies of applications that use same library code can also be executed.

    What this means is, if Static Linking technique is used then, there is redundant code and data in the memory at the same time causing lot of memory wastage, and also the operating system has to lot of work loading unloading applications with larger in size into memory which can consume more time.

    To avoid these problems, Multi-tasking OSs like Windows came out with another technique of for linking libraries to the applications, which is known as Dynamic-Linking. Those libraries that used for Dynamic-Linking are called as Dynamic-Link Libraries. And they will have an extension of .DLL.

    So, The C:\MCHPFSUSB\Pc\Mpusbapi\Dll\Borland_C\mpusbapi.dll is a DLL, or Dynamic Link Library.

    When two applications are using the same DLL, then there will only one code copy of the DLL in memory which will be shared by both applications. This will eventually reduce the size of user application and as the library code is not combined to the application, it will speed up loading of applications. For more information on DLLs, goto Microsoft MSDN site. Alternatively, you can read the books on Windows Programming.

    One note is, even though Windows supports DLLs extensively, it still supports usage of Static Link Libraries, but Microchip's DLL(MPUSBAPI.DLL) is a Dynamic Link Library.


    2. Techniques for invoking functions from the library in Windows Operating Systems


    When a library project is built two files will be created. One is Library reference file(.LIB) and the other is Object Code file( .OBJ, .DLL). Object code is Machine Code with unresolved memory map and references. An Executable normally will have the references and memory map resolved.

    Once the .LIB file and .OBJ file are generated, for using them in C or C++ programs, a Header File (.H) will also be provided/required to be created. The Header file will be included into the source files using #include in the project and .LIB file will be added to Files to be Linked list of the project. The .OBJ will be placed in the source file folder. Sometimes, the .LIB file itself contains the Object Code also, depending on the compiler chain, and there will not be any .OBJ file generated.

    Now, if the generated files are .LIB and .OBJ, or only .LIB file, then these files will be used in Static linking,and if the generated files are .DLL and .LIB files then they will be used in Dynamic-Linking.

    In Static Linking, the method of calling the included library functions is straight forward, and it is as good as calling any other function in the source files which are part of the project. The .H file need to be included in the sources files at required locations.

    In Dynamic Linking, again there are two methods to access the functions available in the library(DLL). They are,
    2.1. Load-Time Linking: In this method, the library is linked to the application using a .LIB in the same manner, how it is done with Static Linking. The only difference is the .DLL file associated with the .LIB file will be loaded at the time of execution. i.e when the application is loaded into the memory. In this technique, the .LIB file will be added to the project library list and the .DLL file will be placed in the system PATH. Functions will be called in the same manner as Static Linking.
    The example given in the following path of C:\MCHPFSUSB\Pc\Mpusbapi\Example Applications\Borland_C\Example 01 - Load-time Linking demonstrate this technique.

    2.2. Run-time Linking: In this technique, the .LIB file will not be used. The application assumes that the .DLL file is available in the system PATH. The application uses LoadLibrary(), GetProcAddress() and FreeLibrary() Win32 API calls for invoking the functions from the DLL.
    The .DLL file is supposed to have the exported public symbols for using these functions. This technique is primarily helpful, when trying to access a DLL library for which a .LIB and/or a .H file are not available. We will use this technique for accessing the MPUSBAPI.DLL file as we don't have proper .LIB for Visual Studio.

    The example given in the following path of C:\MCHPFSUSB\Pc\Mpusbapi\Example Applications\Borland_C\Example 01 - Load-time Linking demonstrate this technique.

    3. Identifying the Function Names in a .DLL file with Dependency Walker.

    The Dependency Walker tool comes with Visual Studio 6.0 . This tool displays what all the functions available in a .DLL file. When the MPUSBAPI.DLL file is opened with Dependency Walker, it looks like this.


    View of MPUSBAPI.DLL in Dependency Walker

    So, from this view we can make out that there are 7 functions available in the DLL and, all of them have underscore ("_") prefixed to them. The same functions along with comments can found out in the files.
    C:\MCHPFSUSB\Pc\Mpusbapi\Dll\Borland_C\Source\_mpusbapi.cpp,
    C:\MCHPFSUSB\Pc\Mpusbapi\Dll\Borland_C\Source\_mpusbapi.h.

    The folder, C:\MCHPFSUSB\Pc\Mpusbapi\Dll\Borland_C\Source\ has two important header files. _mpusbapi.h and mpusbapi.h(without underscore).

    Now we know what functions are available in MPUSBAPI.DLL file. Next step is understand how to use these functions for application development. The _mpusbapi.h (with underscore) file is the actual header file. What it means is it declares the actual functions. This file can only be used during Load Time Linking.

    As we know that Load Time Linking is not possible with Visual Studio and MPUSBAPI.DLL, We need to use the Run Time Linking Technique.

    4. Introduction to LoadLibrary(), GetProcAddress() and FreeLibrary()

    4.1 LoadLibrary():
    This function is used to load any .DLL at run-time of the application.

    SYNTAX:
    HMODULE LoadLibrary( LPCTSTR lpFileName);
    This function takes the .DLL file name or a file name including full path as argument. Then it loads the DLL into the memory for use by application and returns HANDLE (HANDLE is a unique unsigned long number given by Windows OS to each object when it is loaded/created. The object can be application, DLL, Bitmap etc...). If the .DLL is already loaded this function returns the an existing handle.
    If the DLL can not be loaded due to incorrect path or any other reason, this function returns NULL. So, the user application need to check for this condition.

    4.2 GetProcAddress():
    This function is used to get a pointer to a function in the .DLL file.

    SYNTAX:
    FARPROC GetProcAddress( HMODULE hModule, LPCSTR lpProcName );
    This function takes two arguments. The HANDLE returned by the LoadLibrary function for hModule, and the name or ordinal of the function. So, if you take a look at the Dependency Walker picture shown earlier, _MPUSBGetDLLVersion will be name of the function. And 1 is it's ordinal number.
    If the specified function with the name given is not found in the .DLL then it returns NULL.
    The returns value from the function need to be collected in to appropriate pointer variable. This is when the mpusbapi.h (without underscore) comes to use. Microchip has done all the work in this case. The author of MPUSBAPI.DLL created this file keeping in mind the situation. This file has all the required pointer declarations for all the functions supported by DLL and this file need to be included in to the appropriate source files as required so that those declarations need not be made again.

    4.3 FreeLibrary():
    This function is used to close the .DLL library that is opened with LoadLibrary.

    SYNTAX:
    BOOL FreeLibrary( HMODULE hModule );
    The hModule argument what is returned by LoadLibrary is used as argument here. This function need to be called at the end of the program or for unloading the library from memory.


    MPUSBAPI.DLL:


    5. MPUSBAPI.DLL

    This is the PC side driver file, that communicates with the Demo Firmware on PICDEM FS Demo Board. A custom driver file is required when the a Custom Device Class or Vendor Specific Device Class are implemented on the device. For understanding more on device classes, please refer to USB Basics - Part II (How USB Devices are designed and developed?) It communicates with lower level driver mchpusb.sys which in turn communicates with the bus drivers of USB for USB data transfers.

    The MPUSBAPI.DLL provides functions that communicate over an
    end-point
    . Again to understand what is end-point refer to USB Basics - Part II (How USB Devices are designed and developed?). For now we can safely assume end-point as a buffer to which both PC application as well as the device has access.

    The MPUSBAPI.DLL refers the end points with string names. Example: "\\MCHP_EP1" refers to end-point 1 buffer. An end point can be IN end-point or OUT end-point or both.

    The terms IN and OUT are with respect to the HOST or PC. So, always a PC application writes to OUT end-point and the devices read from an OUT end-point. Similarly, the HOST reads from IN end-point and devices write to an IN end-point. The Demo firmware implemented 2 end-points in it. One is Control end-point which will be used by the OS and BIOS for configuring the device. The other end-point implemented is "MCHP_EP1" which is both IN and OUT end-point. The second end-point uses Bulk transfer.

    This DLL provides following functions:
    1. DWORD _MPUSBGetDLLVersion(void)
    This function will retrieve the version number of the DLL.
    2. DWORD _MPUSBGetDeviceCount(PCHAR pVID_PID)

    This function takes the pVID_PID (Vendor ID and Product ID) string as an argument and returns the number of devices with that specific Vendor ID and Product ID.
    If the VID is 0x04d8 and PID is 0x000c, the pVID_PID string will need to have a the value as "vid_04d8&pid_000c"
    3. HANDLE _MPUSBOpen(DWORD instance, // Input PCHAR pVID_PID, // Input PCHAR pEP, // Input DWORD dwDir, // Input DWORD dwReserved); // Input

    This function returns a handle to the end-point. The argument instance is used for passing a zero based index. This index value is based on the number of devices returned by MPUSBGetDeviceCount().


    pVID_PID is the VID and PID string as explained above.
    pEP is the name of end-point something like "\\MCHP_EP1".
    dwDir based on the end-point IN or OUT direction, MP_READ or MP_WRITE need to be passed as argument. dwReserved For future use.

    This function returns a HANDLE to the end point opened which will be used by other functions. If no device is found, returns NULL. Check for NULL.
    4. DWORD _MPUSBRead(HANDLE handle, // Input PVOID pData, // Output DWORD dwLen, // Input PDWORD pLength, // Output DWORD dwMilliseconds); // Input

    This function is used to read from an IN end-point. It uses the handle returned by _MPUSBOpen function. The _MPUSBOpen function need to open this end point, with MP_READ as Direction (dwDir) argument.
    pData is pointer to buffer.
    dwLen size of data to be read.
    pLength size of data actually read.
    dwMilliseconds Total wait time.

    Returns 1 on SUCCESS.
    5. DWORD _MPUSBWrite(HANDLE handle, // Input PVOID pData, // Input DWORD dwLen, // Input PDWORD pLength, // Output DWORD dwMilliseconds); // Input

    This function is used to write to OUT end-point. It uses the handle returned by _MPUSBOpen function. The _MPUSBOpen function need to open this end point, with MP_WRITE as Direction (dwDir) argument.
    pData is pointer to buffer.
    dwLen size of data to be written.
    pLength size of data actually written.
    dwMilliseconds Total wait time.

    Returns 1 on SUCCESS.
    6. DWORD _MPUSBReadInt(HANDLE handle, // Input PVOID pData, // Output DWORD dwLen, // Input PDWORD pLength, // Output DWORD dwMilliseconds); // Input
    Used in Isochronous transfer/ Interrupt transfer. Refer to _mpusbapi.cpp for more details.
    7. BOOL _MPUSBClose(HANDLE handle);
    Used to close the handle opened by the _MPUSBOpen function. Need to be called before application exits. Otherwise the device may not respond properly, if the application is re-opened.


    NOTE: The functions in the DLL has underscores prefixed to them.

    6. A look at the Demo Firmware Source Code


    Now, we know what are all the functions on PC side are available in Microchip DLL(MPUSBAPI.DLL). So, lets take look at the firmware code in Demo example which is in C:\MCHPFSUSB\fw\Demo\ folder. The files which are of interest now are main.c and user.c.

    The main() function in the main.c is starting point of the application. This function has an infinite while loop which inturn calls the function ProcessIO(). The ProcessIO() function is implemented in user.c and it calls another function called ServiceRequests(). This is a general structure adopted by Microchip Firmware library for USB.

    The ServiceRequests function handles the commands sent by the HOST (PC) application, using the _MPUSBRead and _MPUSBWrite calls. There is a union called DATA_PACKET in user.h. This union comprises many structures that help in interpreting the data received over USB.

    When using the Demo application, the format of data transfer seems to be,

    1. CMDByte , DATA LENGTH , [BYTES...]

    2. CMDByte , LED NO. , ON(1)/OFF(0)


    So, in the above format the data will be filled by the Host application and transmitted. The firmware interprets the commands received from host, and it will perform actions depending on what the host sends. The commands are listed in C:\MCHPFSUSB\fw\Demo\user\user.h file. The Host side application need to match these commands. More commands can be added and the Demo application can extended by adding more code in ServiceRequests() function.


    7. VC++ Example

    Download the VC++ Example by clicking here.

    In this example there are two files that need to be looked at.

    7.1. PICConnector.h and PICConnector.cpp: In these 2 files I implemented a simple wrapper class which invokes the functions from MPUSBAPI.DLL. The LoadDLL() member function of PICConnector class need to be called and it uses the Win32 API LoadLibrary(), GetProcAddress(), and FreeLibrary() to load the MPUSBAPI.DLL. Take a look at the source code while reading this portion. When the GetProcAddress call is made, note that the function names are passed with an underscore and the return value is assigned to corresponding function pointer. The function pointers are declared in mpusbapi.h file which is in the project folder.

    Once this DLL is loaded, the Open() and Close() functions can be called to open the pipes on end-point 1 of device with index 0. These functions use the MPUSBOpen() and MPUSBClose() functions internally. Also, take a look at the error checking that is done in these files. This code is designed to work only with the first connected device, which will have an index of 0. But by modifying the code, more than one device can be handled.

    In the Open() function, before calling MPUSBOpen(), the function MPUSBGetDeviceCount() is called with the vid_pid argument. This function returns the count, and if the count is 0, then it means no devices are connected to the PC. This is another error checking mechanism that can be used.

    The SendReceivePacket() function is responsible for actual data transmission. This function makes calls to both MPUSBWrite() as well as MPUSBRead(). The MPUSBRead() is called as soon as MPUSBWrite() is invoked. What it means is, as soon as the PC application sends a command, it is also expecting a response. You can see in the firmware that, after receiving the command and data, there is a response packet sent by the firmware which includes the command bytes in it. It is a kind of acknowledgement implemented in the Demo application. And all applications does not require to implement this feature. So, there can be independent calls to MPUSBRead and MPUSBWrite functions.


    7.2. VCPICUSBDemoDlg.cpp and VCPICUSBDemoDlg.h: The cpp file, implements 3 event handler functions. They are, OnGetVersion(), OnLed3() and OnLed4(). Take a look at the code of these functions.

    Here I will explain the OnGetVersion() function.


    The m_PICConnector is a object of PICConenctor class which loads the MPUSBAPI.DLL, created in the CVCPICUSBDemoDlg class.

    Step A: In this step the pipes on end-point 1(MCHP_EP1) are opened by calling the Open() function. This function inturn calls MPUSBOpen on MCHP_EP1 for both OUT and IN pipes and stores the handler values in two variables, myOutPipe and myInPipe. Take a look at how the calls are made in Open function.

    Step B: In this step two buffers are declared. The length of an bulk endpoint can not exceed 64 bytes in Full-Speed USB. So, the buffer length for both OUT and IN pipes is 64 bytes. But actually we will be transmitting less number of bytes compared to the buffer size.

    Step C: In this step, the Demo Application command(READ_VERSION) is defined. Take a look at the user.h file in the Demo firmware. The value of the command READ_VERSION is mentioned as 0. Then the send_buf is being filled with the command and the data length. When firmware receives this command, based on the command it interprets remaining fields.

    Step D: SendReceivePacket is called in this step. The send_buf which is populated in the previous step with the command and data fields is transmitted in this step, at the same time, as this command is retrieving version information, the pointer to receive_buf and expected length which is 4 are passed as arguments.

    The ServiceRequests() function in the firmware processes this command and fills the response data. When the firmware sets the counter to a non-zero value, the USB stack will transmit the buffer back to Host.

    Step E: In this step, the received data is verified if it is generated by the firmware correctly.

    Step F: As the operation is complete, both IN and OUT pipes are closed in this function.

    Here I am stopping this article. And this article showed how to interact with Demo firmware on Microchip PICDEM FS USB Board using VC++.

    Source Code for this article can be found here.