STM32F103 - 通过USB进行PC通信

时间:2014-05-19 11:12:53

标签: c usb driver stm32 winusb

我正在尝试使用found-bits项目通过USB从Windows应用程序与我的STM32F103进行通信,但没有成功。

程序在WinUsb_ControlTransfer函数调用中不断返回错误代码31。

我做了一些更改,解决了从默认端点接收数据的问题,但在尝试向其发送数据时问题仍然存在。

如何让我的Windows应用程序从STM32发送和接收数据?

P.S。:我为我的设备创建了.inf和.cat文件并安装了驱动程序

BOOL SendDatatoDefaultEndpoint(WINUSB_INTERFACE_HANDLE hDeviceHandle, BYTE byWinUSBCommControl, BYTE *pbyData = NULL, WORD wNumBytesCount = 0)
{
  if (hDeviceHandle==INVALID_HANDLE_VALUE)
  {
    return FALSE;
  }
  BOOL bResult = TRUE;
  WINUSB_SETUP_PACKET SetupPacket;
  ZeroMemory(&SetupPacket, sizeof(WINUSB_SETUP_PACKET));
  ULONG cbSent = 0;

  //Create the setup packet
  SetupPacket.RequestType = (BMREQUEST_HOST_TO_DEVICE << 7)/* | (BMREQUEST_VENDOR << 5) | BMREQUEST_TO_INTERFACE*/;
  //SetupPacket.Request = byWinUSBCommControl;
  //SetupPacket.Value = 0;
  SetupPacket.Index = 0; // specify WinUSBComm interface
  //SetupPacket.Length = wNumBytesCount;
  SetupPacket.Request = USB_REQUEST_GET_DESCRIPTOR;
  SetupPacket.Value = USB_DEVICE_DESCRIPTOR_TYPE << 8;
  SetupPacket.Length = sizeof(USB_DEVICE_DESCRIPTOR);

  bResult = WinUsb_ControlTransfer(hDeviceHandle, SetupPacket, pbyData, wNumBytesCount, &cbSent, 0);
  if(!bResult)
  {
    printf("Error WinUsb_ControlTransfer: %d.\n", GetLastError());
    goto done;
  }

  PTRACE("Data sent: %d \nActual data transferred: %d.\n", wNumBytesCount, cbSent);

  done:
    return bResult;
}

BOOL GetDataFromDefaultEndpoint(WINUSB_INTERFACE_HANDLE hDeviceHandle, BYTE byWinUSBCommControl, BYTE *pbyData, WORD wNumBytesCount)
{
  if ( 0 == wNumBytesCount )
  {
    return TRUE;
  }

  if ( NULL == pbyData )
  {
    return FALSE;
  }

  if (hDeviceHandle==INVALID_HANDLE_VALUE)
  {
    return FALSE;
  }
  BOOL bResult = TRUE;
  WINUSB_SETUP_PACKET SetupPacket;
  ZeroMemory(&SetupPacket, sizeof(WINUSB_SETUP_PACKET));
  ULONG cbSent = 0;

  //Create the setup packet
  SetupPacket.RequestType = (BMREQUEST_DEVICE_TO_HOST << 7)/* | (BMREQUEST_VENDOR << 5) | BMREQUEST_TO_DEVICE*/;
  //SetupPacket.Request = byWinUSBCommControl;
  //SetupPacket.Value = 0;
  SetupPacket.Index = 0; // specify WinUSBComm interface
  //SetupPacket.Length = wNumBytesCount;
  SetupPacket.Request = USB_REQUEST_GET_DESCRIPTOR;
  SetupPacket.Value = USB_DEVICE_DESCRIPTOR_TYPE << 8;
  SetupPacket.Length = sizeof(USB_DEVICE_DESCRIPTOR);

  bResult = WinUsb_ControlTransfer(hDeviceHandle, SetupPacket, pbyData, wNumBytesCount, &cbSent, 0);
  if(!bResult)
  {
    printf("Error WinUsb_ControlTransfer: %d.\n", GetLastError());
    goto done;
  }

  PTRACE("Data get : %d \nActual data transferred: %d.\n", wNumBytesCount, cbSent);

  done:
    return bResult;
}

0 个答案:

没有答案