13- STM32CubeMx 配置U盘读写

扫描二维码关注公众号,回复: 13466489 查看本文章

1、 在main.c文件中  /* USER CODE BEGIN 0 */   和  /* USER CODE END 0 */ 之间加入如下代码

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
extern ApplicationTypeDef Appli_state;
extern USBH_HandleTypeDef hUsbHostFS;
extern char USBHPath[4]; // USBH logical drive path

FATFS FatfsUDisk; // File system object for USB disk logical drive
FIL myFile; // File object

static void MSC_Application(void)
{
    FRESULT fres; // FatFs function common result code
    uint32_t byteswrite;
    uint8_t str[] = "hello world!";

    /* Register the file system object to the FatFs module */
    if( f_mount(&FatfsUDisk, (TCHAR const*)USBHPath, 0) != FR_OK)
    {
        Error_Handler(); //FatFs Initialization Error
    }
    else
    {
        /* Create and Open a new text file object with write access */
        if(f_open(&myFile, "test.txt", FA_CREATE_ALWAYS | FA_WRITE) != FR_OK)
        {
            Error_Handler(); //'STM32.TXT' file Open for write Error
        }
        else
        {
            fres = f_write(&myFile, str, sizeof(str), (void *)&byteswrite);
            if(byteswrite == 0 || (fres != FR_OK))
            {
                Error_Handler();
            }
            else
            {
                f_close(&myFile); //Close the open text file
            }
        }
    }
}
/* USER CODE END 0 */

 2、 在main.c文件中  int main(void) 函数中 while(1)内加入如下代码:加在  /* USER CODE BEGIN 3 */   和  /* USER CODE END 3 */ 之间

int main(void)
{
  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_FATFS_Init();
  MX_USB_HOST_Init();
  /* USER CODE BEGIN 2 */

  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */
    MX_USB_HOST_Process();

    /* USER CODE BEGIN 3 */
    switch(Appli_state)
    {
        case APPLICATION_READY:
            MSC_Application();
            Appli_state = APPLICATION_DISCONNECT;
            break;
        case APPLICATION_DISCONNECT:
            f_mount(NULL, "", 0);
            break;
        default:
            break;
    }
  }
  /* USER CODE END 3 */
}

插上U盘,运行代码一小段时间后,取下U盘,插入电脑看是否有代码中建立的文件及写入文件的内容!有则成功啦! 

 

 

猜你喜欢

转载自blog.csdn.net/weixin_46672094/article/details/121157802