ww
1. 首先在cube里面选用USB OTG, fats 文件系统
2. 在main函数里面初始化和USB消息轮询:
int main(void)
{
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
if (MX_FATFS_Init() != APP_OK)
Error_Handler();
MX_USB_Host_Init();
while (1)
{
MX_USB_HOST_Process();
switch (Appli_state)
{
case APPLICATION_START:
Appli_state = APPLICATION_DISCONNECT;
break;
case APPLICATION_READY:
read_write_U_disk_file_data();
Appli_state = APPLICATION_DISCONNECT;
break;
case APPLICATION_DISCONNECT:
f_mount(NULL, "", 0);
break;
default:
break;
}
}
}
初始化:
USBH_HandleTypeDef hUsbHostFS;
ApplicationTypeDef Appli_state = APPLICATION_IDLE;
void MX_USB_Host_Init(void)
{
if (USBH_Init(&hUsbHostFS, USBH_UserProcess, HOST_FS) != USBH_OK)
{
Error_Handler();
}
if (USBH_RegisterClass(&hUsbHostFS, USBH_MSC_CLASS) != USBH_OK)
{
Error_Handler();
}
if (USBH_Start(&hUsbHostFS) != USBH_OK)
{
Error_Handler();
}
}
MX_USB_HOST_Process(); 是获取到U盘的状态
void MX_USB_HOST_Process(void)
{
USBH_Process(&hUsbHostFS);
}
static void USBH_UserProcess(USBH_HandleTypeDef *phost, uint8_t id)
{
switch (id)
{
case HOST_USER_SELECT_CONFIGURATION:
break;
case HOST_USER_DISCONNECTION:
Appli_state = APPLICATION_DISCONNECT;
break;
case HOST_USER_CLASS_ACTIVE:
Appli_state = APPLICATION_READY;
break;
case HOST_USER_CONNECTION:
Appli_state = APPLICATION_START;
break;
default:
break;
}
}
当收到的消息是:
1. HOST_USER_CLASS_ACTIVE, 表明U盘驱动和文件系统已经可以读出文件了, 执行: read_write_U_disk_file_data();
2. HOST_USER_DISCONNECTION和HOST_USER_CONNECTION 表示u盘的拔插
* read_write_U_disk_file_data(); 里面怎样读文件:
FATFS fatfs;
FIL file;
DIR dir;
FILINFO fileInfo;
static void MSC_Application(void)
{
FRESULT res;
res = f_mount(&fatfs, "0:/", 1);
if (res != FR_OK)
{ // 无法挂载文件
f_mount(NULL, "", 0);
return;
}
res = f_opendir(&dir, "0:/");
if (res != FR_OK)
{ // 无法打开目录
f_mount(NULL, "", 0);
return;
}
while ((f_readdir(&dir, &fileInfo) == FR_OK) && (fileInfo.fname[0] != '\0'))
{
if (fileInfo.fattrib & AM_DIR)
{
continue;
}
if (0 == strcmp(fileInfo.altname, "readme.bin"))
{
res = f_open(&file, fileInfo.altname, FA_READ);
if (res != FR_OK)
{ // 无法打开文件
f_mount(NULL, "", 0);
return;
}
user_read_bin(&file);
f_closedir(&dir);
f_mount(NULL, "", 0);
}
}
f_closedir(&dir);
f_mount(NULL, "", 0);
}
uint8_t user_read_bin(FIL *file)
{
uint8_t ret = 0;
UINT bytes_read;
uint8_t ucAppPageBufer[1024]
while (((ret = f_read(file, ucAppPageBufer, 1024, &bytes_read)) == FR_OK)
&& (bytes_read > 0))
{
// 处理读取的数据, 存在ucAppPageBufer里面, 1024个byte'
}
f_close(file);
f_mount(NULL, "", 0);
return ret;
}
上面的函数就是示例怎样读出bin文件的.
觉得有帮助的兄弟记得点赞