Skip to main content
Associate III
October 8, 2026
Question

STM32G0B1RET6 USB Host – How to Get USB Flash Drive Total and Free Storage Using FatFs?

  • October 8, 2026
  • 0 replies
  • 12 views

Hello STM32 Community,

I am currently working on a USB Flash Drive interface using STM32G0B1RET6 with USB Host and FatFs.

The USB Flash Drive is working correctly. When I plug in a USB Pendrive, my STM32 can detect it, mount the filesystem, and successfully create/write files to the Pendrive.

Now I would like to display/check the following information:

  1. Total USB Flash Drive storage
  2. Used storage
  3. Free/available storage
  4. Detect whether the USB is almost full

My current code is:

static void USBH_UserProcess(USBH_HandleTypeDef *phost, uint8_t id)
{
switch (id)
{
case HOST_USER_CLASS_ACTIVE:

Appli_state = APPLICATION_READY;

USB_Detect_flag = 1; // USB is plugged

Mount_USB();

HAL_GPIO_WritePin(GPIOC, LED_RED_Pin, GPIO_PIN_RESET);

/* Check USB free space */
if (usb_space_result == FR_OK)
{
displayText16x16_DMA(20, 190,
"USB HAS SPACE",
GREEN_COLOR,
BLACK_COLOR);
}
else
{
/* USB does not have enough free space
OR filesystem access failed. */

displayText16x16_DMA(50, 200,
"USB SPACE ERROR",
RED_COLOR,
BLACK_COLOR);
}

break;
}
}

My storage-checking function is:

FRESULT Check_USB_FreeSpace(void)
{
FATFS *fs;
DWORD free_clusters;
uint64_t free_bytes;
FRESULT res;

res = f_getfree("/", &free_clusters, &fs);

if (res != FR_OK)
{
printf("f_getfree ERROR = %d\r\n", res);
return res;
}

free_bytes = (uint64_t)free_clusters *
(uint64_t)fs->csize *
512ULL;

printf("Free Clusters = %lu\r\n", free_clusters);
printf("Cluster Size = %u\r\n", fs->csize);
printf("Free Bytes = %llu\r\n", free_bytes);
printf("Free KB = %llu\r\n", free_bytes / 1024ULL);

/*
* Minimum free space required
* 10 KB
*/
if (free_bytes < (10ULL * 1024ULL))
{
printf("USB FULL / LOW SPACE\r\n");
return FR_DENIED;
}

printf("USB HAS SPACE\r\n");

return FR_OK;
}

My question

Is this the correct way to calculate the USB Flash Drive storage?

I would like to get something like:

USB Total Storage : 14.9 GB
USB Used Storage : 3.2 GB
USB Free Storage : 11.7 GB

or, for example:

Total : 8 GB
Used : 2.5 GB
Free : 5.5 GB