Ir ao conteúdo
  • Cadastre-se

Usb hid


Projetos_afg

Posts recomendados

Bom dia pessoal!

Estou desenvolvendo um gravador para AVR USB (que permite a gravação paralela e serial) usando o PIC18F2550 para a comunicação. O projeto está ficando legal, mas estou tendo dificuldades na parte de programação do computador.

Já encontrei um template usando a dll mcHID:

unit FormMain;

interface

uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs;

const

// input and out buffer size constants...
BufferInSize = 8;
BufferOutSize = 8;
type

// input and output buffers...
TBufferIn = array[0..BufferInSize] of byte;
TBufferOut = array[0..BufferOutSize] of byte;

// main form
TForm1 = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
FBufferIn:TBufferIn;
FBufferOut:TBufferOut;
function USBEvent(var Msg: TMessage): Boolean;
public
end;

var
Form1: TForm1;

implementation

uses
cUSBInterface,
cUSBInterfaceTypes;

const

// vendor and product ID constants...
VENDOR_ID = 6017;
PRODUCT_ID = 2000;

{$R *.DFM}

{
****************************************************************************
* Name : Create *
* Purpose : Create the main form *
****************************************************************************
}
procedure TForm1.FormCreate(Sender: TObject);
begin
Application.HookMainWindow(USBEvent);
Connect(Application.Handle);
end;
{
****************************************************************************
* Name : Destroy *
* Purpose : Free the main form *
****************************************************************************
}
procedure TForm1.FormDestroy(Sender: TObject);
begin
Application.UnHookMainWindow(USBEvent);
end;
{
****************************************************************************
* Name : USBEvent *
* Purpose : DLL message handler hook *
****************************************************************************
}
function TForm1.USBEvent(var Msg: TMessage): Boolean;
var
DevHandle:cardinal;
// TextBuffer:array[0..255] of char;
begin
result := False;
if Msg.Msg = WM_HID_EVENT then
begin
case Msg.WParam of

// a HID device has been plugged in...
NOTIFY_PLUGGED :
begin

// is it our HID device...
DevHandle := Msg.LParam; // handle of HID device in this message
if (GetVendorID(DevHandle) = VENDOR_ID) and (GetProductID(DevHandle) = PRODUCT_ID) then
begin
// add your code here, for example...
// GetProductName(DevHandle, TextBuffer, 256);
// ALabel.Caption := string(TextBuffer);
end;
result := true;
end;

// a HID device has been device removed...
NOTIFY_UNPLUGGED :
begin

// is it our HID device...
DevHandle := Msg.LParam; // handle of HID device in this message
if (GetVendorID(DevHandle) = VENDOR_ID) and (GetProductID(DevHandle) = PRODUCT_ID) then
begin
// add you code here
end;
result := true;
end;

// a HID device has been attached or removed. This event is fired after
// either NotifyPlugged or NotifyUnplugged.
NOTIFY_CHANGED :
begin
// get the handle of the device we are interested in
// and set it's read notification flag to true...
DevHandle := GetHandle(VENDOR_ID,PRODUCT_ID);
SetReadNotify(DevHandle,true);
result := true;
end;

// a HID device has sent some data..
NOTIFY_READ :
begin
DevHandle := Msg.LParam; // handle of HID device in this message
if (GetVendorID(DevHandle) = VENDOR_ID) and (GetProductID(DevHandle) = PRODUCT_ID) then
begin
// read the data - remember that first byte is report ID...
Read(DevHandle,@FBufferIn);

// process data here...
end;
result := true;
end;
end;
end;
end;

(*
if you want to write some data to the USB device, then
try using something like this...

// first element is report ID, set to 0...
FBufferOut[0] := $0;

// fill the buffer with some data...
for index := 1 to BufferOutSize do
FBufferOut[index] := index;

DevHandle := GetHandle(VendorID, ProductID);
Write(DevHandle,@FBufferOut);
*)

end.


Ele funciona legal até a parte de leitura do dispositivo (Read(DevHandle,@FBufferIn);). Ele retorna o 3º byte sempre com o valor 0x0C, sendo que era para estar zero(já testei outros programas prontos, e neles funciona legal).

Outra coisa que acontece é que depois de usar a função de leitura, quando eu encerro o programa, ele mostra um erro de violação de memória. Estou usando o windows 7 64 bits, mas já tentei compilar e rodar em um windows XP e deu na mesma.

Estou usando o Delphi 7.

Será que alguém tem um exemplo de programa desse tipo funcionando?

Link para o comentário
Compartilhar em outros sites

De uma procurada aqui no fórum,que postei vários links utilizando um ótimo componente que é nativo para Delphi,mas ensino como instalar no Borland c++,5,6 e RadStudio2007.

Postei os exemplos em Delphi e Borland C++.

posso te ajudar no firmware tambem pois tenho projetos programados (18F2550)em ASM ou C18.

Qualquer dúvida pergunte.

Link para o comentário
Compartilhar em outros sites

vtrx, esse componente matou a charada: http://www.4shared.com/folder/B6gjeIIG/_online.html

É até melhor, já que não precisa de uma dll. Ainda só testei a parte de conexão e desconexão de dispositivos, está funcionando bem legal. Em breve eu crio um tópico com o projeto do gravador. A primeira parte ele só grava no modo SPI, a segunda parte ele vai gravar em HVPP, para poder configurar aqueles fusíveis chatos que desabilitam a gravação pela SPI.

Muito obrigado pela ajuda!

Link para o comentário
Compartilhar em outros sites

Prezado aqui na empresa utilizamos o modo Hid com os pic 18f2550 e 18F4550funciona numa boa e no lado do Delphi eu mesmo adaptei o script que você postou acima como componente e funciona numa boa. Lembre-se que o Buffer[1] do delphi é o Buffer[0] do pic. Assim sendo caso no lado do pic seja por exemplo Bf[0] = xx; Bf[1]= x1; Bf[2] = x2 é de se esperar que no lado do Delphi seja BufferIn[1] = xx; BufferIn[2] = x1 e BufferIn[3] = x2; BufferIn[4] pode ser qualquer coisa inclusive lixo de memória uma vez que não foi inicializado nesse caso. Ok? Qualquer dúvida estou a disposição. Quanto ao acess violation o Delphi 7 ocorre isso com certa frequencia. Provavelmente a subrotina está sendo chamada após o término do programa. Tente implementar logo no início da subrotina USBEvent algo do tipo

If Application.Terminated = True Then

Exit;

Acho que deve resolver isso ai se precisar envie o código completo para que eu possa sugerir outras correções Ok? Att. Lucas

Link para o comentário
Compartilhar em outros sites

Na verdade instalei o componente que o vtrx me mandou, e agora funciona tudo corretamente, estou montando a primeira parte do projeto que consiste em usar o módulo SPI do PIC para ler e gravar o AVR.

Estou pensando em começar a usar uma plataforma mais nova, como o Lazarus, que além de ser uma plataforma de programação pascal gratuita, é bem parecido com o Borland Delphi.

Alguém tem algum material bom para começar a mexer no Lazarus?

Outra coisa, eu conheço vagamente a comunicação USB. Sei que se baseia no intercâmbio de pacotes, que é preciso o microcontrolador enviar um pacote de identificação, etc.

Mas eu gostaria de entender como funciona a porta USB do seu nível mais baixo até o mais alto. Como manipular as APIs do Windows para criar drivers para alguns tipos de comunicação, em que o HID não serve. Gostaria de entender como funciona esse protocolo por inteiro. Alguém poderia sugerir algum livro ou postar algum material bem completo?

Já baixei alguns documentos da usb.org mas é difícil de encontrar as informações que eu preciso.

Link para o comentário
Compartilhar em outros sites

  • 1 ano depois...

Por favor.

Por favor, preciso fazer meu PC (Windows) comunicar com um PIC18F4550 pela USB HID.

Construi a plaquinha e fiz um programa em Delphi utiizando o mcHID.dll utilizando o EasyHid.

Mas, gosto mais de utilizar o C++ Builder 6.

Peguei o seu exemplo, mas não estou conseguindo. Está apresentando erros.

Poderiam me ajudar?

Obrigado.

Wanderlei Fernandes Gabriel

[email protected]

Link para o comentário
Compartilhar em outros sites

Então, amigo, já tentei com o JVhidControllerClass, já tentei também usando as APIS do Windows (SetupDiEnum, SetupDiGet, ...) e, no C++ Builder 6, não consigo resultado positivo.

Só consigo em Delphi. Se você puder me passar ûm email eu zipo os códigosa e lhe envio...

É que eu quero fazer uma aquisição de dados, até já fiz a plaquinha que está funcionando, mas gostaria que fosse em C++ Builder 6. É que já tenho vários programinhas nesta linguagem.

Obrigado - [email protected]

Link para o comentário
Compartilhar em outros sites

vtrx, bom dia.

Desculpe incomodar, mas estou precisando muito fazer essa comunicação HID / C++ Builder6.

Bom, baixei o vosso exemplo para USB HID Borland C++ 6 e, quando vou seguir aquilo que você escreveu no Bloco de Notas, acontece o seguinte:

Salvo o Package1, Build, Install e não dá erros.

Pergunta se é para salvar as mudanças para o Project Package1. Salvei. Não apresentou erros. Aí, quando vou reiniciar o Borland C++ Builder 6, ele pergunta se quero salvar o Project1. Aí eu não salvo, pois penso que se eu salvar, eu vou salvar um Form vazio em cima de um Project1 que já existe. Correto? Saio então sem salvar o projeto Project1.

Bom, aí eu reinicio o Borland c++ Builder 6 e abro o Project1. Aparece lá o vosso Form.

Quando vou compilar aparece o erro: Error Reading Form Class TJvHidDeviceController not found. E, apresenta as possibilidades: Ignore ou Cancel ou Ignore All. Eu escolho Ignore All.

Desculpe, continuando:

Aí, escolhi Ignore All e ele apresenta o seguinte erro de Compilação: Error: FieldForm1->JvHidDeviceController1 does not have a corresponding componente. E pergunta: Remove Declaration? E apresenta as possibilidades Yes ou No ou Cancel. Se eu escolho No, ele compila e apresenta 13 erros. O primeiro erro:

Na linha: #include "JvHidControllerClass.hpp"

Unable to open include File 'JvHidControllerClass.hpp'.

E agora? O que eu faço?

Muito obrigado pela atenção,

Fernandes Gabriel

Ah, um detalhe:

Os arquivos .pas que eu adiciono no Package1 são:

DBT.PAS, HID.PAS, HidToken.pas, HidUsage.pas, JvHidControllerClass.pas, ModuleLoader.pas, SetupApi.pas e WinConvTypes.pas.

Está Correto?

Obrigado.

Link para o comentário
Compartilhar em outros sites

Tente o seguinte.

Quando abrir o meu projeto,delete o componente HID,no Form,e arraste um novo da paleta.

Se ainda não conseguir,desisntale qualquer componente de acesso HID e faça novamente.

NA primeira compilação,aparecerá erros em alguns arquivos,nesta hora voce deve 'comentar'(//)as linhas com erros que aparecerá nas units do componente até o erro desaparecer,então voce compila o projeto,fecha e salva as alterações para que as units do componente fiquem modificadas,assim não haverá mais erros.

PS:Acabei de refazer par atestar pois faz muito tempo que postei.

1-Coloque a pasta com o componente na pasta LIB do BCB.

2-"File->New->Other->Pacakge".

3-Mouse direito em 'Contains'e salve em uma pasta qualquer,eu escolhi o nome HID_K.

4-Mouse direito em 'Contains' e adicione (Add)todos os arquivos .pas(da psata do componente),voce pode usar Ctrl+A para escolher trodos o .PAs.

5-Depois,'Compile' e 'Install'.

Feche o BCB e reabra.

Na primeira vez vai aparecer o erros que mencionei.

Comente todos feche e salve.

Reinicie,deve estar ok.

OBS:Para refazer,desinstale o componente selecionando "Component","install Packages" e desmarque a caixa de seleção onde esta o componente antigo

Para instalar selecione "Component","Install Component",apague o "Search Path" e em "Unit File Name" voce seleciona todos oa .PAS.

Não se esqueça que se estiver usando o Win7,voce tem que selecionar a pasta de instalação do BCB6 e com mouse direito dar permissão de acesso a pasta toda.

Link para o comentário
Compartilhar em outros sites

Opa, começou a funcionar por aqui. Graças a Deus e ao vosso código.

Obrigado.

Na hora de compilar apresentou apenas 2 Erros:

static const Shortint SPFILENOTIFY_STARTREGISTRATION = 0x19;

static const Shortint SPFILENOTIFY_ENDREGISTRATION = 0x20;

Comentei os dois (//), compilei e, ..., começou a funcionar.

Obrigado.

VTRX, me dá mais uma ajuda? Estou envolvido com esse código abaixo há um bom tempo:

#include <vcl.h>
#pragma hdrstop
#include "Unit1.h"
#include <setupapi.h>
#include <alloc.h>
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
#define MY_DEVICE_ID "VID_0333&PID_0111"
HANDLE WriteHandle = INVALID_HANDLE_VALUE;
HANDLE ReadHandle = INVALID_HANDLE_VALUE;
GUID InterfaceClassGuid = {0x745a17a0l,0x74d3,0x11d0,0xb6,0xfe,0x00,0xa0,0xc9,0x0f,0x57,0xda};
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm1::BtnFecharClick(TObject *Sender)
{
Close();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::BtnConnectClick(TObject *Sender)
{
HDEVINFO DeviceInfoTable = INVALID_HANDLE_VALUE;
PSP_DEVICE_INTERFACE_DATA InterfaceDataStructure = new SP_DEVICE_INTERFACE_DATA;
PSP_DEVICE_INTERFACE_DETAIL_DATA DetailedInterfaceDataStructure = new SP_DEVICE_INTERFACE_DETAIL_DATA;
SP_DEVINFO_DATA DevInfoData;
DWORD InterfaceIndex = 0;
DWORD dwRegType;
DWORD dwRegSize;
DWORD StructureSize = 0;
PBYTE PropertyValueBuffer;
bool MatchFound = false;
DWORD ErrorStatus;
HDEVINFO hDevInfo;
wchar_t *b;
String DeviceIDFromRegistry;
String DeviceIDToFind = MY_DEVICE_ID;
EdtInterfaceIndex->Text="Start";
//First populate a list of plugged in devices (by specifying "DIGCF_PRESENT"), which are of the specified class GUID.
DeviceInfoTable = SetupDiGetClassDevs(&InterfaceClassGuid, NULL, NULL, DIGCF_PRESENT);
//Now look through the list we just populated. We are trying to see if any of them match our device.
for(InterfaceIndex=0;InterfaceIndex<5;InterfaceIndex++)
{
InterfaceDataStructure->cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
if (SetupDiEnumDeviceInterfaces(DeviceInfoTable, NULL, &InterfaceClassGuid, InterfaceIndex, InterfaceDataStructure))
{
ErrorStatus = GetLastError();
if(ERROR_NO_MORE_ITEMS == ErrorStatus) //Did we reach the end of the list of matching devices in the DeviceInfoTable?
{//Cound not find the device. Must not have been attached.
SetupDiDestroyDeviceInfoList(DeviceInfoTable); //Clean up the old structure we no longer need.
Memo1->Lines->Add("ERROR_NO_MORE_ITEMS == ErrorStatus");
return;
}
}
//Now retrieve the hardware ID from the registry. The hardware ID contains the VID and PID, which we will then
//check to see if it is the correct device or not.
//Initialize an appropriate SP_DEVINFO_DATA structure. We need this structure for SetupDiGetDeviceRegistryProperty().
DevInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
SetupDiEnumDeviceInfo(DeviceInfoTable, InterfaceIndex, &DevInfoData);
//First query for the size of the hardware ID, so we can know how big a buffer to allocate for the data.
SetupDiGetDeviceRegistryProperty(DeviceInfoTable, &DevInfoData, SPDRP_HARDWAREID, &dwRegType, NULL, 0, &dwRegSize);
//Allocate a buffer for the hardware ID.
PropertyValueBuffer = (BYTE *) malloc (dwRegSize);
if(PropertyValueBuffer == NULL) //if null, error, couldn't allocate enough memory
{ //Can't really recover from this situation, just exit instead.
ShowMessage("Allocation PropertyValueBuffer impossible");
SetupDiDestroyDeviceInfoList(DeviceInfoTable); //Clean up the old structure we no longer need.
//return;
}
//Retrieve the hardware IDs for the current device we are looking at. PropertyValueBuffer gets filled with a
//REG_MULTI_SZ (array of null terminated strings). To find a device, we only care about the very first string in the
//buffer, which will be the "device ID". The device ID is a string which contains the VID and PID, in the example
//format "Vid_0333&Pid_0333".
SetupDiGetDeviceRegistryProperty(DeviceInfoTable, &DevInfoData, SPDRP_HARDWAREID, &dwRegType, PropertyValueBuffer, dwRegSize, NULL);
//Now check if the first string in the hardware ID matches the device ID of my USB device.
DeviceIDFromRegistry = StrPas((char *)PropertyValueBuffer);
free(PropertyValueBuffer); //No longer need the PropertyValueBuffer, free the memory to prevent potential memory leaks
//Convert both strings to lower case. This makes the code more robust/portable accross OS Versions
DeviceIDFromRegistry = DeviceIDFromRegistry.LowerCase();
DeviceIDToFind = DeviceIDToFind.LowerCase();
//Now check if the hardware ID we are looking at contains the correct VID/PID
MatchFound = (DeviceIDFromRegistry.AnsiPos(DeviceIDToFind)>0);
if(MatchFound == true)
{
EdtInterfaceIndex->Text=InterfaceIndex+1;
InterfaceIndex=5;
Memo1->Lines->Add("Procurado:" + DeviceIDToFind);
Memo1->Lines->Add("Encontrado:" + DeviceIDFromRegistry);
//Device must have been found. Open read and write handles. In order to do this, we will need the actual device path first.
//We can get the path by calling SetupDiGetDeviceInterfaceDetail(), however, we have to call this function twice: The first
//time to get the size of the required structure/buffer to hold the detailed interface data, then a second time to actually
//get the structure (after we have allocated enough memory for the structure.)
DetailedInterfaceDataStructure->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
//First call populates "StructureSize" with the correct value
SetupDiGetDeviceInterfaceDetail(DeviceInfoTable, InterfaceDataStructure, NULL, NULL, &StructureSize, NULL);
DetailedInterfaceDataStructure = (PSP_DEVICE_INTERFACE_DETAIL_DATA)(malloc(StructureSize+100)); //Allocate enough memory
if(DetailedInterfaceDataStructure == NULL) //if null, error, couldn't allocate enough memory
{ //Can't really recover from this situation, just exit instead.
Memo1->Lines->Add("couldn't allocate enough memory");
SetupDiDestroyDeviceInfoList(DeviceInfoTable); //Clean up the old structure we no longer need.
return;
}
DetailedInterfaceDataStructure->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
//Now call SetupDiGetDeviceInterfaceDetail() a second time to receive the goods.
SetupDiGetDeviceInterfaceDetail(DeviceInfoTable, InterfaceDataStructure, DetailedInterfaceDataStructure, StructureSize, NULL, NULL);
//We now have the proper device path, and we can finally open read and write handles to the device.
//We store the handles in the global variables "WriteHandle" and "ReadHandle", which we will use later to actually communicate.
WriteHandle = CreateFile((DetailedInterfaceDataStructure->DevicePath), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
ErrorStatus = GetLastError();
//Translate ErrorCode to String.
TCHAR windowsErrorMessage[256];
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), windowsErrorMessage, 256, NULL);
EdtWriteError->Text = windowsErrorMessage;
if(ErrorStatus == ERROR_SUCCESS) ToggleLedBtn->Enabled = true;
//Make button no longer greyed out
ReadHandle = CreateFile((DetailedInterfaceDataStructure->DevicePath), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
ErrorStatus = GetLastError();
if(ErrorStatus == ERROR_SUCCESS)
{
GetPushbuttonState->Enabled = true; //Make button no longer greyed out
StateLabel->Enabled = true; //Make label no longer greyed out
}
SetupDiDestroyDeviceInfoList(DeviceInfoTable); //Clean up the old structure we no longer need.
return;
}
InterfaceIndex++;
//Keep looping until we either find a device with matching VID and PID, or until we run out of items.
}//end of while(true)
ShowMessage("Sorte");
}
//---------------------------------------------------------------------------

void __fastcall TForm1::ToggleLedBtnClick(TObject *Sender)
{
DWORD BytesWritten = 0;
unsigned char OutputPacketBuffer[65]; //Allocate a memory buffer equal to our endpoint size + 1

OutputPacketBuffer[0] = 0x20; //The first byte is the "Report ID". This number is used by the USB driver, but does not
//get tranmitted accross the USB bus. The custom HID class firmware is only configured for
//one type of report, therefore, we must always initializate this byte to "0" before sending
//a data packet to the device.

OutputPacketBuffer[1] = 0x01; //0x80 is the "Toggle LED(s)" command in the firmware
//For simplicity, we will leave the rest of the buffer uninitialized, but you could put real
//data in it if you like.

//The basic Windows I/O functions WriteFile() and ReadFile() can be used to read and write to HID class USB devices.
//Note that we need the handle which we got earlier when we called CreateFile() (when we hit the connect button).
//The following function call will send out 64 bytes (starting from OutputPacketBuffer[1]) to the USB device. The data will
//arrive on the OUT interrupt endpoint.
WriteFile(WriteHandle, &OutputPacketBuffer, 65, &BytesWritten, 0); //Blocking function, unless an "overlapped" structure is used
}
//---------------------------------------------------------------------------

void __fastcall TForm1::GetPushbuttonStateClick(TObject *Sender)
{
DWORD BytesWritten = 0;
DWORD BytesRead = 0;
unsigned char OutputPacketBuffer[65]; //Allocate a memory buffer equal to our endpoint size + 1
unsigned char InputPacketBuffer[65]; //Allocate a memory buffer equal to our endpoint size + 1

InputPacketBuffer[0] = 0; //The first byte is the "Report ID" and does not get transmitted over the USB bus. Always set = 0.
OutputPacketBuffer[0] = 0; //The first byte is the "Report ID" and does not get transmitted over the USB bus. Always set = 0.

OutputPacketBuffer[1] = 0x81; //0x81 is the "Get Pushbutton State" command in the firmware
//For simplicity, we will leave the rest of the buffer uninitialized, but you could put real
//data in it if you like.

//The basic Windows I/O functions WriteFile() and ReadFile() can be used to read and write to HID class USB devices
//(once we have the read and write handles to the device, which are obtained with CreateFile()).

//To get the pushbutton state, first, we send a packet with our "Get Pushbutton State" command in it.
//The following call to WriteFile() sends 64 bytes of data to the USB device.
WriteFile(WriteHandle, &OutputPacketBuffer, 65, &BytesWritten, 0); //Blocking function, unless an "overlapped" structure is used
//Now get the response packet from the firmware.
//The following call to ReadFIle() retrieves 64 bytes of data from the USB device.
ReadFile(ReadHandle, &InputPacketBuffer, 65, &BytesRead, 0); //Blocking function, unless an "overlapped" structure is used

//InputPacketBuffer[0] is the report ID, which we don't care about.
//InputPacketBuffer[1] is an echo back of the command.
//InputPacketBuffer[2] contains the I/O port pin value for the pushbutton.
if(InputPacketBuffer[2] == 0x01)
{
StateLabel->Caption = "State: Not Pressed"; //Update the pushbutton state text label on the form, so the user can see the result
}
else //InputPacketBuffer[2] must have been == 0x00 instead
{
StateLabel->Caption = "State: Pressed"; //Update the pushbutton state text label on the form, so the user can see the result
}
}
//---------------------------------------------------------------------------




void __fastcall TForm1::BtnClrClick(TObject *Sender)
{
Memo1->Clear();
EdtInterfaceIndex->Text="";
EdtWriteError->Text="";
}

E obtenho o seguinte resultado:

No Memo1:

Procurado:vid_0333&pid_0111

Encontrado:hid\vid_0333&pid_0111&rev_0100

No EdtInterfaceIndex:

3

No EdtWriteError:

A sintaxe do nome do arquivo, do nome do diretório ou do rótulo do volume está incorreta.

Isto é, não consigo o endereço: \\.\.\USB\Vid_0333& ..... completo.

Sabe onde estou errando?

Obrigado.

Link para o comentário
Compartilhar em outros sites

Bom dia.

Então, o projeto todo está aí. Tem um Form com um Memo, dois Edits, um Label e três Botões.

Tentei postar o desenho do Memo, mas pelo jeito, não foi.

Sim, com o exemplo do seu Link, ele está funcionando perfeitamente.

Apenas tive que comentar aquelas 2 Linhas:

static const Shortint SPFILENOTIFY_STARTREGISTRATION = 0x19;

static const Shortint SPFILENOTIFY_ENDREGISTRATION = 0x20;

Comentei os dois (//), compilei e, ..., começou a funcionar.

Obrigado.

Link para o comentário
Compartilhar em outros sites

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Sobre o Clube do Hardware

No ar desde 1996, o Clube do Hardware é uma das maiores, mais antigas e mais respeitadas comunidades sobre tecnologia do Brasil. Leia mais

Direitos autorais

Não permitimos a cópia ou reprodução do conteúdo do nosso site, fórum, newsletters e redes sociais, mesmo citando-se a fonte. Leia mais

×
×
  • Criar novo...

 

GRÁTIS: ebook Redes Wi-Fi – 2ª Edição

EBOOK GRÁTIS!

CLIQUE AQUI E BAIXE AGORA MESMO!