哪位大哥帮忙看下,DELPHI 向USB设备写数据,总是失败,读数据是可以的 :function TForm1.WriteCode(strCode: string): string;
var
  PreparsedData: PHIDPPreparsedData; //PHIDP_PREPARSED_DATA ;
  Success: Boolean;
  Capabilities: THIDPCaps; //HIDP_CAPS ;
  OutputReport: array[0..60] of byte;
  OutputReport1: array[0..9] of byte;
  bWritten: DWORD;
  ii: Integer;
  strv: string;
  c: BYTE;
  strGet: string;
  iv: Integer;
begin
  Success := HidD_GetPreparsedData(hDevHandle, PreparsedData);
  if Success then
  begin
    iv := 0;
    ii := 1;    HidP_GetCaps(PreparsedData, Capabilities);
    FillChar(OutputReport, Length(OutputReport), 0);
    FillChar(OutputReport1, Length(OutputReport1), 0);    while ii < Length(strCode) do
    begin
      strv := Copy(strCode, ii, 2);
      inc(ii);
      inc(ii);
      c := $ + StrToInt(IntToStr(StrToInt('$' + strv)));
      OutputReport[iv] := (c);      Inc(iv);
    end;
//向USB口写数据,所发的数据没问题。
    Success := WriteFile(hDevHandle, OutputReport, Capabilities.OutputReportByteLength, bWritten, 0);    if not Success then
      me1.Lines.Add('写入失败')
    else
      me1.Lines.Add('写入:' + strCode);  end;end;

解决方案 »

  1.   

    1.看看hDevHandle的值是不是正确的,如果这个值等于INVALID_HANDLE_VALUE,那就不对了,说明设备没有正确打开;
    2.用GetLastError查看WriteFile返回的错误代码是多少,根据这个提示去找原因。
      

  2.   

    楼上高手哦。除了楼上指出的外,提供以下参考:
    一、该函数没返回;
    二、两行 “inc(ii);” 语句, 可写成一句:inc(ii,2);
    三、“c := $ + StrToInt(IntToStr(StrToInt('$' + strv)));” 语句中,第一项的 $ 没意义,等效于 “c := StrToInt(IntToStr(StrToInt('$' + strv)));” 请复核你的意图与运算结果是否一致;  
    四、向USB口写数据前加个语句:
    {
      ......
      showmessage('hDevHandle:'+inttostr(hDevHandle)+#13
        +'长度:'+inttostr(Capabilities.OutputReportByteLength));
      //向USB口写数据,所发的数据没问题。
      ......
    }
    以便观察hDevHandle是否等于INVALID_HANDLE_VALUE(4294967295即DWORD(-1))、发送长度是否正确。