STM32存储左右互搏 SDIO总线FATS文件读写SD/MicroSD/TF卡
SD/MicroSD/TF卡是基于FLASH的一种常见非易失存储单元,由接口协议电路和FLASH构成。市面上由不同尺寸和不同容量的卡,手机领域用的TF卡实际就是MicroSD卡,尺寸比SD卡小,而电路和协议操作则是一样。这里介绍STM32CUBEIDE开发平台HAL库SDIO总线FATS文件操作读写SD/MicroSD/TF卡的例程。
SD/MicroSD/TF卡访问接口
SD/MicroSD/TF卡可以通过访问更快的SDIO专用协议接口或是访问慢一些的普通SPI接口进行操作,两种协议接口复用管脚。通过SDIO访问的接口连接方式如下:
其中CMD连接用于指示发送的是命令还是数据。CLK提供访问同步时钟,4根数据线(DATA0 ~ DATA3 )则实现信息双向传输。
SDIO可以操作在1bit数据线和4bit数据线模式,因为4bit数据线明显效率高于1bit数据线模式,所以1bit数据线模式很少用,只有在某种极限节省连接资源的情况下可以用1bit数据线模式,在1bit模式下,数据线DATA0用来传输数据,DATA1用作中断。在4bit数据线模式下,数据线DATA0~DATA3用于传输数据,其中DATA1复用作中断线。
例程采用STM32F103VET6芯片对4GB的TF卡进行操作,TF卡也可以插入转换卡套插入SD卡接口。
STM32工程配置
首先建立基本工程并设置时钟:
配置SDIO接口,时钟分频到1MHz,根据实际接线信号质量情况可调整提高工作频率:
配置使用DMA, 优先级可以根据需要调整:
配置FATS参数:
需要指定用于识别卡在位的输入管脚,如果硬件上并没有连接,就设定一个下拉的输入管脚并选择即可。
配置UART1作为控制和打印输出接口:
保存并生成初始工程代码:
STM32工程代码
UART串口printf打印输出实现参考:STM32 UART串口printf函数应用及浮点打印代码空间节省 (HAL)
对SD/MicroSD/TF卡的SDIO接口FATS操作可以调用HAL库函数进行,代码实现在main.c文件里,实现如下功能:
- 串口收到0x01指令,装载SD/MicroSD/TF卡
- 串口收到0x02指令,创建/打开文件并从头位置写入数据
- 串口收到0x03指令,打开文件并从头位置读入数据
- 串口收到0x04指令,创建/打开文件并从设定位置写入数据
- 串口收到0x05指令,打开文件并从设定位置读入数据
完整的main.c代码如下:
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : main.c
* @brief : Main program body
******************************************************************************
* @attention
*
* Copyright (c) 2022 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
//Written by Pegasus Yu in 2022
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "fatfs.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "stdio.h"
#include "ctype.h"
#include "string.h"
#include "usart.h"
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
__IO float usDelayBase;
void PY_usDelayTest(void)
{
__IO uint32_t firstms, secondms;
__IO uint32_t counter = 0;
firstms = HAL_GetTick()+1;
secondms = firstms+1;
while(uwTick!=firstms) ;
while(uwTick!=secondms) counter++;
usDelayBase = ((float)counter)/1000;
}
void PY_Delay_us_t(uint32_t Delay)
{
__IO uint32_t delayReg;
__IO uint32_t usNum = (uint32_t)(Delay*usDelayBase);
delayReg = 0;
while(delayReg!=usNum) delayReg++;
}
void PY_usDelayOptimize(void)
{
__IO uint32_t firstms, secondms;
__IO float coe = 1.0;
firstms = HAL_GetTick();
PY_Delay_us_t(1000000) ;
secondms = HAL_GetTick();
coe = ((float)1000)/(secondms-firstms);
usDelayBase = coe*usDelayBase;
}
void PY_Delay_us(uint32_t Delay)
{
__IO uint32_t delayReg;
__IO uint32_t msNum = Delay/1000;
__IO uint32_t usNum = (uint32_t)((Delay%1000)*usDelayBase);
if(msNum>0) HAL_Delay(msNum);
delayReg = 0;
while(delayReg!=usNum) delayReg++;
}
/* USER CODE END PTD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
/* USER CODE END PM */
/* Private variables ---------------------------------------------------------*/
SD_HandleTypeDef hsd;
DMA_HandleTypeDef hdma_sdio;
UART_HandleTypeDef huart1;
/* USER CODE BEGIN PV */
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_DMA_Init(void);
static void MX_SDIO_SD_Init(void);
static void MX_USART1_UART_Init(void);
/* USER CODE BEGIN PFP */
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
uint8_t uart1_rxd[256];
uint8_t uart1_txd[256];
uint8_t cmd;
uint8_t disk_mount_status = 0;
FIL file;
UINT bytesread;
UINT byteswritten;
uint8_t rBuffer[20]; //Buffer for read
uint8_t WBuffer[20] ={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20}; //Buffer for write
extern char SDPath[4];
/* USER CODE END 0 */
/**
* @brief The application entry point.
* @retval int
*/
int main(void)
{
/* USER CODE BEGIN 1 */
FRESULT retSD;
disk_mount_status = 0;
char * dpath = "0:"; //Disk Path
for(uint8_t i=0; i<4; i++)
{
SDPath[i] = *(dpath+i);
}
uint32_t SD_Read_Size;
const TCHAR* filepath = "0:test.txt";
/* 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_DMA_Init();
MX_SDIO_SD_Init();
MX_USART1_UART_Init();
MX_FATFS_Init();
/* USER CODE BEGIN 2 */
PY_usDelayTest();
PY_usDelayOptimize();
HAL_UART_Receive_IT(&huart1, uart1_rxd, 1);
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
if(cmd==0x01) //Mount SD
{
cmd = 0;
if(disk_mount_status==1) printf("\r\nSD mounted already\r\n");
else
{
retSD = f_mount(&SDFatFS,(TCHAR const*)SDPath,1); //SD mount
if(retSD==FR_NO_FILESYSTEM)
{
printf("\r\nFile system doesn't exist. Now to format......\r\n");
retSD = f_mkfs((TCHAR const*)SDPath,0,0); //SD format
if(retSD != FR_OK )
{
printf("\r\nFormat error: %d\r\n",retSD);
}
else
{
printf("\r\nFormat OK\r\n");
}
}
else if(retSD==FR_OK)
{
disk_mount_status = 1;
printf("\r\nSD mount successful\r\n");
}
else
{
printf("\r\nSD mount error: %d\r\n",retSD);
}
}
}
else if(cmd==2) //File creation and write
{
cmd = 0;
if(disk_mount_status==0) printf("\r\nSD not mounted: %d\r\n",retSD);
else
{
retSD = f_open( &file, filepath, FA_CREATE_ALWAYS | FA_WRITE ); //Open or create file
if(retSD == FR_OK)
{
printf("\r\nFile open or creation successful\r\n");
__disable_irq();
retSD = f_write( &file, (const void *)WBuffer, sizeof(WBuffer), &byteswritten); //Write data
__enable_irq();
if(retSD == FR_OK)
{
printf("\r\nFile write successful\r\n");
}
else
{
printf("\r\nFile write error: %d\r\n",retSD);
}
f_close(&file); //Close file
}
else
{
printf("\r\nFile open or creation error %d\r\n",retSD);
}
}
}
else if(cmd==3) //File read
{
cmd = 0;
if(disk_mount_status==0) printf("\r\nSD not mounted: %d\r\n",retSD);
else
{
retSD = f_open( &file, filepath, FA_OPEN_EXISTING | FA_READ); //Open file
if(retSD == FR_OK)
{
printf("\r\nFile open successful\r\n");
retSD = f_read( &file, (void *)rBuffer, sizeof(rBuffer), &bytesread); //Read data
if(retSD == FR_OK)
{
printf("\r\nFile read successful\r\n");
PY_Delay_us_t(200000);
SD_Read_Size = sizeof(rBuffer);
for(uint16_t i = 0;i < SD_Read_Size;i++)
{
printf("%d ", rBuffer[i]);
}
printf("\r\n");
}
else
{
printf("\r\nFile read error: %d\r\n", retSD);
}
f_close(&file); //Close file
}
else
{
printf("\r\nFile open error: %d\r\n", retSD);
}
}
}
else if(cmd==4) //File locating write
{
cmd = 0;
if(disk_mount_status==0) printf("\r\nSD not mounted: %d\r\n",retSD);
else
{
retSD = f_open( &file, filepath, FA_CREATE_ALWAYS | FA_WRITE); //Open or create file
if(retSD == FR_OK)
{
printf("\r\nFile open or creation successful\r\n");
retSD=f_lseek( &file, f_tell(&file) + sizeof(WBuffer) ); //move file operation pointer, f_tell(&file) gets file head locating
if(retSD == FR_OK)
{
__disable_irq();
retSD = f_write( &file, (const void *)WBuffer, sizeof(WBuffer), &byteswritten);
__enable_irq();
if(retSD == FR_OK)
{
printf("\r\nFile locating write successful\r\n");
}
else
{
printf("\r\nFile locating write error: %d\r\n", retSD);
}
}
else
{
printf("\r\nFile pointer error: %d\r\n",retSD);
}
f_close(&file); //Close file
}
else
{
printf("\r\nFile open or creation error %d\r\n",retSD);
}
}
}
else if(cmd==5) //File locating read
{
cmd = 0;
if(disk_mount_status==0) printf("\r\nSD not mounted: %d\r\n",retSD);
else
{
retSD = f_open(&file, filepath, FA_OPEN_EXISTING | FA_READ); //Open file
if(retSD == FR_OK)
{
printf("\r\nFile open successful\r\n");
retSD = f_lseek(&file,f_tell(&file)+ sizeof(WBuffer)/2); //move file operation pointer, f_tell(&file) gets file head locating
if(retSD == FR_OK)
{
retSD = f_read( &file, (void *)rBuffer, sizeof(rBuffer), &bytesread);
if(retSD == FR_OK)
{
printf("\r\nFile locating read successful\r\n");
PY_Delay_us_t(200000);
SD_Read_Size = sizeof(rBuffer);
for(uint16_t i = 0;i < SD_Read_Size;i++)
{
printf("%d ",rBuffer[i]);
}
printf("\r\n");
}
else
{
printf("\r\nFile locating read error: %d\r\n",retSD);
}
}
else
{
printf("\r\nFile pointer error: %d\r\n",retSD);
}
f_close(&file);
}
else
{
printf("\r\nFile open error: %d\r\n",retSD);
}
}
}
else;
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
}
/**
* @brief System Clock Configuration
* @retval None
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
/** Initializes the RCC Oscillators according to the specified parameters
* in the RCC_OscInitTypeDef structure.
*/
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.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/** Initializes the CPU, AHB and APB buses 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();
}
}
/**
* @brief SDIO Initialization Function
* @param None
* @retval None
*/
static void MX_SDIO_SD_Init(void)
{
/* USER CODE BEGIN SDIO_Init 0 */
/* USER CODE END SDIO_Init 0 */
/* USER CODE BEGIN SDIO_Init 1 */
/* USER CODE END SDIO_Init 1 */
hsd.Instance = SDIO;
hsd.Init.ClockEdge = SDIO_CLOCK_EDGE_RISING;
hsd.Init.ClockBypass = SDIO_CLOCK_BYPASS_DISABLE;
hsd.Init.ClockPowerSave = SDIO_CLOCK_POWER_SAVE_DISABLE;
hsd.Init.BusWide = SDIO_BUS_WIDE_1B;
hsd.Init.HardwareFlowControl = SDIO_HARDWARE_FLOW_CONTROL_ENABLE;
hsd.Init.ClockDiv = 71;
/* USER CODE BEGIN SDIO_Init 2 */
/* USER CODE END SDIO_Init 2 */
}
/**
* @brief USART1 Initialization Function
* @param None
* @retval None
*/
static void MX_USART1_UART_Init(void)
{
/* USER CODE BEGIN USART1_Init 0 */
/* USER CODE END USART1_Init 0 */
/* USER CODE BEGIN USART1_Init 1 */
/* USER CODE END USART1_Init 1 */
huart1.Instance = USART1;
huart1.Init.BaudRate = 115200;
huart1.Init.WordLength = UART_WORDLENGTH_8B;
huart1.Init.StopBits = UART_STOPBITS_1;
huart1.Init.Parity = UART_PARITY_NONE;
huart1.Init.Mode = UART_MODE_TX_RX;
huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart1.Init.OverSampling = UART_OVERSAMPLING_16;
if (HAL_UART_Init(&huart1) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN USART1_Init 2 */
/* USER CODE END USART1_Init 2 */
}
/**
* Enable DMA controller clock
*/
static void MX_DMA_Init(void)
{
/* DMA controller clock enable */
__HAL_RCC_DMA2_CLK_ENABLE();
/* DMA interrupt init */
/* DMA2_Channel4_5_IRQn interrupt configuration */
HAL_NVIC_SetPriority(DMA2_Channel4_5_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(DMA2_Channel4_5_IRQn);
}
/**
* @brief GPIO Initialization Function
* @param None
* @retval None
*/
static void MX_GPIO_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOC_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOD_CLK_ENABLE();
/*Configure GPIO pin : PA8 */
GPIO_InitStruct.Pin = GPIO_PIN_8;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_PULLDOWN;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
}
/* USER CODE BEGIN 4 */
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
if(huart==&huart1)
{
cmd = uart1_rxd[0];
HAL_UART_Receive_IT(&huart1, uart1_rxd, 1);
}
}
/* 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 */
__disable_irq();
while (1)
{
}
/* 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,
ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
STM32例程测试
串口指令0x01测试效果如下:
串口指令0x02测试效果如下:
串口指令0x03测试效果如下:
串口指令0x04测试效果如下:
串口指令0x05测试效果如下:
注意事项
对于STM32F4等系列,在进行卡装载(mount)操作时,需要切换为单线模式进行,否则会错误,进行数据写读前再切换为4线模式。
STM32例程下载
STM32F103VET6 SDIO总线FATS文件读写SD/MicroSD/TF卡例程下载
STM32F401RCT6 SDIO总线FATS文件读写SD/MicroSD/TF卡例程下载
–End–