How to write to a .txt file using USB Host MSC, FATFS and FreeRTOS
I am using the NUCLEO-L476RG and I want to write to a .txt file on the USB Stick using FreeRTOS. For that, I have enabled FreeRTOS, USB_OTG_FS, Mass Storage Host Class and FATFS (USB Disk). When I generate the project, I see MX_USB_HOST_Init(); in my DefaultTask that the Cube generates.
I have written a USB_Write function (see below) that works perfectly when I don't use FreeRTOS, so I already tested it. But when I add FreeRTOS to my project, it doesn't work.
What I realized, is that, if I use it without FreeRTOS, there is a MX_USB_HOST_Process(); function in the while loop that then calls USBH_Process(&hUsbHostFS);. But when I add FreeRTOS to the mix, this function isn't there anymore, only the Init function in the defaultTask. So I tried to call USBH_Process(&hUsbHostFS); in the Task loop myself but I honestly don't know if that is the way to go.
Without FreeRTOS, my while loop looks like this:
//USB variable
extern ApplicationTypeDef Appli_state;
USBH_HandleTypeDef hUsbHostFS;
//USB logical PATH
char USBHPath[4];
//File IO variables
FIL myFile;
FRESULT res;
UINT byteswritten, bytesread;
char USBbuffer[100];
//FATFS variable
FATFS myUSBfatFs;
while (1) {
/* USER CODE END WHILE */
MX_USB_HOST_Process(); //generated by CubeMX automatically
/* USER CODE BEGIN 3 */
switch (Appli_state) {
case APPLICATION_IDLE:
break;
case APPLICATION_START:
if (f_mount(&myUSBfatFs, (TCHAR const*) USBHPath, 0) == FR_OK) { //mount USB
//HAL_GPIO_WritePin(GPIOA, GPIO_PIN_5, 1); //LED on if USB is plugged
}
break;
case APPLICATION_READY:
USB_Write("Test\r\n");
break;
case APPLICATION_DISCONNECT:
break;
}
}
This is my USB_Write function:
bool USB_Write(char text[100]) {
/*Copy parameter to USB buffer*/
sprintf(USBbuffer, text); //'text'cannot be larger than 100 characters, otherwise buffer overflow for the sprintf() function
/*Open and Append file for writing to .txt*/
if (f_open(&myFile, "CubeIDE.txt", FA_OPEN_APPEND | FA_WRITE) != FR_OK) {
return 0;
}
//Write to text file
res = f_write(&myFile, (const void*) USBbuffer, strlen(USBbuffer),
&byteswritten);
//HAL_UART_Transmit(&huart2, (uint8_t*) "Text appended to .txt file!\r\n", 29,HAL_MAX_DELAY);
if ((res != FR_OK) || (byteswritten == 0)) {
return 0;
}
f_close(&myFile);
return 1; //Success
}
This works perefectly without FreeRTOS, so I wanted to achieve the same result using FreeRTOS, but no luck :( I have struggled with this for days now, trying to debug it for hours every day, but no success. I would greatly appreciate any help.
