Hello RemiNao,
From your detailed post, code, and debug information. I have isolated the problem. Your tests with the RAM disk (proving USBX is correct) and standalone LevelX (proving your driver is correct) are perfect. The issue is, as you suspect, in the integration.
This symptom points directly to a fundamental mismatch between your USBX and LevelX configurations, which is causing a classic buffer overflow.
Possible cause you are facing is of Sector Size Mismatch:
- USBX MSC Config: Your
USBD_STORAGE_GetMediaBlocklengthfunction correctly tells Windows that your disk's logical block (sector) size is 512 bytes. This is the standard for USB mass storage. - LevelX Config: Your debug screenshot of the
nor_flashstruct showslx_nor_flash_sector_size: 4096. This means you have configured LevelX to use a 4096-byte logical sector.
These two systems are not speaking the same language. Windows is asking for blocks of 512 bytes, but LevelX is reading and writing blocks of 4096 bytes.
Workaround I would recommend:
You must configure LevelX to use the same 512-byte logical sector size that USBX is using. The physical sector size of your flash (4096 bytes) is different, and LevelX's entire purpose is to manage this translation.
You need to do this in your lx_stm32_nor_custom_driver_initialize function, which you pass to _lx_nor_flash_open. In that function, you must define the driver parameters.
You need to set:
- Physical Sector Size: The erase-block size of your flash. This should be 4096.
- Logical Sector Size: The block size you want to expose. This must be 512 to match USBX.
LevelX also requires an internal "scratch" buffer equal to the size of at least one physical sector (4096 bytes) to perform its read-modify-erase-write wear-leveling operations. You must also allocate and provide this buffer during initialization.
Once LevelX is configured with a 512-byte logical sector, your USBD_STORAGE_Read and USBD_STORAGE_Write loops will work perfectly, as lx_nor_flash_sector_read will correctly read/write one 512-byte block at a time.
Answering your other question "if FileX can't be used, how can I write a formatted file to my flash memory?"
When used as a USB Mass Storage device, the Host (Windows) is the master. It controls the file system (FAT, exFAT, etc.).
Your device's only job is to provide raw block-level access via USBD_STORAGE_Read and USBD_STORAGE_Write. You cannot (and must not) use FileX on the device at the same time, as the two file systems would instantly corrupt each other. If you need to pre-load the disk with a file, you will have to:
- Implement your FileX code first.
- In a "first boot" routine, open the media with FileX, format it, create a file, write to it, and close the media.
- Then, un-initialize FileX and start the USBX MSC class, handing over control to the host.
Please accept the answer and upvote for visibility to other community members.