Wishing you all a Happy and Prosperous New Year 2009


Nov 24, 2008

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.

    No comments: