CUBEMX STM32F105RB U盤讀寫詳細教程
abin 42817001
- 打開cubemx軟件,
2.選擇單片機型號,本文選stm32f105rb
3.設置RCC,
4.設置時鐘
1 根據開發板選外部晶振,一般是8Mhz。
2 選通外部晶振通道,由於ubs要使用48Mhz頻率,內部頻率無法提供
3工具單片機選擇主頻,
1 2 3步驟無先後順序,
5.選擇調試端口,這裏使用UART2,可以根據需要選擇其他的uart
6.配置USB順序
檢查usb時鐘是否是48Mhz,一般軟件會自動設置好。
Host 設置 見usbh_conf.h 65-90行
7.設置PC9腳輸出
由於本開發板的usb通過PC9低電平導通三極管給usb供電,所以要另外設置PC9腳, 如與本板不同可忽略本步驟。
8.管腳佈局查看
9.PROJECT配置
10.點擊軟件界面的右上角的 產生代碼,可能會出現一個警告窗口,不必理會,點YES
軟件會自動生成KEIL需要的相關工程文件,點打開工程,然後就自動打開KEIL,
11.Keil 操作
12.Cubemx生成的main.c還不能直接使用,要定義變量 回調函數 USB操作函數等
代碼要保存在cubemx設定好的用戶代碼區域,如果硬件變動生成新代碼,用戶自定義的代碼就會保留。
13.下面是main.c修改後的文件,紅色部分是增加的內容,其他文件不需修改
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : main.c
* @brief : Main program body
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2019 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "fatfs.h"
#include "usart.h"
#include "usb_host.h"
#include "gpio.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
/* USER CODE END PTD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
//定義PC9腳,如不需要可取消
#define USB_POWER_Pin GPIO_PIN_9
#define USB_POWER_GPIO_Port GPIOC
/* USER CODE END PM */
/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN PV */
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
void MX_USB_HOST_Process(void);
/* USER CODE BEGIN PFP */
FATFS USBDISKFatFs; /* File system object for USB disk logical drive */
FIL MyFile; /* File object */
extern ApplicationTypeDef Appli_state;
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
//下面2個函數 使能、禁止HCD_Port的回調函數,勿修改,必須
/**
* @brief Port Port Enabled callback.
* @param hhcd: HCD handle
* @retval None
*/
void HAL_HCD_PortEnabled_Callback(HCD_HandleTypeDef *hhcd)
{
USBH_LL_PortEnabled(hhcd->pData);
}
/**
* @brief Port Port Disabled callback.
* @param hhcd: HCD handle
* @retval None
*/
void HAL_HCD_PortDisabled_Callback(HCD_HandleTypeDef *hhcd)
{
USBH_LL_PortDisabled(hhcd->pData);
}
/**
* @brief Main routine for Mass Storage Class
* @param None
* @retval None
*/
//下面函數操作USB 文件讀寫,可根據需要修改,函數名可自定義
void MSC_Application(void)
{
/* FatFs function common result code description: */
/* FR_OK = 0, (0) Succeeded */
/* FR_DISK_ERR, (1) A hard error occurred in the low level disk I/O layer */
/* FR_INT_ERR, (2) Assertion failed */
/* FR_NOT_READY, (3) The physical drive cannot work */
/* FR_NO_FILE, (4) Could not find the file */
/* FR_NO_PATH, (5) Could not find the path */
/* FR_INVALID_NAME, (6) The path name format is invalid */
/* FR_DENIED, (7) Access denied due to prohibited access or directory full */
/* FR_EXIST, (8) Access denied due to prohibited access */
/* FR_INVALID_OBJECT, (9) The file/directory object is invalid */
/* FR_WRITE_PROTECTED, (10) The physical drive is write protected */
/* FR_INVALID_DRIVE, (11) The logical drive number is invalid */
/* FR_NOT_ENABLED, (12) The volume has no work area */
/* FR_NO_FILESYSTEM, (13) There is no valid FAT volume */
/* FR_MKFS_ABORTED, (14) The f_mkfs() aborted due to any parameter error */
/* FR_TIMEOUT, (15) Could not get a grant to access the volume within defined period */
/* FR_LOCKED, (16) The operation is rejected according to thex file sharing policy */
/* FR_NOT_ENOUGH_CORE, (17) LFN working buffer could not be allocated */
/* FR_TOO_MANY_OPEN_FILES, (18) Number of open files > _FS_SHARE */
/* FR_INVALID_PARAMETER (19) Given parameter is invalid */
FRESULT res; /* FatFs function common result code */
uint32_t byteswritten, bytesread; /* File write/read counts */
uint8_t wtext[] = "Hello Test USB!"; /* File write buffer */
uint8_t rtext[100]; /* File read buffer */
/* Register the file system object to the FatFs module */
res = f_mount(&USBDISKFatFs, (TCHAR const*)USBHPath, 0);
if(res != FR_OK)
{
/* FatFs Initialization Error */
USBH_UsrLog("f_mount error: %d", res);
Error_Handler();
}
USBH_UsrLog("create the file in: %s", USBHPath);
/* Create and Open a new text file object with write access */
res = f_open(&MyFile, "USBHost.txt", FA_CREATE_ALWAYS | FA_WRITE);
if(res != FR_OK)
{
/* 'hello.txt' file Open for write Error */
USBH_UsrLog("f_open with write access error: %d", res);
Error_Handler();
}
/* Write data to the text file */
res = f_write(&MyFile, wtext, sizeof(wtext), (void *)&byteswritten);
if((byteswritten == 0) || (res != FR_OK))
{
/* 'hello.txt' file Write or EOF Error */
USBH_UsrLog("file write or EOF error: %d", res);
Error_Handler();
}
/* Close the open text file */
f_close(&MyFile);
/* Open the text file object with read access */
res = f_open(&MyFile, "USBHost.txt", FA_READ);
if(res != FR_OK)
{
/* 'hello.txt' file Open for read Error */
USBH_UsrLog("f_open with read access error: %d", res);
Error_Handler();
}
/* Read data from the text file */
res = f_read(&MyFile, rtext, sizeof(rtext), (void *)&bytesread);
if((bytesread == 0) || (res != FR_OK))
{
/* 'hello.txt' file Read or EOF Error */
USBH_UsrLog("f_read error: %d", res);
Error_Handler();
}
/* Close the open text file */
f_close(&MyFile);
/* Compare read data with the expected data */
if((bytesread != byteswritten))
{
/* Read data is different from the expected data */
USBH_UsrLog("file doesn't match");
Error_Handler();
}
/* Success of the demo: no error occurrence */
USBH_UsrLog("USBHost.txt was created into the disk");
/* Unlink the USB disk I/O driver */
FATFS_UnLinkDriver(USBHPath);
}
/* USER CODE END 0 */
/**
* @brief The application entry point.
* @retval int
*/
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_USART2_UART_Init();
MX_FATFS_Init();
MX_USB_HOST_Init();
/* USER CODE BEGIN 2 */
//拉低PC9,如無該設置可取消
HAL_GPIO_WritePin(USB_POWER_GPIO_Port, USB_POWER_Pin, GPIO_PIN_RESET);
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
printf("STM32 start ok!\n");
while (1)
{
/* USER CODE END WHILE */
MX_USB_HOST_Process();
/* USER CODE BEGIN 3 */
//判斷USB是否進入準備狀態APPLICATION_READY
switch(Appli_state)
{
/**
* The generated code from STM32CubeMX has two "confusing" application states
* APPLICATION_START on HOST_USER_CONNECTION and APPLICATION_READY on HOST_USER_CLASS_ACTIVE.
* Any FatFs commands should be executed after APPLICATION_STATE_READY is reached."
*/
case APPLICATION_READY:
printf("ready ok\n");
MSC_Application();
Appli_state = APPLICATION_IDLE;
break;
case APPLICATION_IDLE:
default:
break;
}
}
/* USER CODE END 3 */
}
/**
* @brief System Clock Configuration
* @retval None
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};
/** Initializes the CPU, AHB and APB busses clocks
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.Prediv1Source = RCC_PREDIV1_SOURCE_HSE;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
RCC_OscInitStruct.PLL2.PLL2State = RCC_PLL_NONE;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/** Initializes the CPU, AHB and APB busses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
{
Error_Handler();
}
PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_USB;
PeriphClkInit.UsbClockSelection = RCC_USBCLKSOURCE_PLL_DIV3;
if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
{
Error_Handler();
}
/** Configure the Systick interrupt time
*/
__HAL_RCC_PLLI2S_ENABLE();
}
/* USER CODE BEGIN 4 */
//##############
//USB調試信息輸出要用到printf,必須設置
//如果printf不能使用,需#include <stdio.h>,如使用UART1,則下面的huart2要改成huart1
/* fputc */
int fputc(int ch, FILE *f)
{
HAL_UART_Transmit(&huart2 , (uint8_t *)&ch, 1 , 0xffff);
while (huart2.gState != HAL_UART_STATE_READY);//Loop until the end of transmission 每個發送都值得優化
return ch;
}
/* USER CODE END 4 */
/**
* @brief This function is executed in case of error occurrence.
* @retval None
*/
void Error_Handler(void)
{
/* USER CODE BEGIN Error_Handler_Debug */
/* User can add his own implementation to report the HAL error return state */
/* USER CODE END Error_Handler_Debug */
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t *file, uint32_t line)
{
/* USER CODE BEGIN 6 */
/* User can add his own implementation to report the file name and line number,
tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
14.程序運行結果如下(啓動後插上U盤,然後拔出U盤)。
由於FATFS系統版本不同,可能有些U盤無法識別。比如3.0 U盤
- 是MX_USB_HOST_Process(); 函數產生的信息
- 是 void MSC_Application(void) 輸出的內容
15.網友介紹F407可以直接使用CUBEMX生成的文件,無需修改。使用F407的朋友可自行驗證。
16.本文內容在STM32F105RB + cubemx5.4 + keilMDK5.2 + J-LINK V8.0調試通過。
17.本文由abin 42817001整理,
18.感謝 @廈門-電梯-窩瓜(892219846) @大拇指[em]IT(2571393392) 指點、解惑。
19.完成時間 2011.09 補充:日期有誤,實爲2019.09
cubemx+keil 源碼 下載地址 https://download.csdn.net/download/silno/11967893