本帖最后由 jinglixixi_457498010 于 2025-5-23 13:57 编辑

在开发板的例程中提供了测试SD卡读写的程序,名称为FatFs_uSD_Standalone,其功能是在加挂外部SD卡的情况下,对SD卡进行测试并以指示灯的形式加以指示是否成功。

其主程序为:

int main(void)
  • {
  •   HAL_Init();
  •   SystemClock_Config();
  •   ADAFRUIT_802_SD_Init(0);
  •   BSP_LED_Init(LED2);
  •   BSP_LED_Init(LED3);
  •   MX_GPIO_Init();
  •   MX_FATFS_Init();
  •   while (1)
  •   {
  •     ProcessStatus = MX_FATFS_Process();
  •     if (ProcessStatus == APP_ERROR)
  •     {
  •       Error_Handler();
  •     }
  •     else if (ProcessStatus == APP_OK)
  •     {
  •       Success_Handler();
  •     }
  •   }
  • }
  • 复制代码

    相应的判别指示函数为:

    <pre>void Success_Handler(void)
  • {
  •   BSP_LED_On(LED2);
  •   while(1)
  •   {
  •   }
  • }

  • void Error_Handler(void)
  • {
  •   BSP_LED_On(LED3);
  •   while(1)
  •   {
  •   }
  • }
  • </pre>
  • 复制代码

    由此可知,在通过测试的情况下是点亮LED2,若是测试失败则点亮红色的LED3。

    那该如何连接外挂的SD卡呢?

    经反复查找,SD卡与开发板的连接关系为:

    SD_SPI_CS   ---- PB5

    SD_SPI_MOSI ---- PA7

    SD_SPI_MISO ---- PA6

    SD_SPI_SCK---- PA5


    在连接外部SD卡的情况下,经程序的编译和下载,其运行结果如下图所示,是红色的LED3被点亮说明读写测试失败。

    image.png

    测试结果


    从相关的程序调用关系看,在正常的情况下要执行的是该程序:

    <pre>static int32_t FS_FileOperations(void)
  • {
  •   FRESULT res;
  •   uint32_t byteswritten, bytesread;
  •   uint8_t wtext[] = "This is STM32 working with FatFs and uSD diskio driver";
  •   uint8_t rtext[100];
  •   if(f_mount(&SDFatFs, (TCHAR const*)SDPath, 0) == FR_OK)
  •   {
  •     if(f_open(&SDFile, "STM32.TXT", FA_CREATE_ALWAYS | FA_WRITE) == FR_OK)
  •     {
  •       res = f_write(&SDFile, wtext, sizeof(wtext), (void *)&byteswritten);
  •       if((byteswritten > 0) && (res == FR_OK))
  •       {
  •         f_close(&SDFile);
  •         if(f_open(&SDFile, "STM32.TXT", FA_READ) == FR_OK)
  •         {
  •           res = f_read(&SDFile, rtext, sizeof(rtext), (void *)&bytesread);
  •           if((bytesread > 0) && (res == FR_OK))
  •           {
  •             f_close(&SDFile);
  •             if((bytesread == byteswritten))
  •             {
  •               if(Buffercmp((uint32_t *)rtext, (uint32_t *)wtext, sizeof(rtext)))
  •               {  
  •                 return 0;
  •               }
  •             }
  •           }
  •         }
  •       }
  •     }
  •   }
  •   return -1;
  • }
  • </pre>
  • 复制代码

    也就是说,它会在SD卡上先创建一个名为STM32.TXT的文件,并向文件内写入指定的文字信息 "This is STM32 working with FatFs and uSD diskio driver"。然后,再对该文件进行读取处理,并判别读写的内容是否一致。

    应该说这项功能是十分应用价值的,希望它能更加有效和稳定。