栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

STM32之完成对SD卡的数据写入

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

STM32之完成对SD卡的数据写入

实验步骤

链接:https://pan.baidu.com/s/1MFVI8M022kbmuOlGbAl6aw 提取码:xhc1
下载源程序
下载完成后打开
修改此处,否则会有乱码

主函数

int main(void)
{
  

  
  

  

  
  HAL_Init();

  

  

  
  SystemClock_Config();

  

  

  
  MX_GPIO_Init();
  MX_SPI1_Init();
  MX_FATFS_Init();
  MX_USART1_UART_Init();
  
	
	HAL_UART_Receive_IT(&huart1,&aRxBuffer1,1); 	//enable uart	

	printf(" mian rn");

	Get_SDCard_Capacity();	//得到使用内存并选择格式化



  

  
  
  while (1)
  {		
		WritetoSD(WriteBuffer,sizeof(WriteBuffer));			
		HAL_Delay(500);
		WriteBuffer[0] = WriteBuffer[0] +0;
		WriteBuffer[1] = WriteBuffer[1] +1;
		write_cnt ++;		
		while(write_cnt > 10)
		{	
			printf(" while rn");
			HAL_Delay(500);
		}			
    
    
  }
  
}

SD卡写入函数

void WritetoSD(BYTE write_buff[],uint8_t bufSize)
{
	FATFS fs;
	FIL file;
	uint8_t res=0;
	UINT Bw;	
	
	res = SD_init();		//SD卡初始化
	
	if(res == 1)
	{
		printf("SD卡初始化失败! rn");		
	}
	else
	{
		printf("SD卡初始化成功! rn");		
	}
	
	res=f_mount(&fs,"0:",1);		//挂载
	
//	if(test_sd == 0)		//用于测试格式化
	if(res == FR_NO_FILESYSTEM)		//没有文件系统,格式化
	{
//		test_sd =1;				//用于测试格式化
		printf("没有文件系统! rn");		
		res = f_mkfs("", 0, 0);		//格式化sd卡
		if(res == FR_OK)
		{
			printf("格式化成功! rn");		
			res = f_mount(NULL,"0:",1); 		//格式化后先取消挂载
			res = f_mount(&fs,"0:",1);			//重新挂载	
			if(res == FR_OK)
			{
				printf("SD卡已经成功挂载,可以进进行文件写入测试!rn");
			}	
		}
		else
		{
			printf("格式化失败! rn");		
		}
	}
	else if(res == FR_OK)
	{
		printf("挂载成功! rn");		
	}
	else
	{
		printf("挂载失败! rn");
	}	
	
	res = f_open(&file,SD_FileName,FA_OPEN_ALWAYS |FA_WRITE);
	if((res & FR_DENIED) == FR_DENIED)
	{
		printf("卡存储已满,写入失败!rn");		
	}
	
	f_lseek(&file, f_size(&file));//确保写词写入不会覆盖之前的数据
	if(res == FR_OK)
	{
		printf("打开成功/创建文件成功! rn");		
		res = f_write(&file,write_buff,bufSize,&Bw);		//写数据到SD卡
		if(res == FR_OK)
		{
			printf("文件写入成功! rn");			
		}
		else
		{
			printf("文件写入失败! rn");
		}		
	}
	else
	{
		printf("打开文件失败!rn");
	}	
	
	f_close(&file);						//关闭文件		
	f_mount(NULL,"0:",1);		 //取消挂载
	
}


接线



修改输入

输出三行

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/675891.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号