How to detect when USB is disconnected?

1.1k views Asked by At

I use a virtual com port for communication between the microcontroller and the computer.
I have mk. stm32h743 self-powered from its own 3.3V power supply. With the help of a cube, I raised a virtual com port. How can you understand that the USB is disconnected from the device ?
When you connect Usb, it calls "CDC_Init_FS" and hUsbDeviceFS.dev_state is set to 3, which corresponds to "USBD_STATE_CONFIGURED".
But when you disconnect the USB there is no callback "HAL_PCD_DisconnectCallback (PCD_HandleTypeDef * hpcd);"

Why "HAL_PCD_DisconnectCallback (PCD_HandleTypeDef * hpcd);" not called when USB is disabled?

I have no way to track Vbus voltages. So I did it like this :

void HAL_PCD_SuspendCallback(PCD_HandleTypeDef hpcd) 
{
USBD_LL_Suspend((USBD_HandleTypeDef)hpcd->pData);
__HAL_PCD_GATE_PHYCLOCK(hpcd); 
if (hpcd->Init.low_power_enable) 
{ 
   SCB->SCR |= (uint32_t)((uint32_t)(SCB_SCR_SLEEPDEEP_Msk | 
   SCB_SCR_SLEEPONEXIT_Msk)); 
} 
SBD_LL_DevDisconnected(&hUsbDeviceFS); 
}

Hello.

I have a problem with USB working properly - USB CDC (Virtual Com Port) with CubeMX HAL after disconnecting the USB cable and connecting again.

For the test I created a project similar to the one presented here - https://www.youtube.com/watch?v=AYICE0gU-Sg using STM32CubeIDE and STM32CubeMX.

The program writes data in the while (1) loop to the USB port after uploading to STM32.

    while(1)
{
 CDC_Transmit_FS(buffer, sizeof(buffer));
 HAL_Delay(1000);
}

The data is written out, visible in Windows 7 (Tera Term).

When I disconnect the USB cable (OTG FS port) and reconnect, Windows sends the message "USB device not recognized".

Data is not received.

In order for the data to be transferred and the cable to be recognized, I must do a Reset on the board.

Hardware:

MCU: STM32H743VIT

Software: STM32CubeIDE v1.2

Firmware package: STM32Cube_FW_H7_V1.7.0

How to make the USB device work all the time correctly (after disconnecting the cable and reconnecting it), so that it is recognized by Windows and data is transferred?

0

There are 0 answers