当前位置:网站首页>Cubemx stm32f105rb USB flash drive reading and writing detailed tutorial
Cubemx stm32f105rb USB flash drive reading and writing detailed tutorial
2022-06-25 09:34:00 【silno】
CUBEMX STM32F105RB U Detailed course of disk reading and writing
abin 42817001
- open cubemx Software ,

2. Select the model of single chip microcomputer , Selected in this paper stm32f105rb
3. Set up RCC,

4. Set the clock

1 Select the external crystal oscillator according to the development board , It's usually 8Mhz.
2 Gate the external crystal oscillator channel , because ubs To use 48Mhz frequency , Internal frequency cannot be provided
3 The tool single chip microcomputer selects the main frequency ,
1 2 3 There is no sequence of steps ,
5. Select the debug port , Use here UART2, You can choose others as needed uart

6. To configure USB The order


Check usb Whether the clock is 48Mhz, Generally, the software will set it automatically .


Host Set up see usbh_conf.h 65-90 That's ok


7. Set up PC9 Foot output
Due to the usb adopt PC9 Low level turn on triode to usb Power supply , So you need to set it separately PC9 foot , If it is different from this board, this step can be ignored .
8. Pin layout view


9.PROJECT To configure

10. Click... In the upper right corner of the software interface
Generating code , A warning window may appear , Don't pay any attention to , spot YES

The software will automatically generate KEIL Relevant engineering documents required , Click to open the project , Then it opens automatically KEIL,

11.Keil operation

12.Cubemx Generated main.c It can't be used directly , To define variables Callback function USB Operation function, etc
The code should be saved in cubemx Set the user code area , If a hardware change generates new code , User defined code will be preserved .
13. Here is main.c Revised document , The red part is the added content , Other documents do not need to be modified
/* 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 */
// Definition PC9 foot , Cancel if not required
#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 */
// below 2 A function Can make 、 prohibit HCD_Port Callback function for , Don't modify , must
/**
* @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
*/
// The following function operations USB File read and write , It can be modified as needed , The function name can be customized
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 */
// Pull it down PC9, If there is no such setting, you can cancel
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 */
// Judge USB Whether it is ready 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 Debugging information output needs printf, You have to set
// If printf Out of commission , Need to be #include <stdio.h>, If you use UART1, Is the following huart2 To be converted into 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 Every send is worth optimizing
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. The program runs as follows ( Plug in after startup U disc , And then pull it out U disc ).
because FATFS Different system versions , There may be some U Disk unrecognized . such as 3.0 U disc
- yes MX_USB_HOST_Process(); Information generated by the function
- yes void MSC_Application(void) Output content

15. Introduction by netizens F407 You can use it directly CUBEMX Generated files , There is no need to modify . Use F407 Your friends can verify by themselves .
16. The content of this article is in STM32F105RB + cubemx5.4 + keilMDK5.2 + J-LINK V8.0 Debugging through .
17. This paper is written by abin 42817001 Arrangement ,
18. thank @ Xiamen - The elevator - Chaenomeles (892219846) @ The thumb [em]IT(2571393392) Give directions 、 To reassure .
19. Completion time 2011.09 Add : Wrong date , It is 2019.09
cubemx+keil Source code Download address https://download.csdn.net/download/silno/11967893
边栏推荐
- 【OpenCV】—输入输出XML和YAML文件
- socket编程——epoll模型
- [opencv] - Discrete Fourier transform
- When unity released webgl, jsonconvert Serializeobject() conversion failed
- Japanese online notes for postgraduate entrance examination (9): composition template
- Atguigu---17-life cycle
- How to download the school logo, school name and corporate logo on a transparent background without matting
- 2021mathorcupc topic optimal design of heat dissipation for submarine data center
- Matplotlib axvline() and axhline() functions in Matplotlib
- Analysis on the thinking of 2022 meisai C question
猜你喜欢

22 mathematical modeling contest 22 contest C

Oracle-单行函数大全

2、 Training fashion_ MNIST dataset
![[zufe school competition] difficulty classification and competition suggestions of common competitions in the school (taking Zhejiang University of Finance and economics as an example)](/img/ee/2b8aebc1c63902d4d85ff71fd45070.jpg)
[zufe school competition] difficulty classification and competition suggestions of common competitions in the school (taking Zhejiang University of Finance and economics as an example)

使用Navicat对比多环境数据库数据差异和结构差异,以及自动DML和DDL脚本

C # startup program loses double quotation marks for parameters passed. How to solve it?

How much money have I made by sticking to fixed investment for 3 years?

备战2022年金九银十必问的1000道Android面试题及答案整理,彻底解决面试的烦恼

Mapping mode of cache

Is it harder to find a job in 2020? Do a good job in these four aspects and find a good job with high salary
随机推荐
With the QQ group file storage function of super nice, you immediately have n cloud disks that are easy to download and never expire
Is it safe to open a stock account on the compass?
How to delete a blank page that cannot be deleted in word
When unity released webgl, jsonconvert Serializeobject() conversion failed
Nodejs using the express framework demo
[buuctf.reverse] 121-125
106. simple chat room 9: use socket to transfer audio
35 websites ICER must know
Atguigu---18-component
Voiceprint Technology (I): the past and present life of voiceprint Technology
Make a skylearn high-dimensional dataset_ Circles and make_ moons
[zufe expense reimbursement] zhecai invoice reimbursement specification (taking Xinmiao reimbursement as an example), which can be passed in one trip at most
Are the top ten securities companies at great risk of opening accounts and safe and reliable?
股票在线开户安全吗?找谁可以办理?
matplotlib matplotlib中plt.grid()
[final review notes] digital logic
【mysql学习笔记21】存储引擎
Work of the 15th week
Compare and explain common i/o models
Online notes on Mathematics for postgraduate entrance examination (9): a series of courses on probability theory and mathematical statistics