How to detect if a Bluetooth HID device was disconnected? - c
I'm using CreateFile to open an asynchronous file handle to a Bluetooth HID device on the system. The device will then start streaming data, and I use ReadFile to read data from the device. The problem is, that if the Bluetooth connection is dropped, ReadFile just keeps giving ERROR_IO_PENDING instead of reporting a failure.
I cannot rely on timeouts, because the device doesn't send any data if there is nothing to report. I do not want it to time out if the connection is still alive, but there is simply no data for a while.
Still, the Bluetooth manager (both the Windows one and the Toshiba one) do immediately notice that the connection was lost. So this information is somewhere inside the system; it's just not getting through to ReadFile.
I have available:
the file handle (HANDLE value) to the device,
the path that was used to open that handle (but I don't want to attempt to open it another time, creating a new connection...)
an OVERLAPPED struct used for asynchronous ReadFile.
I am not sure if this issue is Bluetooth-specific, HID-specific, or occurs with devices in general. Is there any way that I can either
get ReadFile to return an error when the connection was dropped, or
detect quickly upon a timeout from ReadFile whether the connection is still alive (it needs to be fast because ReadFile is called at least 100 times per second), or
solve this problem in another way I haven't thought of?
You are going to have to have some sort of polling to check. Unless there is a event you can attach (I'm not familiar with the driver), the simplest way is to poll your COM port by doing a ReadFile and check is dwBytesRead > 0 when you send a command. There should be some status command you can send or you can check if you can write to the port and copy those bytes written to dwBytesWrite using WriteFile, for instance, and check if that is equal to the length of bytes you are sending. For instance:
WriteFile(bcPort, cmd, len, &dwBytesWrite, NULL);
if (len == dwBytesWrite) {
// Good! Return true
} else
// Bad! Return false
}
This is how I do it in my application. Below may seem like a bunch of boilerplate code, but I think it will help you get to the root of your problem. I first open the Comm Port in the beginning.
I have an array of COM ports that I maintain and check to see if they are open before writing to a particular COM port. For instance, they are opened in the beginning.
int j;
DWORD dwBytesRead;
if (systemDetect == SYS_DEMO)
return;
if (port <= 0 || port >= MAX_PORT)
return;
if (hComm[port]) {
ShowPortMessage(true, 20, port, "Serial port already open:");
return;
}
wsprintf(buff, "COM%d", port);
hComm[port] = CreateFile(buff,
GENERIC_READ | GENERIC_WRITE,
0, //Set of bit flags that specifies how the object can be shared
0, //Security Attributes
OPEN_EXISTING,
0, //Specifies the file attributes and flags for the file
0); //access to a template file
if (hComm[port] != INVALID_HANDLE_VALUE) {
if (GetCommState(hComm[port], &dcbCommPort)) {
if(baudrate == 9600) {
dcbCommPort.BaudRate = CBR_9600;//current baud rate
} else {
if(baudrate == 115200) {
dcbCommPort.BaudRate = CBR_115200;
}
}
dcbCommPort.fBinary = 1; //binary mode, no EOF check
dcbCommPort.fParity = 0; //enable parity checking
dcbCommPort.fOutxCtsFlow = 0; //CTS output flow control
dcbCommPort.fOutxDsrFlow = 0; //DSR output flow control
// dcbCommPort.fDtrControl = 1; //DTR flow control type
dcbCommPort.fDtrControl = 0; //DTR flow control type
dcbCommPort.fDsrSensitivity = 0;//DSR sensitivity
dcbCommPort.fTXContinueOnXoff = 0; //XOFF continues Tx
dcbCommPort.fOutX = 0; //XON/XOFF out flow control
dcbCommPort.fInX = 0; //XON/XOFF in flow control
dcbCommPort.fErrorChar = 0; //enable error replacement
dcbCommPort.fNull = 0; //enable null stripping
//dcbCommPort.fRtsControl = 1; //RTS flow control
dcbCommPort.fRtsControl = 0; //RTS flow control
dcbCommPort.fAbortOnError = 0; //abort reads/writes on error
dcbCommPort.fDummy2 = 0; //reserved
dcbCommPort.XonLim = 2048; //transmit XON threshold
dcbCommPort.XoffLim = 512; //transmit XOFF threshold
dcbCommPort.ByteSize = 8; //number of bits/byte, 4-8
dcbCommPort.Parity = 0; //0-4=no,odd,even,mark,space
dcbCommPort.StopBits = 0; //0,1,2 = 1, 1.5, 2
dcbCommPort.XonChar = 0x11; //Tx and Rx XON character
dcbCommPort.XoffChar = 0x13; //Tx and Rx XOFF character
dcbCommPort.ErrorChar = 0; //error replacement character
dcbCommPort.EofChar = 0; //end of input character
dcbCommPort.EvtChar = 0; //received event character
if (!SetCommState(hComm[port], &dcbCommPort)) {
setBit(SystemState, SYSTEM_PORT_ERROR);
//ShowPortMessage(true, 21, port, "Cannot set serial port state information:");
if (!CloseHandle(hComm[port])) {
//ShowPortMessage(true, 22, port, "Cannot close serial port:");
}
hComm[port] = NULL;
return;
}
} else {
setBit(SystemState, SYSTEM_PORT_ERROR);
//ShowPortMessage(true, 29, port, "Cannot get serial port state information:");
if (!CloseHandle(hComm[port])) {
//ShowPortMessage(true, 22, port, "Cannot close serial port:");
}
hComm[port] = NULL;
return;
}
if (!SetupComm(hComm[port], 1024*4, 1024*2)) {
setBit(SystemState, SYSTEM_PORT_ERROR);
//ShowPortMessage(true, 23, port, "Cannot set serial port I/O buffer size:");
if (!CloseHandle(hComm[port])) {
//ShowPortMessage(true, 22, port, "Cannot close serial port:");
}
hComm[port] = NULL;
return;
}
if (GetCommTimeouts(hComm[port], &ctmoOld)) {
memmove(&ctmoNew, &ctmoOld, sizeof(ctmoNew));
//default setting
ctmoNew.ReadTotalTimeoutConstant = 100;
ctmoNew.ReadTotalTimeoutMultiplier = 0;
ctmoNew.WriteTotalTimeoutMultiplier = 0;
ctmoNew.WriteTotalTimeoutConstant = 0;
if (!SetCommTimeouts(hComm[port], &ctmoNew)) {
setBit(SystemState, SYSTEM_PORT_ERROR);
//ShowPortMessage(true, 24, port, "Cannot set serial port timeout information:");
if (!CloseHandle(hComm[port])) {
//ShowPortMessage(true, 22, port, "Cannot close serial port:");
}
hComm[port] = NULL;
return;
}
} else {
setBit(SystemState, SYSTEM_PORT_ERROR);
//ShowPortMessage(true, 25, port, "Cannot get serial port timeout information:");
if (!CloseHandle(hComm[port])) {
//ShowPortMessage(true, 22, port, "Cannot close serial port:");
}
hComm[port] = NULL;
return;
}
for (j = 0; j < 255; j++) {
if (!ReadFile(hComm[port], buff, sizeof(buff), &dwBytesRead, NULL)) {
setBit(SystemState, SYSTEM_PORT_ERROR);
//ShowPortMessage(true, 26, port, "Cannot read serial port:");
j = 999; //read error
break;
}
if (dwBytesRead == 0) //No data in COM buffer
break;
Sleep(10); //Have to sleep certain time to let hardware flush buffer
}
if (j != 999) {
setBit(pcState[port], PORT_OPEN);
}
} else {
setBit(SystemState, SYSTEM_PORT_ERROR);
//ShowPortMessage(true, 28, port, "Cannot open serial port:");
hComm[port] = NULL;
}
HANDLE TCommPorts::OpenCommPort(void) {
// OPEN THE COMM PORT.
if (hComm)
return NULL; // if already open, don't bother
if (systemDetect == SYS_DEMO)
return NULL;
hComm = CreateFile(port,
GENERIC_READ | GENERIC_WRITE,
0, //Set of bit flags that specifies how the object can be shared
0, //Security Attributes
OPEN_EXISTING,
0, //Specifies the file attributes and flags for the file
0);//access to a template file
// If CreateFile fails, throw an exception. CreateFile will fail if the
// port is already open, or if the com port does not exist.
// If the function fails, the return value is INVALID_HANDLE_VALUE.
// To get extended error information, call GetLastError.
if (hComm == INVALID_HANDLE_VALUE) {
// throw ECommError(ECommError::OPEN_ERROR);
return INVALID_HANDLE_VALUE;
}
// GET THE DCB PROPERTIES OF THE PORT WE JUST OPENED
if (GetCommState(hComm, &dcbCommPort)) {
// set the properties of the port we want to use
dcbCommPort.BaudRate = CBR_9600;// current baud rate
//dcbCommPort.BaudRate = CBR_115200;
dcbCommPort.fBinary = 1; // binary mode, no EOF check
dcbCommPort.fParity = 0; // enable parity checking
dcbCommPort.fOutxCtsFlow = 0; // CTS output flow control
dcbCommPort.fOutxDsrFlow = 0; // DSR output flow control
//dcbCommPort.fDtrControl = 1; // DTR flow control type
dcbCommPort.fDtrControl = 0; // DTR flow control type
dcbCommPort.fDsrSensitivity = 0;// DSR sensitivity
dcbCommPort.fTXContinueOnXoff = 0; // XOFF continues Tx
dcbCommPort.fOutX = 0; // XON/XOFF out flow control
dcbCommPort.fInX = 0; // XON/XOFF in flow control
dcbCommPort.fErrorChar = 0; // enable error replacement
dcbCommPort.fNull = 0; // enable null stripping
//dcbCommPort.fRtsControl = 1; // RTS flow control
dcbCommPort.fRtsControl = 0; // RTS flow control
dcbCommPort.fAbortOnError = 0; // abort reads/writes on error
dcbCommPort.fDummy2 = 0; // reserved
dcbCommPort.XonLim = 2048; // transmit XON threshold
dcbCommPort.XoffLim = 512; // transmit XOFF threshold
dcbCommPort.ByteSize = 8; // number of bits/byte, 4-8
dcbCommPort.Parity = 0; // 0-4=no,odd,even,mark,space
dcbCommPort.StopBits = 0; // 0,1,2 = 1, 1.5, 2
dcbCommPort.XonChar = 0x11; // Tx and Rx XON character
dcbCommPort.XoffChar = 0x13; // Tx and Rx XOFF character
dcbCommPort.ErrorChar = 0; // error replacement character
dcbCommPort.EofChar = 0; // end of input character
dcbCommPort.EvtChar = 0; // received event character
}
else
{
// something is way wrong, close the port and return
CloseHandle(hComm);
throw ECommError(ECommError::GETCOMMSTATE);
}
// SET BAUD RATE, PARITY, WORD SIZE, AND STOP BITS TO OUR SETTINGS.
// REMEMBERTHAT THE ARGUMENT FOR BuildCommDCB MUST BE A POINTER TO A STRING.
// ALSO NOTE THAT BuildCommDCB() DEFAULTS TO NO HANDSHAKING.
// wsprintf(portSetting, "%s,%c,%c,%c", baud, parity, databits, stopbits);
dcbCommPort.DCBlength = sizeof(DCB);
// BuildCommDCB(portSetting, &dcbCommPort);
if (!SetCommState(hComm, &dcbCommPort)) {
// something is way wrong, close the port and return
CloseHandle(hComm);
throw ECommError(ECommError::SETCOMMSTATE);
}
// set the intial size of the transmit and receive queues.
// I set the receive buffer to 32k, and the transmit buffer
// to 9k (a default).
if (!SetupComm(hComm, 1024*32, 1024*9))
{
// something is hay wire, close the port and return
CloseHandle(hComm);
throw ECommError(ECommError::SETUPCOMM);
}
// SET THE COMM TIMEOUTS.
if (GetCommTimeouts(hComm,&ctmoOld)) {
memmove(&ctmoNew, &ctmoOld, sizeof(ctmoNew));
//default settings
ctmoNew.ReadTotalTimeoutConstant = 100;
ctmoNew.ReadTotalTimeoutMultiplier = 0;
ctmoNew.WriteTotalTimeoutMultiplier = 0;
ctmoNew.WriteTotalTimeoutConstant = 0;
if (!SetCommTimeouts(hComm, &ctmoNew)) {
// something is way wrong, close the port and return
CloseHandle(hComm);
throw ECommError(ECommError::SETCOMMTIMEOUTS);
}
} else {
CloseHandle(hComm);
throw ECommError(ECommError::GETCOMMTIMEOUTS);
}
return hComm;
}
Related
HAL_UART_Transmit_IT sending data twice
I am trying to establish UART communication between a PC and a STM32f407-DISC1 board using an arduino nano as a middle man. The PC sends 'r' to the arduino to indicate a request. The request is then communicated to the stm32 with a GPIO interrupt, which then should be transmitting 480 bytes of data using HAL_UART_Transmit_IT. It however sends the data twice, with only a single request made. The code on the STM32 is generated by STM32CubeMX Data request made by the arduino void loop() { digitalWrite(4, 0); // Clear EXTI11 line. if (mySerial.available() && received < 480) { // STM32 sending data and is not done. buff[received] = mySerial.read(); // Append received data to the buffer. received++; } if (received >= 480) { // If the buffer is full received = 0; // transmit it to PC. Serial.println(buff); } if (Serial.available()) { if (Serial.read() == 'r') { // PC requests data from the STM32 digitalWrite(4, 1); // Triggers STM32 EXTI11 line. while (Serial.available()) // Empty the buffer. Serial.read(); } } } data transmission on the STM32 void EXTI15_10_IRQHandler(void) { // Make sure that the interrupt is the good one. if (HAL_GPIO_ReadPin(data_req_IRQ_GPIO_Port, data_req_IRQ_Pin)) { if (is_sending_data == FALSE) // If no transmission is happening should_send_data = TRUE; // raise transmission flag. } // IRQ handling stuff... } void HAL_UART_TxCpltCallback(UART_HandleTypeDef * huart) { is_sending_data = FALSE; // Transmition is completed, unblock requests. } void main(void){ // Init and other stuff... while (1) { if (should_send_data == TRUE) { // If data was requested HAL_GPIO_WritePin(LD5_GPIO_Port, LD5_Pin, GPIO_PIN_RESET); HAL_UART_Transmit_IT(&huart3, matrice, 480); // Start transmission by interrupt. is_sending_data = TRUE; // Block requests. should_send_data = FALSE; // Clear flag. } // matrice acquisition stuff here } }
Alright so I found a solution, but it involved just rethinking my approach, so sorry for those looking for an answer to this problem. I removed the arduino middle man by replacing it with a USB to RS232 converter and made UART reception work by interrupt. The STM detects the 'r' character which triggers the data communication. Here is the interrupt part: void USART3_IRQHandler(void) { if (USART3->SR & UART_IT_RXNE) { // If a byte is received rxBuff[0] = (uint8_t) (huart3.Instance->DR & (uint8_t) 0xFF); // Read it. __HAL_UART_FLUSH_DRREGISTER(&huart3); // Clear the buffer to avoid errors. rx_new_char_flag = TRUE; // Raise the new_char flag. return; // Stops the IRQHandler from disabling interrupts. } } and the gestion of that in the main while (1) { if (rx_new_char_flag == TRUE) { rx_new_char_flag = FALSE; if (rxBuff[0] == 'r') { rxBuff[0] = 0; HAL_UART_Transmit_IT(&huart3, matrice, 480); // Start transmission by interrupt. } } On the PC side, to optimize performance, instead of waiting for the full 480 bytes, I wait for only one character, if one is received I keep reading the serial port, as shown in the code bellow int i = 0; do { ReadFile(m_hSerial, &temp_rx[i], 1, &dwBytesRead, NULL); i++; } while (dwBytesRead > 0 && i < 480); for (int j = i; j < 480; j++) // If the transmission is incomplete, fill the buffer with 0s to avoid garbage data. temp_rx[j] = 0; if(i>=480) // If all the bytes has been received, copy the data in the working buffer. std::copy(std::begin(temp_rx), std::end(temp_rx), std::begin(m_touch_state)); This works well with pretty decent performance, so that may be a permanent solution to my problem.
How to continuos transmit data?
Chip:C8051F321 & PCF85176(LCD Driver) I am trying to communicate from C8051F321(MASTER) to PCF85176(SLAVE), and the original code is only transmit for one byte like this: START → SLAVE ADDR → DATA → ACK → STOP But I tried to make it like START → SLAVE ADDR → Command → ACK → DATA → ACK...→ ACK ..→ ACK .. → STOP And it always no effect like my code How can I correct my code? Thanks for helping~ void SMBus_ISR (void) interrupt 7 { bit FAIL = 0; // Used by the ISR to flag failed // transfers static bit ADDR_SEND = 0; // Used by the ISR to flag failed unsigned char a; // transmissions as slave addresses if(ARBLOST == 0) { switch (SMB0CN & 0xF0) // Status vector { // Master Transmitter/Receiver: START condition transmitted. case SMB_MTSTA: SMB0DAT = TARGET; // Load address of the target slave SMB0DAT &= 0xFE; // Clear the LSB of the address for the // R/W bit SMB0DAT |= SMB_RW; // Load R/W bit STA = 0; // Manually clear START bit ADDR_SEND = 1; break; // Master Transmitter: Data byte case SMB_MTDB: if (ACK) // Slave Address or Data Byte { // Acknowledged? if (ADDR_SEND) { ADDR_SEND = 0; // Next byte is not a slave address if(SMB_DATA_OUT==0xF0) { SMB0DAT = SMB_DATA_OUT; ADDR_SEND = 0; } else { SMB0DAT = SMB_Command_OUT; ADDR_SEND = 1; } } else // If previous byte was not a slave address, { STO =1; // Set STO to terminate transfer SMB_BUSY =0; // And free SMBus interface } } else { STO = 1; // Set STO to terminate transfer STA = 1; // By a START NUM_ERRORS++; // Indicate error } break; //Master Receiver:byte received case SMB_MRDB: SMB_DATA_IN =SMB0DAT; // Store received byte SMB_BUSY = 0; // Free SMBus interface ACK = 0; // Send NACK to indicate last byte // of this transfer STO = 1; // Send STOP to terminate transfer break; default: FAIL = 1; // Indicate failed transfer // and handle at end of ISR break; }//end switch } else { //ARBLOST = 1,error occurred...abort transmission FAIL = 1; } //end ARBLOST if if(FAIL) // If the transfer failed, { SMB0CF &= ~0x80; // Reset communication SMB0CF |= 0x80; STA = 0; STO = 0; ACK = 0; SMB_BUSY = 0; // Free SMBus FAIL = 0; NUM_ERRORS++; // Indicate an error occurred } SI = 0; //Clear interrupt flag }
poll the status of CTS line in windows
Hi stackoverflow users! I need to poll the CTS line of my serial port in Windows environment, I have opened successfully the COM port, HANDLE hSerialIn; const char* pcCommPort = TEXT("COM3"); hSerialIn = CreateFile(pcCommPort, GENERIC_READ | GENERIC_WRITE, \ 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); Then I want to have something like this DCB dcb = { 0 }; while (GetCommState(hSerialIn, &dcb)) { if (dcb.fOutxCtsFlow) ; else ; } The background of my interest in COM port is that there, I have a USB->UART convertor which in connected to the trigger output of the measuring device, this device triggers the output each second, and I want to have it in my program. When I connect to the COM port via Hercules(Terminal app) it works, I see that my CTS line is changing each second. So how to check the state of the CTS line? Thanks in advance.
DWORD dwModemStatus; BOOL fCTS = 0; if (!SetCommMask(hSerialIn, EV_CTS)) { DWORD err = GetLastError(); printf("\nHandle creation error code: %x\n", err); } DWORD dwCommEvent; while(1) { if (!WaitCommEvent(hSerialIn, &dwCommEvent, NULL)) // An error occurred waiting for the event. printf(""); else { if (!GetCommModemStatus(hSerialIn, &dwModemStatus)) // Error in GetCommModemStatus; return; fCTS = MS_CTS_ON & dwModemStatus; if(fCTS) printf("%x ", fCTS); } }
STM32 USB OTG HOST Library hangs trying to create file with FatFs
I am trying to create a file with FatFs on USB flash, but my f_open call trying to read boot sector for first time file system mount hangs on this function. DRESULT disk_read ( BYTE drv, /* Physical drive number (0) */ BYTE *buff, /* Pointer to the data buffer to store read data */ DWORD sector, /* Start sector number (LBA) */ BYTE count /* Sector count (1..255) */ ) { BYTE status = USBH_MSC_OK; if (drv || !count) return RES_PARERR; if (Stat & STA_NOINIT) return RES_NOTRDY; if(HCD_IsDeviceConnected(&USB_OTG_Core)) { do { status = USBH_MSC_Read10(&USB_OTG_Core, buff,sector,512 * count); USBH_MSC_HandleBOTXfer(&USB_OTG_Core ,&USB_Host); if(!HCD_IsDeviceConnected(&USB_OTG_Core)) { return RES_ERROR; } } while(status == USBH_MSC_BUSY ); // Loop which create hanging state } if(status == USBH_MSC_OK) return RES_OK; return RES_ERROR; } The main problem is the loop which creates hanging state while(status == USBH_MSC_BUSY ); So I do not know what to do to avoid this. Using debugger I discover that state is caused by parameter CmdStateMachine of structure USBH_MSC_BOTXferParam, type USBH_BOTXfer_TypeDef is equal CMD_UNINITIALIZED_STATE which actually cause miss up of switch statement of USBH_MSC_Read10 function. /** * #brief USBH_MSC_Read10 * Issue the read command to the device. Once the response received, * it updates the status to upper layer * #param dataBuffer : DataBuffer will contain the data to be read * #param address : Address from which the data will be read * #param nbOfbytes : NbOfbytes to be read * #retval Status */ uint8_t USBH_MSC_Read10(USB_OTG_CORE_HANDLE *pdev, uint8_t *dataBuffer, uint32_t address, uint32_t nbOfbytes) { uint8_t index; static USBH_MSC_Status_TypeDef status = USBH_MSC_BUSY; uint16_t nbOfPages; status = USBH_MSC_BUSY; if(HCD_IsDeviceConnected(pdev)) { switch(USBH_MSC_BOTXferParam.CmdStateMachine) { case CMD_SEND_STATE: /*Prepare the CBW and relevant field*/ USBH_MSC_CBWData.field.CBWTransferLength = nbOfbytes; USBH_MSC_CBWData.field.CBWFlags = USB_EP_DIR_IN; USBH_MSC_CBWData.field.CBWLength = CBW_LENGTH; USBH_MSC_BOTXferParam.pRxTxBuff = dataBuffer; for(index = CBW_CB_LENGTH; index != 0; index--) { USBH_MSC_CBWData.field.CBWCB[index] = 0x00; } USBH_MSC_CBWData.field.CBWCB[0] = OPCODE_READ10; /*logical block address*/ USBH_MSC_CBWData.field.CBWCB[2] = (((uint8_t*)&address)[3]); USBH_MSC_CBWData.field.CBWCB[3] = (((uint8_t*)&address)[2]); USBH_MSC_CBWData.field.CBWCB[4] = (((uint8_t*)&address)[1]); USBH_MSC_CBWData.field.CBWCB[5] = (((uint8_t*)&address)[0]); /*USBH_MSC_PAGE_LENGTH = 512*/ nbOfPages = nbOfbytes/ USBH_MSC_PAGE_LENGTH; /*Tranfer length */ USBH_MSC_CBWData.field.CBWCB[7] = (((uint8_t *)&nbOfPages)[1]) ; USBH_MSC_CBWData.field.CBWCB[8] = (((uint8_t *)&nbOfPages)[0]) ; USBH_MSC_BOTXferParam.BOTState = USBH_MSC_SEND_CBW; /* Start the transfer, then let the state machine manage the other transactions */ USBH_MSC_BOTXferParam.MSCState = USBH_MSC_BOT_USB_TRANSFERS; USBH_MSC_BOTXferParam.BOTXferStatus = USBH_MSC_BUSY; USBH_MSC_BOTXferParam.CmdStateMachine = CMD_WAIT_STATUS; status = USBH_MSC_BUSY; break; case CMD_WAIT_STATUS: if((USBH_MSC_BOTXferParam.BOTXferStatus == USBH_MSC_OK) && \ (HCD_IsDeviceConnected(pdev))) { /* Commands successfully sent and Response Received */ USBH_MSC_BOTXferParam.CmdStateMachine = CMD_SEND_STATE; status = USBH_MSC_OK; } else if (( USBH_MSC_BOTXferParam.BOTXferStatus == USBH_MSC_FAIL ) && \ (HCD_IsDeviceConnected(pdev))) { /* Failure Mode */ USBH_MSC_BOTXferParam.CmdStateMachine = CMD_SEND_STATE; } else if ( USBH_MSC_BOTXferParam.BOTXferStatus == USBH_MSC_PHASE_ERROR ) { /* Failure Mode */ USBH_MSC_BOTXferParam.CmdStateMachine = CMD_SEND_STATE; status = USBH_MSC_PHASE_ERROR; } else { /* Wait for the Commands to get Completed */ /* NO Change in state Machine */ } break; default: break; } } return status; } Here is USBH_BOTXfer_TypeDef type declaration; typedef struct _BOTXfer { uint8_t MSCState; uint8_t MSCStateBkp; uint8_t MSCStateCurrent; uint8_t CmdStateMachine; uint8_t BOTState; uint8_t BOTStateBkp; uint8_t* pRxTxBuff; uint16_t DataLength; uint8_t BOTXferErrorCount; uint8_t BOTXferStatus; } USBH_BOTXfer_TypeDef; During the debug I discover that all fields of it is 0x00. Here are my FatFs calls int main(void) { FATFS Fat; FIL file; FRESULT fr; RCC->AHB1ENR |= RCC_AHB1ENR_GPIODEN; /* Enable SWO output */ DBGMCU->CR = 0x00000020; GPIOD->MODER=0x55000000; GPIOD->OTYPER = 0x00000000; GPIOD->OSPEEDR = 0x00000001; while(1) { if (!USB_MSC_IsInitialized()) { USB_MSC_Initialize(); } if (USB_MSC_IsConnected()) { GPIOD->ODR = (1 << 15); disk_initialize(0); fr = f_mount(0, &Fat); if(fr == FR_OK) { fr = f_open(&file,"0:DP_lab8.pdf",(FA_CREATE_ALWAYS | FA_WRITE)); if (fr == FR_OK) { f_close(&file); } f_mount(0, NULL); } } else { GPIOD->ODR = (1 << 14); } USB_MSC_Main(); } } USB_MSC_IsConnected function is: int USB_MSC_IsConnected(void) { if (g_USB_MSC_HostStatus == USB_DEV_NOT_SUPPORTED) { USB_MSC_Uninitialize(); } return !(g_USB_MSC_HostStatus == USB_DEV_DETACHED || g_USB_MSC_HostStatus == USB_HOST_NO_INIT || g_USB_MSC_HostStatus == USB_DEV_NOT_SUPPORTED); } And device states are: typedef enum { USB_HOST_NO_INIT = 0, /* USB interface not initialized */ USB_DEV_DETACHED, /* no device connected */ USB_SPEED_ERROR, /* unsupported USB speed */ USB_DEV_NOT_SUPPORTED, /* unsupported device */ USB_DEV_WRITE_PROTECT, /* device is write protected */ USB_OVER_CURRENT, /* overcurrent detected */ USB_DEV_CONNECTED /* device connected and ready */ } USB_HostStatus; The value of g_USB_MSC_HostStatus is received by standard USB HOST user callbacks.
I think it is a bug in ST host library. I've hunted it down, as my usb host was unable to pass enumeration stage. After a fix the stack is Ok. There is union _USB_Setup in usbh_def.h file in "STM32Cube/Repository/STM32Cube_FW_F7_V1.13.0/Middlewares/ST/STM32_USB_Host_Library/Core/Inc" (any chip, not only F7, any version, not only V1.13.0). It has uint16_t bmRequestType and uint16_t bRequest. These two fileds must be uint8_t as of USB specs. Fixing this issue made usb host go as needed. Enumeration stage passes ok, and all other stages as well.
Extra bytes sent when communicating at 115200 baud over USB serial (WinAPI)
I'm attempting to send serial messages over USB to an Arduino Uno, using raw WinAPI commands. When using baud rates less than 115200, it works perfectly fine. However, when I send at 115200 baud, two extra bytes are sent prefixing the data I sent, but ONLY for the first message after connecting to the Arduino. For example, if I connect to the Arduino and send two bytes, "Hi", the Arduino receives "ððHi". If I send "Hi" again, the Arduino receives "Hi" like it should. (The extra bytes are usually ð (0xF0), but not always.) I know that my computer and the Arduino are capable of communicating at 115200 baud, because other programs such as avrdude and the Arduino IDE's serial monitor can do it fine. I have tried clearing the RX and TX buffers on both sides and also messing the DCB settings, with no effect. Does anyone know what might be causing this? Thanks! Here is my code to reproduce the problem: Computer side: #include <Windows.h> int main() { // Open device as non-overlapped HANDLE device = CreateFile(L"COM6", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); // Make sure the device is valid if(device == INVALID_HANDLE_VALUE) return 0; DCB dcb; if(!GetCommState(device, &dcb)) return 0; dcb.fOutX = 0; dcb.fInX = 0; dcb.fDtrControl = DTR_CONTROL_DISABLE; dcb.fRtsControl = RTS_CONTROL_DISABLE; dcb.fNull = 0; dcb.BaudRate = CBR_115200; dcb.ByteSize = 8; dcb.Parity = NOPARITY; dcb.StopBits = ONESTOPBIT; if(!SetCommState(device, &dcb)) return 0; COMMTIMEOUTS Timeouts = { 0 }; Timeouts.ReadTotalTimeoutConstant = 1000; Timeouts.WriteTotalTimeoutConstant = 1000; if(!SetCommTimeouts(device, &Timeouts)) return 0; char *buf = "abcdef"; DWORD written; WriteFile(device, buf, 6, &written, NULL); DWORD read; char inbuf[100]; ReadFile(device, inbuf, 100, &read, NULL); // When I get the result inbuf, it has 8 bytes: {0xF0, 0xF0, a, b, c, d, e, f} // Doing a 2nd set of Write/ReadFile, with the same message, gives the correct response return 0; } Arduino side: void setup() { Serial.begin(115200); } void loop() { if(Serial.available()) Serial.write(Serial.read()); }