Home > Software engineering >  Sometimes VS2019 USB HID communication failure problem
Sometimes VS2019 USB HID communication failure problem

Time:02-20

Everybody is good, do a with the underlying hardware USB communication tool, using the API interface function, CreateFile, WriteFile, ReadFile

Communication failure will happen, in the probability of not with computers, there are only occasionally, some computers are very frequent, the following figure error:



Int CUsbComm: : WriteReport (BYTE _ReportData [])
{
//Send a report to the device
DWORD BytesWritten=0;
ULONG Result;
Int InputLength OutputLength;
Int ByteNumber=0;
BYTE OutputReport [REPORT_PACK_LEN]={0};
BYTE InputReport [REPORT_PACK_LEN]={0};

//The first byte is The report number
If (m_hWriteHandle!=INVALID_HANDLE_VALUE)
{
For (ByteNumber=0; ByteNumber & lt; M_Capabilities. OutputReportByteLength; ByteNumber++)
{
OutputReport [ByteNumber]=_ReportData [ByteNumber];
}

Result=WriteFile (m_hWriteHandle, OutputReport, m_Capabilities OutputReportByteLength, & amp; BytesWritten, & amp; M_WriteOverlapped);

Result=WaitForSingleObject (m_WriteOverlapped hEvent, USB_TIMEOUT);
The switch (Result)
{
Case WAIT_OBJECT_0:
{
ResetEvent (m_WriteOverlapped hEvent);
return OK;
break;
}
Case WAIT_TIMEOUT:
{
break;
}
Default:
{
CloseDevice ();
break;
}
}
}

ResetEvent (m_WriteOverlapped hEvent);
Return ERR;
}

Int CUsbComm: : ReadReport (BYTE * ReportData)
{
DWORD Result;
Int TMP.
//int InputLength OutputLength;
DWORD NumberOfBytesRead;
Int ByteNumber=0;

BYTE InputReport [REPORT_PACK_LEN]={0};

If (m_hReadHandle!=INVALID_HANDLE_VALUE)
{
ReadFile (m_hReadHandle InputReport, m_Capabilities InputReportByteLength, & amp; NumberOfBytesRead, & amp; M_ReadOverlapped);
//wait event trigger
Result=WaitForSingleObject (m_ReadOverlapped hEvent, USB_TIMEOUT);

The switch (Result)
{
Case WAIT_OBJECT_0:
{
//CHAR ReceivedByte;
For (ByteNumber=0; ByteNumber & lt; M_Capabilities. InputReportByteLength; ByteNumber++)
{
ReportData [ByteNumber]=InputReport [ByteNumber];
}
ResetEvent (m_ReadOverlapped hEvent);
return OK;
break;
}
Case WAIT_TIMEOUT:
{
break;
}
Default:
{
TMP=CloseDevice ();
break;
}
}
}

ResetEvent (m_ReadOverlapped hEvent);
Return ERR;
}
Int. Err=m_UsbComm WriteReport (UsbBuf_s);
if (err !=0)
{
PDlg - & gt; M_eidt_mesg. The Format (_T (" communication failure "));
Goto the end;
}
If (m_UsbComm ReadReport (UsbBuf_r)==0)
{
If ((UsbBuf_r [1].=0 x11) | | (UsbBuf_r [2].=0 x22) | | (UsbBuf_r [3].=0 x33))
{
PDlg - & gt; M_eidt_mesg. The Format (_T (" communication failure "));
Goto the end;
}
}



Experience is not enough, can not find the problem, a senior can provide some advice?

CodePudding user response:

Can consider to use Windows DKK hid operation library

CodePudding user response:

Under GetLastError check the error message

  • Related