Wishing you all a Happy and Prosperous New Year 2009
Dec 26, 2008
Have you came across MojoPac?
How do I burn DVDs onto USB/Thumb ?
A Jewelry Box with USB and Fingerprint Authentication and Security
Dec 24, 2008
USB Drivers for DOS - USBASPI.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.
usbaspi.sys and usbcd.sys available at:http://panasonic.co.jp/pcc/products/drive/cdrrw/kxlrw40an/driver/kxlrw40an.exe
di1000dd.sys available at: http://www.stefan2000.com/darkehorse/PC/DOS/Drivers/USB/mhairu.zip
How to Use the NTFS File System With USB Drives
XEM3050 - Xilinx Spartan-3 FPGA Integration Module
Download Portable Office Suite (Openoffice 3.0) to your USB Thumb Drive/ USB Flash Disk
Dec 23, 2008
USB Cup Warmer
Dec 16, 2008
Intel Developers Demo USB 3.0 Throughput On Linux
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.
Freescale Semiconductor’s MC9S08JM16
Dec 12, 2008
25 Miles USB Cable??? Do you think it is possible? See below.
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
Nordic Semiconductor nRF24LU1+ USB dongle single chip system
Dec 9, 2008
Super Speed USB Logo and Cable Details - USB 3.0
USB over IP Capabilities for your USB device. Silex introduced SDKs for network sharing of USB devices. It is called Silex Virtual Link SDKs.
A USB Beverage Chiller?
What to do with small memory size USB Flash Drives
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
Amazing Tiny 8GB Pico USB drive
LaCie USB Speakers
Nov 25, 2008
Agilent Technologies Announces USB 3.0 SuperSpeed Physical Layer Compliance Test Application
Nov 24, 2008
Using MPUSBAPI.CPP directly instead of MPUSBAPI.DLL
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.
- Create a Win32 Console application as an Empty Project.
- Create main.cpp file and add it to the project.
- 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.
- 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)
- 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.
- 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".
- 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). - 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
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
NOTE
The DLL need to be recompiled by adding _stdcall in place of _cdecl to all exported functions.
Ok, lets move on now.
- Public: This keyword is used to indicate that the function declared is public function which can accessed through out the VB program.
- Declare: Used at module level to declare references to external procedures in a dynamic-link library (DLL).
- 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.
- 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.
- 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 | Private] Declare { 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.
[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
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
List of USB Protocol & Bus Analyzers (that come in form of Hardware+Software)
Analyzer | Description | Image(If Available) |
MQP Electronics Packet-Master USB480+ | Description:
| |
MQP Electronics Packet-Master USB480 | Description:
| |
MQP Electronics Packet-Master USB12 | Description:
| |
Ellisys USB Explorer 200 | Description:
| |
Ellisys USB Tracker 110 Recommended | Description:
| |
Wireless USB Explorer 300 Wireless USB Protocol Analyzer | Description:
| |
USB Ver.2.0 Bus Protocol Analyzer SB-2020 | Description:
| |
CATC USBTracer/Trainer™ Protocol Verification System | Description:
| |
CATC Advisor™ Protocol Analyzer | Description:
| |
CATC USBMobile™ Protocol Analyzer | Description:
| |
Beagle™ USB 12 Protocol Analyzer | Description:
| |
Beagle USB 480 Protocol Analyzer | Description:
| |
CATALYST Conquest™ Series USB Protocol Analyzers | Description:
| |
CATALYST SBAE Series, Universal Serial Bus (USB) | Description:
| |
USB2 SnooperTM (USB 2.0 Bus Analyzer) | Description:
|
Nov 22, 2008
Interacting with Microchip Full-Speed USB Demo Board using Visual Studio Tools - VC++ 6.0
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.
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.
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.