USB HID Template for Visual Basic 2005/2008/2010

Published on 29 November, 2010

Introduction

With the decline of serial and parallel ports from modern computers, electronics hobbyists are turning more to utilizing USB (or stick with old computers for their legacy ports). Unfortunately, unlike serial and parallel ports, USB is far from simple and so it can be daunting to try to develop hardware and software for it. However, there are many hardware and software solutions that make developing USB device much simpler.

Some PIC microcontrollers now come with a USB Serial Interface Engine (SIE) that handles the very low level parts of the interface. However, writing firmware to work with the SIE can still be a difficult task. Luckily, many PIC compilers come with USB libraries that work out of the box and are dead easy to use. The code generated by these compilers tends to produce a USB Human Interface Device (HID) as these devices do not require custom drivers to be written because Windows has them preinstalled. However, you still need to write your own PC software to read and write data from your USB device. This article shows you how to do this.

Visual Basic Template

The Visual Basic template, which you can download at the bottom of the page, generates the basic code framework that is needed to interface with your USB device. All you need to do is set the VID, PID and buffer sizes going into and out from the PC. After that you’re ready to read and write data.

To give credit where credit is due, I did not write the code that is in the template – the code is based on the code generated by the EasyHID application from Mecanique and modified for Visual Basic 2005 by Steve Monfette. I modified his code a little, wrote some documentation and packaged it into a VB template.

mcHID.dll on 64-bit Windows

mcHID.dll is a 32-bit DLL and so can only be linked with 32-bit applications. Since all 64-bit versions of Windows come with the WOW64 emulator to run 32-bit applications, mcHID.dll will work on a 64-bit operating system but only if your application is compiled as 32-bit/x86. If you receive runtime errors such as “An attempt was made to load a program with an incorrect format” or similar messages, then make sure that you are not compiling your program to the “x64″ or “Any CPU” configurations. “Any CPU” configures your program so that it runs as a native 32-bit application on 32-bit Windows and runs as a native 64-bit application on 64-bit Windows. This means that the same executable compiled using “Any CPU” will work fine with mcHID.dll on 32-bit Windows, but will fail on 64-bit Windows. Make sure to compile using the x86 configuration.

Installing

Installing the template is simple. Download and extract the archive and you will find two files: USBTemplate.zip andmcHID.dll. Copy mcHID.dll to your windows\system32 folder and copy USBTemplate.zip (copy the actual zip file – do not extract it) to your My Documents\Visual Studio [2005/2008/2010]\Templates\ProjectTemplates.

Using the Template

After installation, load up Visual Basic 2005/2008/2010 and create a new project. When the New Project dialog opens, you should see the USBTemplate option at the bottom.

Select it, give your project a name and then click on OK. Visual Basic creates the basic code framework for you.

The following files are created and can be found in the Solution Explorer:

  1. frmUSB: This is the main form where USB communication takes place.
  2. mcHIDInterface: Contains the underlying code.
  3. HOT TO USE: Contains instructions on how to use the template.

The only file which you need to modify is frmUSB.

Updates

2011/03/06: Modified the declaration of the PID and VID in the main form from Short to Integer (Thanks for Fred Schader).

Download

The template and the DLL file can be downloaded below:

USB HID Template for Visual Basic 2005/2008/2010

79 Responses to USB HID Template for Visual Basic 2005/2008/2010

  1. Fred Schader says:

    I believe that there is an error in the code. The product ID is specified as a short but it will not take a product ID higher than 32767. I recently got a PID from Micrichip that was in the 64k range and to get the program to work had to declare the PID as an integer. Not sure if this also applies to the VID.
    Thanks for the help getting this to run on W7 with the x86 vs any CPU comment

    • Amr Bekhit says:

      Hi Fred,

      Thanks for pointing that out. Yes, there is indeed a problem with the code. The PID and VIDs are both 16-bit values, hence the use of Short for the variable declaration. However, because Short is a signed 16-bit value, its range is 32767 to -32768. Changing it to UShort or Integer (as you have done) solves the problem.

      I will update the template with the corrected code.

  2. Mike says:

    I can’t get this to communicate.

    I have set VendorID, ProductID and buffers correctly. When I check it alwasys returns a handle of “0″. I am trying to connect to a Pic 18F4550. I can talk to it through the Hid terminal that comes with MikroE development environment. I have your template running in Visual Studio 2005. It runs without error but it doesn’t communicate.

    Thank you in advance for your comments.
    Mike

  3. John in Ottawa says:

    Just started using this template, a great resource! In my application, I will be tracking up to 10 identical HID devices plugged into a USB hub. I don’t mind tinkering with the code, but would appreciate any advice you can share or gotchas to avoid.

    Thanks
    -john

    • Amr Bekhit says:

      Hi John,

      Sorry for not getting back to you earlier. It is possible to use the template to talk to multiple identical devices.

      At the moment, the code assumes that there is only one device. In any function calls that require a device handle (e.g. hidWrite, hidSetReadNotify) the code simply retrieves the handle by calling hidGetHandle. This will always retrieve the handle of the first device with a matching VID and PID. If you have a look at the OnChanged function in frmUSB, you will see that the hidSetReadNotify function uses the handle returned by hidGetHandle, which means that the OnRead event will only get called when data is received from the first device you plugged in.

      In order to modify the code to allow you to communicate to multiple devices, modify the OnPlugged function to add the matching handle to an array or list somewhere in your code. Do the same for the OnUnplugged function but remove the matching handle from your array. That way, your array will always contain a list of the handles of the currently plugged in devices. For example, declare a list at the top of your form somewhere:

      Dim USBHandles As New List(Of Integer)

      Now modify the OnPlugged and OnUnplugged functions as follows:

      Public Sub OnPlugged(ByVal pHandle As Integer)
      If hidGetVendorID(pHandle) = VendorID And hidGetProductID(pHandle) = ProductID Then
      ' ** YOUR CODE HERE **
      USBHandles.Add(pHandle)
      End If
      End Sub

      Public Sub OnUnplugged(ByVal pHandle As Integer)
      If hidGetVendorID(pHandle) = VendorID And hidGetProductID(pHandle) = ProductID Then
      hidSetReadNotify(pHandle, False)
      ' ** YOUR CODE HERE **
      USBHandles.Remove(pHandle)
      End If
      End Sub

      Finally, modify the OnChanged function to enable read notifications for all your plugged in devices:

      Public Sub OnChanged()
      For Each pHandle As Integer In USBHandles
      hidSetReadNotify(pHandle, True)
      Next
      End Sub

      You should now be able to send data to your devices individually by using hidWrite (not hidWriteEx). When your devices respond with data, OnRead will be called.

      I will be modifying the USB Template to incorporate these changes as this makes it much more generic and useful.

  4. Robert Lowe says:

    I am having trouble sending data from PC to the PIC.
    I use ‘hidWrite(VendorID, ProductID, BufferOut(0))’ but the VB program hangs. (stops working)
    Passing data from Pic to VB works OK.
    Any ideas would be appreciated.

    Thank you
    -Robert

    PS: Could not find ‘hidWrite’ routine in the template.

    • Amr Bekhit says:

      Are you still having problems? Can you get in touch using the Contact page? I’d like to have a look at your code.

      Regarding hidWrite, the function is available in the template and does indeed work – you can get the handle of the device from the OnPlugged routine.

  5. John in Ottawa says:

    Thanks Amr. Actually, your timing was great as your response confirmed the solution I had cobbled together.

    Due to the number of devices (6), I created a class for the device, placed the buffers and DataIn in that class as well as the pHandle, Serial and related stuff, and created a list to add and remove the elements with plug and unplug respectively. That way I don’t mix up data streams when interrupts come in. I had also modified away from the ‘Ex’ versions of the calls, which works as advertised.

    My thinking ran that, as long as I had separate datain and buffers, I should not have collisions when multiple devices were responding during a multi-part message – I would just route the data to the data in and buffer for the class instance and it should work.

    I did find that I needed to use a timer running a polling routine so I can hear from more than just the head of the pack. It works great as long as all of the devices are connected before I start the application and I don’t remove one until I shut down. For some reason notification gets lost for the device next to the port that has a plug or unplug event. I’ve not sure if the handles are subject to change at this time.

    Is it possible for the pHandle for a connected device to change when another is disconnected?

    I also note that my devices are dual registered (Windows XP). One set of handles has the serial number, the other the long integer Handle assigned by the system. Is there a way to access the serial number based handle, or do we need a different DLL for this? Alternately, can you help me decode the text and length requirements of the hidGetSerialNumber method?

    Thanks again for your support. Great to have this resource available?

    -john

    • Amr Bekhit says:

      Hi John,

      Glad to hear that you’re making progress. I’ve done some more testing and what I’ve found is that every time you plug in or unplug a device, the OnChanged event gets called and the read notifications for all devices get removed. If you use hidGetItemCount and hidGetItem functions to list all of the HID handles you will find that they will completely change everytime a device is plugged or unplugged. If you modify the OnChanged function to scan through the list of new handles, identify the ones that match your VID and PID (remove the code that does that from OnPlugged) and reenable their read notifications, then you will continue to get read interrupts for all your devices.

      Assuming that everything described above is working as it should, then it’s obvious that you can’t use the handles as unique identifiers. It certainly seems possible to use serial numbers if you can modify your descriptor to add one in (I’m looking into that).

  6. John in Ottawa says:

    Oops – wrong keyboard – the ? should have been a !!

  7. John in Ottawa says:

    I have a bit of an update. It appears that, though I can see the new HID handle, set its readnotify to true and test that it is indeed true, I can’t get the interface to pass data from it.

    I have found a workaround, though. In the event of an unplug, I clear all of my buffers, clear my device list, then disconnect from HID, followed by a reconnect. The reconnect triggers the Plugged routine which populates my screen and seems to find all of the new handles.

    Now, this might pose problems for a history log, but I think I can deal with that by simply referencing the history log in a csv file by serial number.

    Does this approach raise any flags with you?

    • Amr Bekhit says:

      Hi John,

      I too have experienced the same behaviour as you: if you clear your list of handles and repopulate it with new ones you can continue to communicate with your devices. I’m currently looking into adding a serial number to the descriptor in mikroC so that I can continue to identify my devices when the handles change.

  8. Jonathan says:

    Hi,

    I have the same problem of Robert Lowe (message 4.)

    I can’t write on my PIC from the VB interface…

    What’s the solution ?
    Thanks

  9. luis says:

    Hi,
    in case of n. 1 Hid with different endpoint
    -Endpoint 81, in 1
    -Endpoint 01, out 1
    -Endpoint 82, in 2
    -Endpoint 02, out 2
    -Endpoint 83, in 3
    -Endpoint 03, in 3
    WHAT TO DO ????
    What’s the solution?
    Thanks

  10. Luis says:

    Sorry if I talk about something elsr, but, referring to reply n. 3 (multiply hid): Every hid can have different endpoints. Every endpoints can transmit packets of different bites. Usually with mcHID.dll you can read and write only one endpoint. The question is: if you have more endpoints, how should you modify mcHID.dll in order to manage all of them? Many greetings, thanks a lot! Luis

    • Amr Bekhit says:

      Hi Luis,

      HID devices with multiple endpoints are not something that I have worked with previously. Looking through the list of functions in mcHID.dll, there does not appear to be any way of specifying which endpoint to communicate with.

      However, If you have a look at the Visual Basic code for reading and writing, you will notice that the first byte of the read and write buffers is always 0 (report ID). Perhaps changing this number could allow you to communicate with multiple endpoints, with the number specifying the endpoint number?

  11. Luis says:

    Hi Amr,
    I noticed the “report ID always set to 0″.
    If Report ID 0 is not sent, the transmission is not performed.
    Using a USB sniffer, the microcontroller sets correctly the following endpoints:
    - Endpoint-81, in 1
    - Endpoint-01, out1
    - Endpoint-82, in 2
    - Endpoint-02, out2
    - Endpoint-83, in 3
    - Endpoint-03, out3
    81,01,82,02,83,03 are the addresses.
    I just have to do some testing and I will tell you the result.

    Thanks

    Luis

  12. Luis says:

    hi,
    …unfortunately are not able to work with different endpoint….

    Luis

  13. Dear Amr,
    I am trying to use your template and am having problems. I seem to be able to connect ok. I am getting OnChanged events and OnPlugged events. However, I can’t seem to be able to write to the device.
    When I execute “hidWriteEx(VendorID, ProductID, BufferOut(0))” and use a USB device monitor, I see nothing happen. When I execute “hidWriteEx(VendorID, ProductID, BufferOut(1))”, I see some activity, but not enough – I see 2 bytes go out, not the 3 I had thought I was passing. Also, I don’t get a response (probably because not enough is being passed out…)
    So I have a few pointed questions beyond “help”.
    1) How do I determine the correct value for BufferOutSize? Is it the number of bytes I am sending + 1? (ie. I need to send the device “C0 03 12″).
    2) How do I determine the BufferInSize? Is this based on the expected response from the device?
    3) Do I need to interate through the BufferOut array?

    Thanks

    Kevin

    • Amr Bekhit says:

      Hi Kevin,

      - 1&2: The size of the buffers transferring data in and out of the PC are fixed and should match the sizes of the IN and OUT buffers of your USB device, as determined by the device’s descriptor.
      - 3: I’m not really sure what you mean. You will probably need to iterate through it to fill it with data, but then you just need a single call to hidWriteEx to transmit the buffer contents.

      What is your USB device? Did you develop it yourself or are you using an existing HID device?

      Amr

  14. Amr,
    Thanks for the response. I am trying to work with a USB/HID RFID reader. I have the API manual for the reader, so know what to send and what to expect back… My code at present (to send soemthing) is:

    BufferInSize = 64
    BufferOutSize = 3

    ReDim BufferIn(BufferInSize)
    ReDim BufferOut(BufferOutSize)

    BufferOut(0) = 0
    BufferOut(1) = CByte(Convert.ToInt32(“31″, 16))
    BufferOut(2) = CByte(Convert.ToInt32(“03″, 16))
    BufferOut(3) = CByte(Convert.ToInt32(“01″, 16))

    hidWriteEx(VendorID, ProductID, BufferOut(0))

    When I do the above, nothing happens (I am using the “Device Monitoring Studio” to watch comms between the device and the computer.

    If I change the hidWriteEX index from 0 to 1, I see the 2nd and 3rd bytes of data go out, but not the 1st.

    By putting in a message box at the end of the code, I can show that the “stall” is occuring at the hidwriteex code, because I never get the message box to show.

    Thanks

    Kevin

  15. Oh, and it is a purchased device, I am using and when I say hidwrite index, I am referring to the index number of “BufferOut” in the hidWriteEX function.

    Kevin

    • Amr Bekhit says:

      Hi Kevin,

      Hmm…I’m wondering if the configuration of your RFID reader might not be compatible with mchid.dll. Can you give me the specific part number of this reader? I’d like to have a quick skim through the datasheet myself.

      Also, there should be no need to ReDim the buffer arrays – simply set the constants at the top of From1.vb to the sizes of your buffers, although there should be nothing wrong with what you’ve done above.

      • kevin berisso says:

        Amr

        The unit is called the RFID Me ( http://www.mti.com.tw/rfidme/). If you send me an email to autoid@ohio.edu, I van send you the API doc for the reader.

        I am wondering if the unit has something weird as well. I know that their software, and another third party have successfully worked with it, but I am not a super strong programmer and wonder if it is just that.

        The resin was because the different commands result in different sized responses from the device. I was hoping that the wproblemwas the code was waiting for more from the buffer.

        Kevin

  16. Mike says:

    I really like mcHID.dll. I’m using it to communicate with several different devices. I would like, however to write a VB class library to communicate with my devices, rather then a form class. I’m not real strong with VB, and was wondering how I can set a ‘hook’ to my class library rather then a form (phostwin)? Any hellp would be appreciated.

    • Amr Bekhit says:

      Hi Mike,

      Hmm…I’m not sure you’re going to be able to get away without using a form. I think that mcHID needs a form handle so that it can perhaps capture and send Windows messages to the form as a way of sending and receiving data from it (have a look at WinProc).

      I would be very interested to hear from you if you find otherwise.

      Amr

  17. Nawar says:

    Hi Amr,
    I just wanted to say thanks a lottttt
    I’ve been trying to communicate with the USB for two weeks now using C#
    then I decided to switch to VB and I found your site and it’s the best

    Thank you
    Nawar

  18. Dustin says:

    Hey Amr,
    I am a student at the University of Colorado at Colorado Springs. I am using your template to communicate my vb 2010 program to an arduino uno via series 1 XBee modules. Looking at your template it shows how to read data into the pc but not send data out. My vb program will be sending out data not reading any incoming data. (This is my first time using vb) Is there anyway you can show me an example code of a sub module for writing data from the pc to anything?

    Thanks for your time
    Dustin

    • Amr Bekhit says:

      Hi Dustin,

      If you want to send data to your USB device, use the HIDWrite or HIDWriteEx functions. The readme file in the template should show an example of their use.

      Amr

      • Dustin says:

        Hey Amr,
        Thanks for the response last time, I went back and read the read me file again and again and came up with this:
        Private Sub CamPostion1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        hidWriteEx(ByVal pVendorID As Integer, ByVal pProductID As Integer, ByRef pData As Byte) As Boolean
        ‘This function is used to send data to the USB device. It’s usage is very simple:
        ‘the BufferOut array (see above)
        ‘is filled with the data that needs to be sent (make sure to set BufferOut(0)=0).
        ‘After that, the function is called as follows:

        BufferOut(0) = 0
        BufferOut(1) = 0I
        BufferOut(2) = 1I

        hidWriteEx(VendorID, ProductID, BufferOut(0))
        End Sub

        The problem is that it is giving me expected errors in the hidWriteEx() expression. What I am trying to do is send a single number (when a button is clicked) with XBee to an Arduino Uno that is why the sub CameraPostion1_Click() called then hidWriteEx() is called after that. Any advice would be wonderful. Thanks for your time!

        Dustin

  19. Gc says:

    I was having a lot of trouble until I started using the template. I have been able to successfully create a form that can communicate with my microcontroller.

    Is it possible for you to make a template for console application or provide instructions to use mcHID.dll in a console application? I am not an advanced programmer in Visual Studio so I was unable to figure it out. You current template works mostly based on events which is great when using it as part of a form. I am trying to get it to work in a linear fashion such as:
    Check if device connected->Send Data->Receive Data

  20. luca says:

    Wonderful, incredible and amazing.
    Only to download and very easy to use. It works always. Thank you.
    I use from vb.net express 2010. Only since connectToHID is a boolean function with no return value I have a warning in compilation.
    Please suggest me an idea to fix this (transforming in subroutine could be?)
    Best Regards
    Luca

  21. Manal says:

    i need to transmit data from micro controller pic18f4550 to laptop via usb. at first just run ur program i had build errors like
    Error 2 ‘Sub Main’ was not found in ‘$safeprojectname$.My.MyApplication’.

    Error 3 Character is not valid. C:\Users\MMM\Downloads\USBTemplate-2011-03-06-16-34-00\USBTemplate\My Project\Application.Designer.vb 35 34 USBTemplate1

    Error 4 ‘Settings’ is not a member of ‘My’. C:\Users\MMM\Downloads\USBTemplate-2011-03-06-16-34-00\USBTemplate\My Project\usb_vbb.vb 34 13 USBTemplate1

    Error 5 Character is not valid. C:\Users\MMM\Downloads\USBTemplate-2011-03-06-16-34-00\USBTemplate\My Project\usb_vbb.vb 67 55 USBTemplate1

    please help me to understand how solve these problems

  22. azer says:

    hi if i want to create a button that send “111″ to my pic
    and an ather button that read continously what the pic send
    what is the code that will let me do that

    thank you for your eventual help

  23. rony galo says:

    excelent
    I´m trying to build a vendor device,,,,will be usefull

  24. lcpoon says:

    Hi,

    I have two HID devices (same PID and same VID) connected to the host. I want to send the command to one of the HIDs. Which API to be used?

  25. alfonso says:

    hi, i didn’t understand how to send a byte on usb port if iwont to do it which function have i to use?can you make an example for me tanks

  26. alfonso says:

    hi i didn’t undrstand how to use hidusb.
    If i want to send a byte on usb port which function have i to use hidwriteex or hidwrite? can you write for me an exsample code please? tanks

  27. Erika says:

    Hi, I’m Erika, I’m peruvian so i hope that you can understand this.
    I’m trying to comunicate a freescale whith my computer by USB port, and i need to get data from the freescale using Visual Basic, maybe you can help my with this, jejeje , im recently knowing more about VB, and i need help please =D

  28. Julito 3A says:

    Wow!!! i was looking for this for a long time!!! time to study vb 2010 and migrate from vb6 ^^ … btw does this lib supports bulk transmissions ??

  29. Vincent says:

    This is a v useful sample.
    I am trying to interface with a PC mouse
    I can connect and disconnect ok.
    Am not sure I have set up the right buffer size.
    I don’t seem to be able to read Buffer(1). The OnRead is never called.
    Is this because Windows takes control of the actual device and so block other app to read from it?
    Any idea,
    Cheers.

  30. reltkaine says:

    thans for these tutorial i was able to connect pic18f4550 mikroC pro

  31. stephen says:

    Hi and thanks for the great tutorials.
    I used your template to try and connect to a PIC 18F2550.
    I can’t seem to be able to connect to the PIC although both VID and PID match the descriptor in my MikroC project.

    Do you have any idea what could cause that?

    Also, I am getting an error in VB 2010 when I try to send some data to the PIC. I create a simple button in the form which only does:
    BufferOut(1) = 255
    BufferOut(0) = 0
    hidWriteEx(VendorID, ProductID, BufferOut(0))

    the error (badformatimage..) says: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)

    It seemed pretty straight forward while reading your tutorial but I can’t figure out what I am doing wrong.
    Other than the same buffer size (which is 64 bytes) for both my descriptor and the VB form, is there anything else that must match in order for the communication to work?

    Thanks!
    Stephen

    • Amr Bekhit says:

      Hi Stephen,

      The error you’re getting is because your application is running as a 64-bit process and is trying to load the 32-bit mcHID.dll. Simply change your compile platform in Visual Studio from x64 or AnyCPU to x86.

      Amr

  32. Andrzej says:

    Hi – could you, please, help me to fix the following problem?
    I connected USB scanner the USB port and I modified VendorID to &HC2E and ProductID to &H206 as determined by USB scanner.
    When I unplug or plug this device, OnPlugged or OnUnPlugged functions are called.
    When scanning any code bar – OnRead function is never called.
    What should be the pMsg value to be tested in WinProc function instead of WM_HID_EVENT (which is good for NOTIFY_PLUGGED, or NOTIFY_UNPLUGGED and other cases)?
    Thank you in advance for your help,
    Andrzej

  33. TImothy says:

    I am battling with same problem as Andrzej. I can read from HID RFID reader. I can detect plugging and unplugging of the device. Whenever an RFID card is scanned, the Onread event is not triggered.

    I’ll appreciate your assistance.

    Regards,

    Tim.

  34. Fernando says:

    Hi, I have a problem. I cant get this to work under W7. When I test the solution under XP, it works ok. But under W7, when I add the reference to mchid.dll the VS popsup a message “Cant add reference… verify its a valid COM component” (this is a translation, something like that it says). What can be de the problem? I’m working with VB2008 Express.
    Thank you.

  35. Fernando says:

    Thank you Amr! That did it! Thanks for your fast response!

  36. Salman says:

    Hi,

    I am beginner at VB and I am using your code to communicate with PIC18F4550. As a previous comment said, I am facing problems.

    Public Sub hidWriteEx(ByVal pVendorID As Integer, ByVal pProductID As Integer, ByRef pData As Byte) As Boolean

    hidWriteEx(VendorID, ProductID, BufferOut(0))

    My compiler gives an error “end of statement expected” at “AS Boolean” statement. Please help me figure this out.

    Regards,
    Salman

  37. Arun Sharma says:

    First of all i want to thanks you..

    Your USB tempelate Saves my huge time..

    I had successfully sent data from PC TO USB

    but what i want is to receive data.
    How can i do so…
    I am not a good Programmer of Visual Basic.

    But still trying
    Here is my Code to send data from PC to usb

    Private Sub btn_Send_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_Send.Click
    BufferOut(0) = 0
    For Me.i = 1 To Len(txt_Data_to_Send.Text)
    BufferOut(i) = Asc(Mid(txt_Data_to_Send.Text, i))
    Next

    hidWriteEx(VendorID, ProductID, BufferOut(0))

    This is working absolutely fine…
    But My OnRead Function is not Working..

    I am Echoing Data what i sent but my Sent portion is working Properly but not the receive one..
    But doing some Research i came to a conclusion that my OnRead function never gets called..
    It gets called when i remove my USB Device

    Here is the Receive Function

    Public Sub OnRead(ByVal pHandle As Integer)
    ‘ read the data (don’t forget, pass the whole array)…
    MsgBox(“Reading From PIC”)
    If hidRead(pHandle, BufferIn(0)) Then
    ‘** YOUR CODE HERE **
    ‘first byte is the report ID, e.g. BufferIn(0)
    ‘the other bytes are the data from the microcontroller…
    For Me.i = 1 To BufferInSize
    MsgBox(USB_Data_Received)
    USB_Data_Received(i) = BufferIn(i)
    txt_Receive.Text = txt_Receive.Text & Chr(USB_Data_Received(i))
    Next
    ‘Data gets Printed in the Receve Window
    ‘Now clear the Buffer USB_Data_Receive
    For Me.i = 1 To BufferInSize
    USB_Data_Received(i) = 0
    ‘Clear the Buffer Before Exiting
    Next
    MsgBox(BufferIn)
    End If
    End Sub

    I have msgbox to know whether onread function gets called or not,
    it gets called when i remove my device..

    Pls reply me soon

    • Amr Bekhit says:

      Hi Arun,

      If your OnRead function is never being called, then your USB device is not transmitting data to the PC. Please make sure that your HID device is transmitting data to the PC. You could use the HID Terminal that comes with mikroC to test this.

      Amr

  38. Arun Sharma says:

    Hi!! Amr
    Thanks for your reply…

    I Checked my Code and it is working properly(mikroC one).

    And after few experiments i got this result..
    My OnRead() function is called but,
    what ever data i am receive from USB, i want it to be displayed on a Text_Box Present at VB Form..

    For this i have declared a array

    Dim USB_Data_Received(BufferInSize) As Byte

    Now My OnRead Function is as follow:-


    Public Sub OnRead(ByVal pHandle As Integer)
    ' read the data (don't forget, pass the whole array)...
    MsgBox("Reading From PIC")
    If hidRead(pHandle, BufferIn(0)) Then
    ' ** YOUR CODE HERE **
    ' first byte is the report ID, e.g. BufferIn(0)
    ' the other bytes are the data from the microcontroller...
    For Me.i = 1 To BufferInSize
    USB_Data_Received(i) = BufferIn(i)
    MsgBox(USB_Data_Received)
    'txt_Receive.Text = txt_Receive.Text & Chr(USB_Data_Received(i))
    Next
    'Data gets Printed in the Receve Window
    'Now clear the Buffer USB_Data_Receive
    For Me.i = 1 To BufferInSize
    USB_Data_Received(i) = 0
    'Clear the Buffer Before Exiting
    Next

    End If

    My this part is not working

    USB_Data_Received(i) = BufferIn(i)
    i.e i am not able to copy data from the USB Port, But i am getting the Data successfully

    Because when i Transmit “S” from the USB and use this statement in Visual Basic

    MsgBox(BufferIn(1)) –> get 83 ascii value of S

    MsgBox(Chr(BufferIn(1)) ) –> get “S”

    This means i am getting data propely,
    But i am not able to display that data on the Receive_Text_Box..

    I am new to Visual Basic thats why i don’t know how to do that..

    Pls reply me as soon as possible

    Thanks

    • -tE says:

      I have just begun to add an HID to a software I am developing. I am getting it to read just fine. You have to set the “Focus” to the textbox of the form you want to be filled.
      My question is reguarding only using the data I want from the string that is produced. I haven’t tried this download yet, but my textbox is being filled just by setting the focus to it. I want to be able to only use the name from the card for instance. Any ideas? Would the template that is here help do this?

  39. Hero7 says:

    I’m somehow lost I try an easy task with the template but nothing seems to work

    could someone show me a code for the onread section

    I don’t know if my 64bit OS is the problem I just need a valid code to test the template if not I have to find a 32bit OS.

    • Amr Bekhit says:

      What problems are you having? If you are getting error messages when trying to run the program on 64-bit Windows, then please read the section titled “mcHID.dll on 64-bit Windows” at the top of this page.

      Regarding reading data, the template already does most of the work for you. The OnRead function saves the data inside the BufferIn array – you just need to process the contents of the array as your application requires.

  40. Hero7 says:

    thanks for the answer
    I’m using VB express and for what I read ,I haven’t the possibility to choose something else then ANYCPU;I have to upgrade to an higher version of visual ; I’ll try with a 32 bit OS.
    thanks for the good work and support.

  41. Hero7 says:

    Finally I found how to change the target CPU; I was wrong in the end, sorry.

    for those who may be in the same case

    ” To target x86 in the express editions:

    Tools –> Options –> Projects and Solutions–>General Check “Show advanced build configurations”
    If “Configuration Manager” doesn’t show on the Buid menu, add it and click it.
    Active Solution Platform –> New –> Type or select the new platform x86 ”

    http://go4answers.webhost4life.com/Example/visual-basic-2008-express-edition-45272.aspx

    http://www.vbforfree.com/?p=418

  42. Hero7 says:

    a complement for 64 bit user’s
    don’t forget to Copy mcHID.dll to your C:\Windows\SysWOW64

  43. pablo says:

    HI, i hope somebody help me about a mcHID.dll problem.

    When I open de windows form. the usb connect correctly.
    When i close de windows form. the usb disconnect correctly.

    the problem, is when im trying close the connection in an other part of my code.
    the program is blocked and i have to stop debug and start again.

    does somebody knows what could be happened?

    thanks for help

    • Amr Bekhit says:

      How are you closing the connection? I wrote a test program that calls DisconnectFromHID() inside a button and that seems to work OK.

      • Pablo says:

        sorry Amr Bekhit.

        im use the same function than you DisconnectFromHID()

        it’s so strange cause when im close the form (with close button form) and call DisconnectFromHID fuction, works perfectly.

        but, when i just want to disconnect after some processes finished. the aplication blocked.

  44. need2know says:

    How to use mcHID.dll to send zero packet length data to the device?

    • Amr Bekhit says:

      I’m not sure about this. The hidWrite and hidWriteEx commands do not take any parameters that specify the size of the message. This would lead me to guess that they determine the buffer size from the device descriptor, thus meaning that the size of the messages sent to and from the device are fixed.

      I tried passing a single byte to the hidWrite command as follows:

      Dim ZeroMessage As Byte = 0 'Report ID is 0
      hidWrite(handle, ZeroMessage)

      Although this seemed to work (my devices indicated that they received a USB packet), I think hidWrite is sending more than one byte. For my test devices, the Buffer Out size is 64, and I reckon that after transmitting the contents of ZeroMessage, the function also transmitted the next 64 bytes in RAM that happen to be after ZeroMessage.

      Try it for yourself and let me know what you find.

      • need2know says:

        The codes do not work. I used USB trace software to capture the event and it does not send out zero-length packect. BTW, I’ll try using hid.dll and check if it works.

  45. need2know says:

    Is that possible to use mcHID.dll to send zero-length packet out to the device? If yes, can I have the codes?

  46. Anthony Lee says:

    Hi there,

    I just try out the template, so far it work fine for me, its my 1st try to use MCU USB function for my Project, really thanks a lot.

    Just some small info to share, I’m using a win 7 64bit, VB 2010, on my first try, I copy the dll file into my system32, all the code are unable to work, than I try to copy it into SysWOW64 folder, everything works fine.

    • Amr Bekhit says:

      Hi Anthony, glad you found the template useful.

      Regarding the dll, it will also work if you ensure the DLL is in the same directory as your executable. This is the method I recommend as all the files that your program needs to run are kept in the same place and not scattered about the system.

  47. daniel menendez says:

    Hi, I have found this material very interesting.
    I have followed the procedure to install the template, but when I create a New Project in Visual Basic 2008, I can´t see the USBTemplate icon in “My Templates”.
    Could you help me?
    Thanks you very much and best regards, Daniel

  48. daniel menendez says:

    In other words, I can´t see the USBTemplate option at the bottom.

Leave a Reply

Your email address will not be published. Required fields are marked *

*


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>