> 技术文档 > STM32使用软件模拟spi读写sd卡(使用SD卡读卡器模块)

STM32使用软件模拟spi读写sd卡(使用SD卡读卡器模块)


1.引言

介绍SD卡在嵌入式系统中的常见应用场景及重要性。
简述硬件SPI和软件模拟SPI的优缺点,说明软件模拟SPI的适用场景(如引脚资源紧张或硬件SPI被占用时)。
明确本文目标:通过软件模拟SPI实现STM32与SD卡的通信。
开发板:STM32F103RCT6
模块:读卡器模块(SD卡的内存一定要在32G以下)


2.SD卡与SPI协议基础

SD卡的物理结构及通信协议概述。

                                        
                                                                图SD卡物理结构

        SD卡有自己的寄存器,但他不能直接进行读写操作,需要通过命令来控制,SDIOx协议定义了一些命令用于实现某一特定功能,SD卡就根据收到的命令对内部寄存器进行修改。SPI协议童谣也可做到发送命令,但是有些SD卡的命令SPI并不支持。

SPI模式下的引脚定义(CS、CLK、MISO、MOSI)和SPI协议的工作机制(时钟极性、相位、数据格式)及软件模拟的核心逻辑。
详情可以看快速了解spi协议

一个完整的SD卡操作过程是:主机发起“命令”,SD卡根据命令内容选择是否发送响应信息及数据等,如果是数据读/写操作,主机还需要发送停止读/写数据的命令来结束本次操作,直意味这主机发起命令后,SD卡卡伊没有响应,数据等过程,这取决与命令的含义。


图SD卡命令格式

        SD 卡的命令固定为 48 位,由 6 个字节组成,字节 1 的最高 2 位固定为 01,低 6 位为命令 号(比如 CMD16,为 10000B 即 16 进制的 0X10,完整的 CMD16,第一个字节为 01010000, 即 0X10+0X40)。字节 2~5 为命令参数,有些命令是没有参数的。字节 6 的高七位为 CRC 值, 最低位恒定为 1。 


图SD卡控制命令格式


3.软件模拟SPI的实现步骤

GPIO配置
设置STM32的GPIO引脚为推挽输出(CLK、MOSI、CS)和浮空输入(MISO),注意引脚速度与上拉电阻配置。

/*引脚配置层*/#define SD_SPI SPI1#define SD_SPI_CLK RCC_APB2Periph_SPI1#define SD_SPI_APBxClock_FUN RCC_APB2PeriphClockCmd #define SD_SPI_SCK_PIN  GPIO_Pin_5  #define SD_SPI_SCK_GPIO_PORT GPIOC #define SD_SPI_SCK_GPIO_CLK  RCC_APB2Periph_GPIOA #define SD_SPI_MISO_PIN  GPIO_Pin_6 #define SD_SPI_MISO_GPIO_PORT GPIOC #define SD_SPI_MISO_GPIO_CLK RCC_APB2Periph_GPIOA #define SD_SPI_MOSI_PIN  GPIO_Pin_7 #define SD_SPI_MOSI_GPIO_PORT GPIOC #define SD_SPI_MOSI_GPIO_CLK RCC_APB2Periph_GPIOA #define SD_CS_PIN GPIO_Pin_4 #define SD_CS_GPIO_PORT  GPIOC  #define SD_CS_GPIO_CLK  RCC_APB2Periph_GPIOA#define SD_DETECT_PIN  GPIO_Pin_0  #define SD_DETECT_GPIO_PORT  GPIOE #define SD_DETECT_GPIO_CLK  RCC_APB2Periph_GPIOEvoid MySPI_Init(void){ /*GPIO初始化*/ GPIO_InitTypeDef GPIO_InitStructure; /*开启时钟*/ RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE); //*!< Configure SD_SPI pins: SCK */ GPIO_InitStructure.GPIO_Pin = SD_SPI_SCK_PIN; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; GPIO_Init(SD_SPI_SCK_GPIO_PORT, &GPIO_InitStructure); /*!< Configure SD_SPI pins: MOSI */ GPIO_InitStructure.GPIO_Pin = SD_SPI_MOSI_PIN; GPIO_Init(SD_SPI_MOSI_GPIO_PORT, &GPIO_InitStructure); /*!< Configure SD_SPI pins: MISO */ GPIO_InitStructure.GPIO_Pin = SD_SPI_MISO_PIN; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING; GPIO_Init(SD_SPI_MISO_GPIO_PORT, &GPIO_InitStructure); /*!< Configure SD_SPI_CS_PIN pin: SD Card CS pin */ GPIO_InitStructure.GPIO_Pin = SD_CS_PIN; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; GPIO_Init(SD_CS_GPIO_PORT, &GPIO_InitStructure); /*设置默认电平*/ SD_CS_HIGH(); //SS默认高电平 MySPI_W_SCK(1);//SCK默认低电平}

CS片选引脚由于我用的是野火老师的底层,为了不做太多修改,所以用的野火老师自己的操作。

模拟SPI时序函数
实现基本的时钟信号生成(CLK翻转)、数据发送(MOSI)与接收(MISO采样)函数,示例代码片段:

/** * 函 数:SPI写SS引脚电平 * 参 数:BitValue 协议层传入的当前需要写入SS的电平,范围0~1 * 返 回 值:无 * 注意事项:此函数需要用户实现内容,当BitValue为0时,需要置SS为低电平,当BitValue为1时,需要置SS为高电平 */void MySPI_W_SS(uint8_t BitValue) {GPIO_WriteBit(SD_CS_GPIO_PORT, SD_CS_PIN, (BitAction)BitValue);//根据BitValue,设置SS引脚的电平}/** * 函 数:SPI写SCK引脚电平 * 参 数:BitValue 协议层传入的当前需要写入SCK的电平,范围0~1 * 返 回 值:无 * 注意事项:此函数需要用户实现内容,当BitValue为0时,需要置SCK为低电平,当BitValue为1时,需要置SCK为高电平 */void MySPI_W_SCK(uint8_t BitValue){GPIO_WriteBit(SD_SPI_SCK_GPIO_PORT, SD_SPI_SCK_PIN, (BitAction)BitValue);//根据BitValue,设置SCK引脚的电平}/** * 函 数:SPI写MOSI引脚电平 * 参 数:BitValue 协议层传入的当前需要写入MOSI的电平,范围0~1 * 返 回 值:无 * 注意事项:此函数需要用户实现内容,当BitValue为0时,需要置MOSI为低电平,当BitValue为1时,需要置MOSI为高电平 */void MySPI_W_MOSI(uint8_t BitValue){GPIO_WriteBit(SD_SPI_MOSI_GPIO_PORT, SD_SPI_MOSI_PIN, (BitAction)BitValue);//根据BitValue,设置MOSI引脚的电平,BitValue要实现非0即1的特性}/** * 函 数:I2C读MISO引脚电平 * 参 数:无 * 返 回 值:协议层需要得到的当前MISO的电平,范围0~1 * 注意事项:此函数需要用户实现内容,当前MISO为低电平时,返回0,当前MISO为高电平时,返回1 */uint8_t MySPI_R_MISO(void){return GPIO_ReadInputDataBit(SD_SPI_MISO_GPIO_PORT , SD_SPI_MISO_PIN);//读取MISO电平并返回}// 软件SPI写入一个字节uint8_t SD_WriteByte(uint8_t data){ uint8_t i, receive = 0; for(i = 0; i < 8; i++) { // 设置MOSI输出 if(data & 0x80) MySPI_W_MOSI(1); else MySPI_W_MOSI(0); data <<= 1; // 产生时钟下降沿 MySPI_W_SCK(0);Delay_us(1);//Delay_us(5); // 产生时钟上升沿 MySPI_W_SCK(1); // 读取MISO输入 receive <<= 1; if(MySPI_R_MISO()) receive |= 0x01; //Delay_us(5);Delay_us(1); } return receive;}// 软件SPI读取一个字节uint8_t SD_ReadByte(void){ return SD_WriteByte(0xFF); // 发送0xFF同时接收数据}

        为了能够与SD卡通过SPI协议通信,要注意SPI的时钟相位(CPHA)和时钟极性(CPOL)的设置,如下图,我们是通过软件模拟SPI协议,所以要通过手动拉高/拉低引脚来实现通信。首先当我们通过MOSI发送一位数据后,就要先拉底再拉高时钟信号产生上升沿来告诉从机要接收数据或主机接收数据。
图SPI模式(CPOL=1,CPHA=1)

4.文件系统集成与读写实现

FATFS文件系统移植
FATFS文件系统如果想要自己移植的或就去FAT官网,需要自己实现diskio.c中的底层驱动适配(如disk_readdisk_write调用软件SPI函数)。只要能够使用SPI实现SD卡的初始化,读/写,移植一般是没有问题的。我用的是野火老师的源码。ebf_stm32f103_mini_std_code: 野火STM32F103 MINI开发板 标准库教程配套代码 (gitee.com)


5.完整代码
/** ****************************************************************************** * @file stm32_eval_spi_sd.h * @author MCD Application Team * @version V4.5.0 * @date 07-March-2011 * @brief This file contains all the functions prototypes for the stm32_eval_spi_sd * firmware driver. ****************************************************************************** * @attention * * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE * TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY * DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING * FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE * CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. * * 

© COPYRIGHT 2011 STMicroelectronics

****************************************************************************** *//* Define to prevent recursive inclusion -------------------------------------*/#ifndef __STM32_EVAL_SPI_SD_H#define __STM32_EVAL_SPI_SD_H#ifdef __cplusplus extern \"C\" {#endif/* Includes ------------------------------------------------------------------*/#include \"stm32f10x.h\"#include \"ff.h\" /** @addtogroup Utilities * @{ */ #define SD_SPI SPI1#define SD_SPI_CLK RCC_APB2Periph_SPI1#define SD_SPI_APBxClock_FUN RCC_APB2PeriphClockCmd #define SD_SPI_SCK_PIN GPIO_Pin_5 #define SD_SPI_SCK_GPIO_PORT GPIOC #define SD_SPI_SCK_GPIO_CLK RCC_APB2Periph_GPIOA #define SD_SPI_MISO_PIN GPIO_Pin_6 #define SD_SPI_MISO_GPIO_PORT GPIOC #define SD_SPI_MISO_GPIO_CLK RCC_APB2Periph_GPIOA #define SD_SPI_MOSI_PIN GPIO_Pin_7 #define SD_SPI_MOSI_GPIO_PORT GPIOC #define SD_SPI_MOSI_GPIO_CLK RCC_APB2Periph_GPIOA #define SD_CS_PIN GPIO_Pin_4 #define SD_CS_GPIO_PORT GPIOC #define SD_CS_GPIO_CLK RCC_APB2Periph_GPIOA#define SD_DETECT_PIN GPIO_Pin_0 #define SD_DETECT_GPIO_PORT GPIOE #define SD_DETECT_GPIO_CLK RCC_APB2Periph_GPIOE /** @addtogroup STM32_EVAL * @{ */ /** @addtogroup Common * @{ */ /** @addtogroup STM32_EVAL_SPI_SD * @{ */ /** @defgroup STM32_EVAL_SPI_SD_Exported_Types * @{ */ typedef enum{/** * @brief SD reponses and error flags */ SD_RESPONSE_NO_ERROR = (0x00), SD_IN_IDLE_STATE = (0x01), SD_ERASE_RESET = (0x02), SD_ILLEGAL_COMMAND = (0x04), SD_COM_CRC_ERROR = (0x08), SD_ERASE_SEQUENCE_ERROR = (0x10), SD_ADDRESS_ERROR = (0x20), SD_PARAMETER_ERROR = (0x40), SD_RESPONSE_FAILURE = (0xFF),/** * @brief Data response error */ SD_DATA_OK = (0x05), SD_DATA_CRC_ERROR = (0x0B), SD_DATA_WRITE_ERROR = (0x0D), SD_DATA_OTHER_ERROR = (0xFF)} SD_Error;/** * @brief Card Specific Data: CSD Register */ typedef struct{ __IO uint8_t CSDStruct; /*!< CSD structure */ __IO uint8_t SysSpecVersion; /*!< System specification version */ __IO uint8_t Reserved1; /*!< Reserved */ __IO uint8_t TAAC; /*!< Data read access-time 1 */ __IO uint8_t NSAC; /*!< Data read access-time 2 in CLK cycles */ __IO uint8_t MaxBusClkFrec; /*!< Max. bus clock frequency */ __IO uint16_t CardComdClasses; /*!< Card command classes */ __IO uint8_t RdBlockLen; /*!< Max. read data block length */ __IO uint8_t PartBlockRead; /*!< Partial blocks for read allowed */ __IO uint8_t WrBlockMisalign; /*!< Write block misalignment */ __IO uint8_t RdBlockMisalign; /*!< Read block misalignment */ __IO uint8_t DSRImpl; /*!< DSR implemented */ __IO uint8_t Reserved2; /*!< Reserved */ __IO uint32_t DeviceSize; /*!< Device Size */ __IO uint8_t MaxRdCurrentVDDMin; /*!< Max. read current @ VDD min */ __IO uint8_t MaxRdCurrentVDDMax; /*!< Max. read current @ VDD max */ __IO uint8_t MaxWrCurrentVDDMin; /*!< Max. write current @ VDD min */ __IO uint8_t MaxWrCurrentVDDMax; /*!< Max. write current @ VDD max */ __IO uint8_t DeviceSizeMul; /*!< Device size multiplier */ __IO uint8_t EraseGrSize; /*!< Erase group size */ __IO uint8_t EraseGrMul; /*!< Erase group size multiplier */ __IO uint8_t WrProtectGrSize; /*!< Write protect group size */ __IO uint8_t WrProtectGrEnable; /*!< Write protect group enable */ __IO uint8_t ManDeflECC; /*!< Manufacturer default ECC */ __IO uint8_t WrSpeedFact; /*!< Write speed factor */ __IO uint8_t MaxWrBlockLen; /*!< Max. write data block length */ __IO uint8_t WriteBlockPaPartial; /*!< Partial blocks for write allowed */ __IO uint8_t Reserved3; /*!< Reserded */ __IO uint8_t ContentProtectAppli; /*!< Content protection application */ __IO uint8_t FileFormatGrouop; /*!< File format group */ __IO uint8_t CopyFlag; /*!< Copy flag (OTP) */ __IO uint8_t PermWrProtect; /*!< Permanent write protection */ __IO uint8_t TempWrProtect; /*!< Temporary write protection */ __IO uint8_t FileFormat; /*!< File Format */ __IO uint8_t ECC; /*!< ECC code */ __IO uint8_t CSD_CRC; /*!< CSD CRC */ __IO uint8_t Reserved4; /*!< always 1*/} SD_CSD;/** * @brief Card Identification Data: CID Register */typedef struct{ __IO uint8_t ManufacturerID; /*!< ManufacturerID */ __IO uint16_t OEM_AppliID; /*!< OEM/Application ID */ __IO uint32_t ProdName1; /*!< Product Name part1 */ __IO uint8_t ProdName2; /*!< Product Name part2*/ __IO uint8_t ProdRev; /*!< Product Revision */ __IO uint32_t ProdSN; /*!< Product Serial Number */ __IO uint8_t Reserved1; /*!< Reserved1 */ __IO uint16_t ManufactDate; /*!< Manufacturing Date */ __IO uint8_t CID_CRC; /*!< CID CRC */ __IO uint8_t Reserved2; /*!< always 1 */} SD_CID;/** * @brief SD Card information */typedef struct{ SD_CSD SD_csd; SD_CID SD_cid; uint64_t CardCapacity; /*!< Card Capacity */ uint32_t CardBlockSize; /*!< Card Block Size */} SD_CardInfo;extern SD_CardInfo SDCardInfo;//用于存储卡的信息/** * @} */ /** @defgroup STM32_EVAL_SPI_SD_Exported_Constants * @{ */ /** * @brief Block Size */#define SD_BLOCK_SIZE 0x200/** * @brief Dummy byte */#define SD_DUMMY_BYTE 0xFF/** * @brief Start Data tokens: * Tokens (necessary because at nop/idle (and CS active) only 0xff is * on the data/command line) */#define SD_START_DATA_SINGLE_BLOCK_READ 0xFE /*!< Data token start byte, Start Single Block Read */#define SD_START_DATA_MULTIPLE_BLOCK_READ 0xFE /*!< Data token start byte, Start Multiple Block Read */#define SD_START_DATA_SINGLE_BLOCK_WRITE 0xFE /*!< Data token start byte, Start Single Block Write */#define SD_START_DATA_MULTIPLE_BLOCK_WRITE 0xFD /*!< Data token start byte, Start Multiple Block Write */#define SD_STOP_DATA_MULTIPLE_BLOCK_WRITE 0xFD /*!< Data toke stop byte, Stop Multiple Block Write *//** * @brief SD detection on its memory slot */#define SD_PRESENT ((uint8_t)0x01)#define SD_NOT_PRESENT ((uint8_t)0x00)/** * @brief Commands: CMDxx = CMD-number | 0x40 */#define SD_CMD_GO_IDLE_STATE 0 /*!< CMD0 = 0x40 */#define SD_CMD_SEND_OP_COND 1 /*!< CMD1 = 0x41 */#define SD_CMD_SEND_IF_COND8/*!< CMD8 = 0x48 */#define SD_CMD_SEND_CSD 9 /*!< CMD9 = 0x49 */#define SD_CMD_SEND_CID 10 /*!< CMD10 = 0x4A */#define SD_CMD_STOP_TRANSMISSION 12 /*!< CMD12 = 0x4C */#define SD_CMD_SEND_STATUS 13 /*!< CMD13 = 0x4D */#define SD_CMD_SET_BLOCKLEN 16 /*!< CMD16 = 0x50 */#define SD_CMD_READ_SINGLE_BLOCK 17 /*!< CMD17 = 0x51 */#define SD_CMD_READ_MULT_BLOCK 18 /*!< CMD18 = 0x52 */#define SD_CMD_SET_BLOCK_COUNT 23 /*!< CMD23 = 0x57 */#define SD_CMD_WRITE_SINGLE_BLOCK 24 /*!< CMD24 = 0x58 */#define SD_CMD_WRITE_MULT_BLOCK 25 /*!< CMD25 = 0x59 */#define SD_CMD_PROG_CSD 27 /*!< CMD27 = 0x5B */#define SD_CMD_SET_WRITE_PROT 28 /*!< CMD28 = 0x5C */#define SD_CMD_CLR_WRITE_PROT 29 /*!< CMD29 = 0x5D */#define SD_CMD_SEND_WRITE_PROT 30 /*!< CMD30 = 0x5E */#define SD_CMD_SD_ERASE_GRP_START 32 /*!< CMD32 = 0x60 */#define SD_CMD_SD_ERASE_GRP_END 33 /*!< CMD33 = 0x61 */#define SD_CMD_UNTAG_SECTOR 34 /*!< CMD34 = 0x62 */#define SD_CMD_ERASE_GRP_START 35 /*!< CMD35 = 0x63 */#define SD_CMD_ERASE_GRP_END 36 /*!< CMD36 = 0x64 */#define SD_CMD_UNTAG_ERASE_GROUP 37 /*!< CMD37 = 0x65 */#define SD_CMD_ERASE 38 /*!< CMD38 = 0x66 */#define SD_CMD_READ_OCR58 /*!< CMD58 */#define SD_CMD_APP_CMD55 /*!< CMD55 返回0x01*/#define SD_ACMD_SD_SEND_OP_COND41 /*!< ACMD41 返回0x00*///SD卡的类型#define SD_TYPE_NOT_SD 0//非SD卡#define SD_TYPE_V1 1//V1.0的卡#define SD_TYPE_V2 2 //SDSC#define SD_TYPE_V2HC 4 //SDHC /** @defgroup STM32_EVAL_SPI_SD_Exported_Macros * @{ *//** * @brief Select SD Card: ChipSelect pin low */ #define SD_CS_LOW() GPIO_ResetBits(SD_CS_GPIO_PORT, SD_CS_PIN)/** * @brief Deselect SD Card: ChipSelect pin high */ #define SD_CS_HIGH() GPIO_SetBits(SD_CS_GPIO_PORT, SD_CS_PIN)/** * @} */ /** @defgroup STM32_EVAL_SPI_SD_Exported_Functions * @{ */ void SD_DeInit(void); SD_Error SD_Init(void);uint8_t SD_Detect(void);SD_Error SD_GetCardInfo(SD_CardInfo *cardinfo);SD_Error SD_GetCardType(void);SD_Error SD_ReadBlock(uint8_t* pBuffer, uint64_t ReadAddr, uint16_t BlockSize);SD_Error SD_ReadMultiBlocks(uint8_t* pBuffer, uint64_t ReadAddr, uint16_t BlockSize, uint32_t NumberOfBlocks);SD_Error SD_WriteBlock(uint8_t* pBuffer, uint64_t WriteAddr, uint16_t BlockSize);SD_Error SD_WriteMultiBlocks(uint8_t* pBuffer, uint64_t WriteAddr, uint16_t BlockSize, uint32_t NumberOfBlocks);SD_Error SD_GetCSDRegister(SD_CSD* SD_csd);SD_Error SD_GetCIDRegister(SD_CID* SD_cid);void SD_SendCmd(uint8_t Cmd, uint32_t Arg, uint8_t Crc);SD_Error SD_GetResponse(uint8_t Response);uint8_t SD_GetDataResponse(void);SD_Error SD_GoIdleState(void);uint16_t SD_GetStatus(void);uint8_t SD_WriteByte(uint8_t byte);uint8_t SD_ReadByte(void);FRESULT f_read_co(FIL* fp, void* buff, UINT btr, UINT* br);FRESULT f_write_co(FIL* fp, const void* buff, UINT btw, UINT* bw);FRESULT create_data_file(FIL* fp,char *filename);FRESULT write_data(FIL* fp, char *filename, char *time, double ax, double ay, double az, double roll, double gx,double gy, double gz,double ax2, double ay2, double az2, double roll2, double gx2, double gy2, double gz2);#ifdef __cplusplus}#endif#endif /* __STM32_EVAL_SPI_SD_H *//** * @} *//** * @} *//** * @} *//** * @} */ /** * @} */ /******************* (C) COPYRIGHT 2011 STMicroelectronics *****END OF FILE****/
/** ****************************************************************************** * @file stm32_eval_spi_sd.c * @author MCD Application Team * @version V4.5.0 * @date 07-March-2011 * @brief This file provides a set of functions needed to manage the SPI SD * Card memory mounted on STM32xx-EVAL board (refer to stm32_eval.h * to know about the boards supporting this memory). * It implements a high level communication layer for read and write * from/to this memory. The needed STM32 hardware resources (SPI and * GPIO) are defined in stm32xx_eval.h file, and the initialization is * performed in SD_LowLevel_Init() function declared in stm32xx_eval.c * file. * You can easily tailor this driver to any other development board, * by just adapting the defines for hardware resources and * SD_LowLevel_Init() function. *  * +-------------------------------------------------------+ * |  Pin assignment  | * +-------------------------+---------------+-------------+ * | STM32 SPI Pins | SD | Pin | * +-------------------------+---------------+-------------+ * | SD_SPI_CS_PIN  | ChipSelect | 1 | * | SD_SPI_MOSI_PIN / MOSI | DataIn | 2 | * | | GND | 3 (0 V) | * | | VDD | 4 (3.3 V)| * | SD_SPI_SCK_PIN / SCLK | Clock | 5 | * | | GND | 6 (0 V) | * | SD_SPI_MISO_PIN / MISO | DataOut | 7 | * +-------------------------+---------------+-------------+ ****************************************************************************** * @attention * * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE * TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY * DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING * FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE * CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. * * 

© COPYRIGHT 2011 STMicroelectronics

****************************************************************************** *//* Includes ------------------------------------------------------------------*/#include \"./sdcard/bsp_spi_sdcard.h\"#include \"Delay.h\"#include \"stdio.h\"#include \"string.h\"#define SD_BLOCKSIZE 512 //SD卡块大小#define NULL 0//记录卡的类型uint8_t SD_Type = SD_TYPE_NOT_SD;//存储卡的类型SD_CardInfo SDCardInfo;//用于存储卡的信息 /*引脚配置层*//** * 函 数:SPI写SS引脚电平 * 参 数:BitValue 协议层传入的当前需要写入SS的电平,范围0~1 * 返 回 值:无 * 注意事项:此函数需要用户实现内容,当BitValue为0时,需要置SS为低电平,当BitValue为1时,需要置SS为高电平 */void MySPI_W_SS(uint8_t BitValue) {GPIO_WriteBit(SD_CS_GPIO_PORT, SD_CS_PIN, (BitAction)BitValue);//根据BitValue,设置SS引脚的电平}/** * 函 数:SPI写SCK引脚电平 * 参 数:BitValue 协议层传入的当前需要写入SCK的电平,范围0~1 * 返 回 值:无 * 注意事项:此函数需要用户实现内容,当BitValue为0时,需要置SCK为低电平,当BitValue为1时,需要置SCK为高电平 */void MySPI_W_SCK(uint8_t BitValue){GPIO_WriteBit(SD_SPI_SCK_GPIO_PORT, SD_SPI_SCK_PIN, (BitAction)BitValue);//根据BitValue,设置SCK引脚的电平}/** * 函 数:SPI写MOSI引脚电平 * 参 数:BitValue 协议层传入的当前需要写入MOSI的电平,范围0~1 * 返 回 值:无 * 注意事项:此函数需要用户实现内容,当BitValue为0时,需要置MOSI为低电平,当BitValue为1时,需要置MOSI为高电平 */void MySPI_W_MOSI(uint8_t BitValue){GPIO_WriteBit(SD_SPI_MOSI_GPIO_PORT, SD_SPI_MOSI_PIN, (BitAction)BitValue);//根据BitValue,设置MOSI引脚的电平,BitValue要实现非0即1的特性}/** * 函 数:I2C读MISO引脚电平 * 参 数:无 * 返 回 值:协议层需要得到的当前MISO的电平,范围0~1 * 注意事项:此函数需要用户实现内容,当前MISO为低电平时,返回0,当前MISO为高电平时,返回1 */uint8_t MySPI_R_MISO(void){return GPIO_ReadInputDataBit(SD_SPI_MISO_GPIO_PORT , SD_SPI_MISO_PIN);//读取MISO电平并返回}/** * @brief DeInitializes the SD/SD communication. * @param None * @retval None *///void SD_DeInit(void)//{//GPIO_InitTypeDef GPIO_InitStructure;// // SPI_Cmd(SD_SPI, DISABLE); /*!< SD_SPI disable */// SPI_I2S_DeInit(SD_SPI); /*!< DeInitializes the SD_SPI */// // /*!< SD_SPI Periph clock disable */// RCC_APB1PeriphClockCmd(SD_SPI_CLK, DISABLE);// /*!< DeRemap SPI3 Pins */// GPIO_PinRemapConfig(GPIO_Remap_SPI3, DISABLE); // // /*!< Configure SD_SPI pins: SCK */// GPIO_InitStructure.GPIO_Pin = SD_SPI_SCK_PIN;// GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;// GPIO_Init(SD_SPI_SCK_GPIO_PORT, &GPIO_InitStructure);// /*!< Configure SD_SPI pins: MISO */// GPIO_InitStructure.GPIO_Pin = SD_SPI_MISO_PIN;// GPIO_Init(SD_SPI_MISO_GPIO_PORT, &GPIO_InitStructure);// /*!< Configure SD_SPI pins: MOSI */// GPIO_InitStructure.GPIO_Pin = SD_SPI_MOSI_PIN;// GPIO_Init(SD_SPI_MOSI_GPIO_PORT, &GPIO_InitStructure);// /*!< Configure SD_SPI_CS_PIN pin: SD Card CS pin */// GPIO_InitStructure.GPIO_Pin = SD_CS_PIN;// GPIO_Init(SD_CS_GPIO_PORT, &GPIO_InitStructure);// /*!< Configure SD_SPI_DETECT_PIN pin: SD Card detect pin */// GPIO_InitStructure.GPIO_Pin = SD_DETECT_PIN;// GPIO_Init(SD_DETECT_GPIO_PORT, &GPIO_InitStructure);//}void MySPI_Init(void){/*GPIO初始化*/GPIO_InitTypeDef GPIO_InitStructure;/*开启时钟*/RCC_APB2PeriphClockCmd(SD_SPI_CLK, ENABLE);// /*!< Configure SD_SPI pins: SCK */ GPIO_InitStructure.GPIO_Pin = SD_SPI_SCK_PIN; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; GPIO_Init(SD_SPI_SCK_GPIO_PORT, &GPIO_InitStructure); /*!< Configure SD_SPI pins: MOSI */ GPIO_InitStructure.GPIO_Pin = SD_SPI_MOSI_PIN; GPIO_Init(SD_SPI_MOSI_GPIO_PORT, &GPIO_InitStructure); /*!< Configure SD_SPI pins: MISO */ GPIO_InitStructure.GPIO_Pin = SD_SPI_MISO_PIN; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING; GPIO_Init(SD_SPI_MISO_GPIO_PORT, &GPIO_InitStructure); /*!< Configure SD_SPI_CS_PIN pin: SD Card CS pin */ GPIO_InitStructure.GPIO_Pin = SD_CS_PIN; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; GPIO_Init(SD_CS_GPIO_PORT, &GPIO_InitStructure);/*设置默认电平*/SD_CS_HIGH();//SS默认高电平MySPI_W_SCK(1);//SCK默认低电平}/** * @brief Initializes the SD/SD communication. * @param None * @retval The SD Response: * - SD_RESPONSE_FAILURE: Sequence failed * - SD_RESPONSE_NO_ERROR: Sequence succeed */SD_Error SD_Init(void){ uint32_t i = 0; /*!< Initialize SD_SPI */MySPI_Init(); /*!< SD chip select high */ SD_CS_HIGH(); /*!< Send dummy byte 0xFF, 10 times with CS high */ /*!< Rise CS and MOSI for 80 clocks cycles */ for (i = 0; i <= 9; i++) { /*!< Send dummy byte 0xFF */ SD_WriteByte(SD_DUMMY_BYTE); } //获取卡的类型,最多尝试10次i=0;do{/*------------Put SD in SPI mode--------------*//*!10);//不支持的卡if(SD_Type == SD_TYPE_NOT_SD)return SD_RESPONSE_FAILURE;return SD_GetCardInfo(&SDCardInfo);}/** * @brief Detect if SD card is correctly plugged in the memory slot. * @param None * @retval Return if SD is detected or not */uint8_t SD_Detect(void){ __IO uint8_t status = SD_PRESENT; /*!SD_csd)); status = SD_GetCIDRegister(&(cardinfo->SD_cid));if ((SD_Type == SD_TYPE_V1) || (SD_Type == SD_TYPE_V2)){ cardinfo->CardCapacity = (cardinfo->SD_csd.DeviceSize + 1) ; cardinfo->CardCapacity *= (1 <SD_csd.DeviceSizeMul + 2)); cardinfo->CardBlockSize = 1 <SD_csd.RdBlockLen); cardinfo->CardCapacity *= cardinfo->CardBlockSize;}else if (SD_Type == SD_TYPE_V2HC){ cardinfo->CardCapacity = (uint64_t)(cardinfo->SD_csd.DeviceSize + 1) * 512 * 1024; cardinfo->CardBlockSize = 512; } /*!< Returns the reponse */ return status;}/** * @brief Reads a block of data from the SD. * @param pBuffer: pointer to the buffer that receives the data read from the * SD. * @param ReadAddr: SD\'s internal address to read from. * @param BlockSize: the SD card Data block size. * @retval The SD Response: * - SD_RESPONSE_FAILURE: Sequence failed * - SD_RESPONSE_NO_ERROR: Sequence succeed */SD_Error SD_ReadBlock(uint8_t* pBuffer, uint64_t ReadAddr, uint16_t BlockSize){ uint32_t i = 0; SD_Error rvalue = SD_RESPONSE_FAILURE;//SDHC卡块大小固定为512,且读命令中的地址的单位是sectorif (SD_Type == SD_TYPE_V2HC) { BlockSize = 512; ReadAddr /= 512; } /*!< SD chip select low */ SD_CS_LOW(); /*!< Send CMD17 (SD_CMD_READ_SINGLE_BLOCK) to read one block */ SD_SendCmd(SD_CMD_READ_SINGLE_BLOCK, ReadAddr, 0xFF); /*!< Check if the SD acknowledged the read block command: R1 response (0x00: no errors) */ if (!SD_GetResponse(SD_RESPONSE_NO_ERROR)) { /*!< Now look for the data token to signify the start of the data */ if (!SD_GetResponse(SD_START_DATA_SINGLE_BLOCK_READ)) { /*!< Read the SD block data : read NumByteToRead data */ for (i = 0; i < BlockSize; i++) { /*!< Save the received data */ *pBuffer = SD_ReadByte(); /*!< Point to the next location where the byte read will be saved */ pBuffer++; } /*!< Get CRC bytes (not really needed by us, but required by SD) */ SD_ReadByte(); SD_ReadByte(); /*!< Set response value to success */ rvalue = SD_RESPONSE_NO_ERROR; } } /*!< SD chip select high */ SD_CS_HIGH(); /*!< Send dummy byte: 8 Clock pulses of delay */ SD_WriteByte(SD_DUMMY_BYTE); /*!< Returns the reponse */ return rvalue;}/** * @brief Reads multiple block of data from the SD. * @param pBuffer: pointer to the buffer that receives the data read from the * SD. * @param ReadAddr: SD\'s internal address to read from. * @param BlockSize: the SD card Data block size. * @param NumberOfBlocks: number of blocks to be read. * @retval The SD Response: * - SD_RESPONSE_FAILURE: Sequence failed * - SD_RESPONSE_NO_ERROR: Sequence succeed */SD_Error SD_ReadMultiBlocks(uint8_t* pBuffer, uint64_t ReadAddr, uint16_t BlockSize, uint32_t NumberOfBlocks){ uint32_t i = 0, Offset = 0; SD_Error rvalue = SD_RESPONSE_FAILURE;//SDHC卡块大小固定为512,且读命令中的地址的单位是sectorif (SD_Type == SD_TYPE_V2HC) { BlockSize = 512; ReadAddr /= 512; } /*!< SD chip select low */ SD_CS_LOW(); /*!< Data transfer */ while (NumberOfBlocks--) { /*!< Send CMD17 (SD_CMD_READ_SINGLE_BLOCK) to read one block */ SD_SendCmd (SD_CMD_READ_SINGLE_BLOCK, ReadAddr + Offset, 0xFF); /*!< Check if the SD acknowledged the read block command: R1 response (0x00: no errors) */ if (SD_GetResponse(SD_RESPONSE_NO_ERROR)) { return SD_RESPONSE_FAILURE; } /*!< Now look for the data token to signify the start of the data */ if (!SD_GetResponse(SD_START_DATA_SINGLE_BLOCK_READ)) { /*!< Read the SD block data : read NumByteToRead data */ for (i = 0; i < BlockSize; i++) { /*!< Read the pointed data */ *pBuffer = SD_ReadByte(); /*!< Point to the next location where the byte read will be saved */ pBuffer++; } /*!< Set next read address*/ Offset += BlockSize; /*!< get CRC bytes (not really needed by us, but required by SD) */ SD_ReadByte(); SD_ReadByte(); /*!< Set response value to success */ rvalue = SD_RESPONSE_NO_ERROR; } else { /*!< Set response value to failure */ rvalue = SD_RESPONSE_FAILURE; } /* 添加 Send dummy byte 防止读操作失败 */ SD_WriteByte(SD_DUMMY_BYTE); } /*!< SD chip select high */ SD_CS_HIGH(); /*!< Send dummy byte: 8 Clock pulses of delay */ SD_WriteByte(SD_DUMMY_BYTE); /*!< Returns the reponse */ return rvalue;}/** * @brief Writes a block on the SD * @param pBuffer: pointer to the buffer containing the data to be written on * the SD. * @param WriteAddr: address to write on. * @param BlockSize: the SD card Data block size. * @retval The SD Response: * - SD_RESPONSE_FAILURE: Sequence failed * - SD_RESPONSE_NO_ERROR: Sequence succeed */SD_Error SD_WriteBlock(uint8_t* pBuffer, uint64_t WriteAddr, uint16_t BlockSize){ uint32_t i = 0; SD_Error rvalue = SD_RESPONSE_FAILURE;//SDHC卡块大小固定为512,且写命令中的地址的单位是sectorif (SD_Type == SD_TYPE_V2HC) { BlockSize = 512; WriteAddr /= 512; } /*!< SD chip select low */ SD_CS_LOW(); /*!< Send CMD24 (SD_CMD_WRITE_SINGLE_BLOCK) to write multiple block */ SD_SendCmd(SD_CMD_WRITE_SINGLE_BLOCK, WriteAddr, 0xFF); /*!< Check if the SD acknowledged the write block command: R1 response (0x00: no errors) */ if (!SD_GetResponse(SD_RESPONSE_NO_ERROR)) { /*!< Send a dummy byte */ SD_WriteByte(SD_DUMMY_BYTE); /*!< Send the data token to signify the start of the data */ SD_WriteByte(0xFE); /*!< Write the block data to SD : write count data by block */ for (i = 0; i < BlockSize; i++) { /*!< Send the pointed byte */ SD_WriteByte(*pBuffer); /*!< Point to the next location where the byte read will be saved */ pBuffer++; } /*!< Put CRC bytes (not really needed by us, but required by SD) */ SD_ReadByte(); SD_ReadByte(); /*!< Read data response */ if (SD_GetDataResponse() == SD_DATA_OK) { rvalue = SD_RESPONSE_NO_ERROR; } } /*!< SD chip select high */ SD_CS_HIGH(); /*!< Send dummy byte: 8 Clock pulses of delay */ SD_WriteByte(SD_DUMMY_BYTE); /*!< Returns the reponse */ return rvalue;}/** * @brief Writes many blocks on the SD * @param pBuffer: pointer to the buffer containing the data to be written on * the SD. * @param WriteAddr: address to write on. * @param BlockSize: the SD card Data block size. * @param NumberOfBlocks: number of blocks to be written. * @retval The SD Response: * - SD_RESPONSE_FAILURE: Sequence failed * - SD_RESPONSE_NO_ERROR: Sequence succeed */SD_Error SD_WriteMultiBlocks(uint8_t* pBuffer, uint64_t WriteAddr, uint16_t BlockSize, uint32_t NumberOfBlocks){ uint32_t i = 0, Offset = 0; SD_Error rvalue = SD_RESPONSE_FAILURE;//SDHC卡块大小固定为512,且写命令中的地址的单位是sectorif (SD_Type == SD_TYPE_V2HC) { BlockSize = 512; WriteAddr /= 512; } /*!< SD chip select low */ SD_CS_LOW(); /*!< Data transfer */ while (NumberOfBlocks--) { /*!< Send CMD24 (SD_CMD_WRITE_SINGLE_BLOCK) to write blocks */ SD_SendCmd(SD_CMD_WRITE_SINGLE_BLOCK, WriteAddr + Offset, 0xFF); /*!< Check if the SD acknowledged the write block command: R1 response (0x00: no errors) */ if (SD_GetResponse(SD_RESPONSE_NO_ERROR)) { return SD_RESPONSE_FAILURE; } /*!< Send dummy byte */ SD_WriteByte(SD_DUMMY_BYTE); /*!< Send the data token to signify the start of the data */ SD_WriteByte(SD_START_DATA_SINGLE_BLOCK_WRITE); /*!< Write the block data to SD : write count data by block */ for (i = 0; i < BlockSize; i++) { /*!< Send the pointed byte */ SD_WriteByte(*pBuffer); /*!< Point to the next location where the byte read will be saved */ pBuffer++; } /*!< Set next write address */ Offset += BlockSize; /*!< Put CRC bytes (not really needed by us, but required by SD) */ SD_ReadByte(); SD_ReadByte(); /*!< Read data response */ if (SD_GetDataResponse() == SD_DATA_OK) { /*!< Set response value to success */ rvalue = SD_RESPONSE_NO_ERROR; } else { /*!< Set response value to failure */ rvalue = SD_RESPONSE_FAILURE; } } /*!< SD chip select high */ SD_CS_HIGH(); /*!< Send dummy byte: 8 Clock pulses of delay */ SD_WriteByte(SD_DUMMY_BYTE); /*!< Returns the reponse */ return rvalue;}/** * @brief Read the CSD card register. * Reading the contents of the CSD register in SPI mode is a simple * read-block transaction. * @param SD_csd: pointer on an SCD register structure * @retval The SD Response: * - SD_RESPONSE_FAILURE: Sequence failed * - SD_RESPONSE_NO_ERROR: Sequence succeed */SD_Error SD_GetCSDRegister(SD_CSD* SD_csd){ uint32_t i = 0; SD_Error rvalue = SD_RESPONSE_FAILURE; uint8_t CSD_Tab[16]; /*!< SD chip select low */ SD_CS_LOW(); /*!< Send CMD9 (CSD register) or CMD10(CSD register) */ SD_SendCmd(SD_CMD_SEND_CSD, 0, 0xFF); /*!< Wait for response in the R1 format (0x00 is no errors) */ if (!SD_GetResponse(SD_RESPONSE_NO_ERROR)) { if (!SD_GetResponse(SD_START_DATA_SINGLE_BLOCK_READ)) { for (i = 0; i < 16; i++) { /*!< Store CSD register value on CSD_Tab */ CSD_Tab[i] = SD_ReadByte(); } } /*!< Get CRC bytes (not really needed by us, but required by SD) */ SD_WriteByte(SD_DUMMY_BYTE); SD_WriteByte(SD_DUMMY_BYTE); /*!< Set response value to success */ rvalue = SD_RESPONSE_NO_ERROR; } /*!< SD chip select high */ SD_CS_HIGH(); /*!< Send dummy byte: 8 Clock pulses of delay */ SD_WriteByte(SD_DUMMY_BYTE); /*!CSDStruct = (CSD_Tab[0] & 0xC0) >> 6; SD_csd->SysSpecVersion = (CSD_Tab[0] & 0x3C) >> 2; SD_csd->Reserved1 = CSD_Tab[0] & 0x03; /*!TAAC = CSD_Tab[1]; /*!NSAC = CSD_Tab[2]; /*!MaxBusClkFrec = CSD_Tab[3]; /*!CardComdClasses = CSD_Tab[4] << 4; /*!CardComdClasses |= (CSD_Tab[5] & 0xF0) >> 4; SD_csd->RdBlockLen = CSD_Tab[5] & 0x0F; /*!PartBlockRead = (CSD_Tab[6] & 0x80) >> 7; SD_csd->WrBlockMisalign = (CSD_Tab[6] & 0x40) >> 6; SD_csd->RdBlockMisalign = (CSD_Tab[6] & 0x20) >> 5; SD_csd->DSRImpl = (CSD_Tab[6] & 0x10) >> 4; SD_csd->Reserved2 = 0; /*!DeviceSize = (CSD_Tab[6] & 0x03) << 10;//V1卡与SDSC卡的信息 if ((SD_Type == SD_TYPE_V1) || (SD_Type == SD_TYPE_V2)){/*!DeviceSize |= (CSD_Tab[7]) << 2;/*!DeviceSize |= (CSD_Tab[8] & 0xC0) >> 6;SD_csd->MaxRdCurrentVDDMin = (CSD_Tab[8] & 0x38) >> 3;SD_csd->MaxRdCurrentVDDMax = (CSD_Tab[8] & 0x07);/*!MaxWrCurrentVDDMin = (CSD_Tab[9] & 0xE0) >> 5;SD_csd->MaxWrCurrentVDDMax = (CSD_Tab[9] & 0x1C) >> 2;SD_csd->DeviceSizeMul = (CSD_Tab[9] & 0x03) << 1;/*!DeviceSizeMul |= (CSD_Tab[10] & 0x80) >> 7; }//SDHC卡的信息else if (SD_Type == SD_TYPE_V2HC){SD_csd->DeviceSize = (CSD_Tab[7] & 0x3F) <DeviceSize |= (CSD_Tab[8] <DeviceSize |= (CSD_Tab[9]);} SD_csd->EraseGrSize = (CSD_Tab[10] & 0x40) >> 6; SD_csd->EraseGrMul = (CSD_Tab[10] & 0x3F) << 1; /*!EraseGrMul |= (CSD_Tab[11] & 0x80) >> 7; SD_csd->WrProtectGrSize = (CSD_Tab[11] & 0x7F); /*!WrProtectGrEnable = (CSD_Tab[12] & 0x80) >> 7; SD_csd->ManDeflECC = (CSD_Tab[12] & 0x60) >> 5; SD_csd->WrSpeedFact = (CSD_Tab[12] & 0x1C) >> 2; SD_csd->MaxWrBlockLen = (CSD_Tab[12] & 0x03) << 2; /*!MaxWrBlockLen |= (CSD_Tab[13] & 0xC0) >> 6; SD_csd->WriteBlockPaPartial = (CSD_Tab[13] & 0x20) >> 5; SD_csd->Reserved3 = 0; SD_csd->ContentProtectAppli = (CSD_Tab[13] & 0x01); /*!FileFormatGrouop = (CSD_Tab[14] & 0x80) >> 7; SD_csd->CopyFlag = (CSD_Tab[14] & 0x40) >> 6; SD_csd->PermWrProtect = (CSD_Tab[14] & 0x20) >> 5; SD_csd->TempWrProtect = (CSD_Tab[14] & 0x10) >> 4; SD_csd->FileFormat = (CSD_Tab[14] & 0x0C) >> 2; SD_csd->ECC = (CSD_Tab[14] & 0x03); /*!CSD_CRC = (CSD_Tab[15] & 0xFE) >> 1; SD_csd->Reserved4 = 1; /*!< Return the reponse */ return rvalue;}/** * @brief Read the CID card register. * Reading the contents of the CID register in SPI mode is a simple * read-block transaction. * @param SD_cid: pointer on an CID register structure * @retval The SD Response: * - SD_RESPONSE_FAILURE: Sequence failed * - SD_RESPONSE_NO_ERROR: Sequence succeed */SD_Error SD_GetCIDRegister(SD_CID* SD_cid){ uint32_t i = 0; SD_Error rvalue = SD_RESPONSE_FAILURE; uint8_t CID_Tab[16]; /*!< SD chip select low */ SD_CS_LOW(); /*!< Send CMD10 (CID register) */ SD_SendCmd(SD_CMD_SEND_CID, 0, 0xFF); /*!< Wait for response in the R1 format (0x00 is no errors) */ if (!SD_GetResponse(SD_RESPONSE_NO_ERROR)) { if (!SD_GetResponse(SD_START_DATA_SINGLE_BLOCK_READ)) { /*!< Store CID register value on CID_Tab */ for (i = 0; i < 16; i++) { CID_Tab[i] = SD_ReadByte(); } } /*!< Get CRC bytes (not really needed by us, but required by SD) */ SD_WriteByte(SD_DUMMY_BYTE); SD_WriteByte(SD_DUMMY_BYTE); /*!< Set response value to success */ rvalue = SD_RESPONSE_NO_ERROR; } /*!< SD chip select high */ SD_CS_HIGH(); /*!< Send dummy byte: 8 Clock pulses of delay */ SD_WriteByte(SD_DUMMY_BYTE); /*!ManufacturerID = CID_Tab[0]; /*!OEM_AppliID = CID_Tab[1] << 8; /*!OEM_AppliID |= CID_Tab[2]; /*!ProdName1 = CID_Tab[3] << 24; /*!ProdName1 |= CID_Tab[4] << 16; /*!ProdName1 |= CID_Tab[5] << 8; /*!ProdName1 |= CID_Tab[6]; /*!ProdName2 = CID_Tab[7]; /*!ProdRev = CID_Tab[8]; /*!ProdSN = CID_Tab[9] << 24; /*!ProdSN |= CID_Tab[10] << 16; /*!ProdSN |= CID_Tab[11] << 8; /*!ProdSN |= CID_Tab[12]; /*!Reserved1 |= (CID_Tab[13] & 0xF0) >> 4; SD_cid->ManufactDate = (CID_Tab[13] & 0x0F) << 8; /*!ManufactDate |= CID_Tab[14]; /*!CID_CRC = (CID_Tab[15] & 0xFE) >> 1; SD_cid->Reserved2 = 1; /*!< Return the reponse */ return rvalue;}/** * @brief Send 5 bytes command to the SD card. * @param Cmd: The user expected command to send to SD card. * @param Arg: The command argument. * @param Crc: The CRC. * @retval None */void SD_SendCmd(uint8_t Cmd, uint32_t Arg, uint8_t Crc){ uint32_t i = 0x00; uint8_t Frame[6]; Frame[0] = (Cmd | 0x40); /*!> 24); /*!> 16); /*!> 8); /*!< Construct byte 4 */ Frame[4] = (uint8_t)(Arg); /*!< Construct byte 5 */ Frame[5] = (Crc); /*!< Construct CRC: byte 6 */ for (i = 0; i < 6; i++) { SD_WriteByte(Frame[i]); /*!< Send the Cmd bytes */ }}/** * @brief Get SD card data response. * @param None * @retval The SD status: Read data response xxx01 * - status 010: Data accecpted * - status 101: Data rejected due to a crc error * - status 110: Data rejected due to a Write error. * - status 111: Data rejected due to other error. */uint8_t SD_GetDataResponse(void){ uint32_t i = 0; uint8_t response, rvalue; while (i <= 64) { /*!< Read resonse */ response = SD_ReadByte(); /*!< Mask unused bits */ response &= 0x1F; switch (response) { case SD_DATA_OK: { rvalue = SD_DATA_OK; break; } case SD_DATA_CRC_ERROR: return SD_DATA_CRC_ERROR; case SD_DATA_WRITE_ERROR: return SD_DATA_WRITE_ERROR; default: { rvalue = SD_DATA_OTHER_ERROR; break; } } /*!< Exit loop in case of data ok */ if (rvalue == SD_DATA_OK) break; /*!< Increment loop counter */ i++; } /*!< Wait null data */ while (SD_ReadByte() == 0); /*!< Return response */ return response;}/** * @brief Returns the SD response. * @param None * @retval The SD Response: * - SD_RESPONSE_FAILURE: Sequence failed * - SD_RESPONSE_NO_ERROR: Sequence succeed */SD_Error SD_GetResponse(uint8_t Response){ uint32_t Count = 0xFFF; /*!< Check if response is got or a timeout is happen */ while ((SD_ReadByte() != Response) && Count) { Count--; } if (Count == 0) { /*!< After time out */ return SD_RESPONSE_FAILURE; } else { /*!< Right response got */ return SD_RESPONSE_NO_ERROR; }}/** * @brief Returns the SD status. * @param None * @retval The SD status. */uint16_t SD_GetStatus(void){ uint16_t Status = 0; /*!< SD chip select low */ SD_CS_LOW(); /*!< Send CMD13 (SD_SEND_STATUS) to get SD status */ SD_SendCmd(SD_CMD_SEND_STATUS, 0, 0xFF); Status = SD_ReadByte(); Status |= (uint16_t)(SD_ReadByte() << 8); /*!< SD chip select high */ SD_CS_HIGH(); /*!< Send dummy byte 0xFF */ SD_WriteByte(SD_DUMMY_BYTE); return Status;}/** * @brief 获取SD卡的版本类型,并区分SDSC和SDHC * @param 无 * @retval The SD Response: * - SD_RESPONSE_FAILURE: Sequence failed * - SD_RESPONSE_NO_ERROR: Sequence succeed */SD_Error SD_GetCardType(void){ uint32_t i = 0;uint32_t Count = 0xFFF; uint8_t R7R3_Resp[4];uint8_t R1_Resp; SD_CS_HIGH();/*!< Send Dummy byte 0xFF */SD_WriteByte(SD_DUMMY_BYTE);/*!< SD chip select low */SD_CS_LOW(); /*!< Send CMD8 */ SD_SendCmd(SD_CMD_SEND_IF_COND, 0x1AA, 0x87); /*!< Check if response is got or a timeout is happen */ while (( (R1_Resp = SD_ReadByte()) == 0xFF) && Count) { Count--; } if (Count == 0) { /*!< After time out */ return SD_RESPONSE_FAILURE; }//响应 = 0x05 非V2.0的卡if(R1_Resp == (SD_IN_IDLE_STATE|SD_ILLEGAL_COMMAND)) { /*----------Activates the card initialization process-----------*/do{/*!< SD chip select high */SD_CS_HIGH();/*!< Send Dummy byte 0xFF */SD_WriteByte(SD_DUMMY_BYTE);/*!< SD chip select low */SD_CS_LOW();/*!< 发送CMD1完成V1 版本卡的初始化 */SD_SendCmd(SD_CMD_SEND_OP_COND, 0, 0xFF);/*!< Wait for no error Response (R1 Format) equal to 0x00 */}while (SD_GetResponse(SD_RESPONSE_NO_ERROR));//V1版本的卡完成初始化SD_Type = SD_TYPE_V1;//不处理MMC卡//初始化正常}//响应 0x01 V2.0的卡 else if (R1_Resp == SD_IN_IDLE_STATE) { /*!< 读取CMD8 的R7响应 */ for (i = 0; i < 4; i++) { R7R3_Resp[i] = SD_ReadByte(); }/*!< SD chip select high */SD_CS_HIGH();/*!< Send Dummy byte 0xFF */SD_WriteByte(SD_DUMMY_BYTE);/*!< SD chip select low */SD_CS_LOW();//判断该卡是否支持2.7-3.6V电压if(R7R3_Resp[2]==0x01 && R7R3_Resp[3]==0xAA){//支持电压范围,可以操作Count = 200;//发卡初始化指令CMD55+ACMD41do {//CMD55,以强调下面的是ACMD命令 SD_SendCmd(SD_CMD_APP_CMD, 0, 0xFF);if (!SD_GetResponse(SD_RESPONSE_NO_ERROR)) // SD_IN_IDLE_STATEreturn SD_RESPONSE_FAILURE; //超时返回//ACMD41命令带HCS检查位 SD_SendCmd(SD_ACMD_SD_SEND_OP_COND, 0x40000000, 0xFF); if(Count-- == 0) return SD_RESPONSE_FAILURE; //重试次数超时 }while(SD_GetResponse(SD_RESPONSE_NO_ERROR)); //初始化指令完成,读取OCR信息,CMD58 //-----------鉴别SDSC SDHC卡类型开始----------- Count = 200; do{/*!< SD chip select high */SD_CS_HIGH();/*!< Send Dummy byte 0xFF */SD_WriteByte(SD_DUMMY_BYTE);/*!< SD chip select low */SD_CS_LOW();/*!< 发送CMD58 读取OCR寄存器 */SD_SendCmd(SD_CMD_READ_OCR, 0, 0xFF);}while ( SD_GetResponse(SD_RESPONSE_NO_ERROR) || Count-- == 0);if(Count == 0)return SD_RESPONSE_FAILURE; //重试次数超时//响应正常,读取R3响应 /*!< 读取CMD58的R3响应 */for (i = 0; i < 4; i++){R7R3_Resp[i] = SD_ReadByte();}//检查接收到OCR中的bit30(CCS)//CCS = 0:SDSC CCS = 1:SDHC if(R7R3_Resp[0]&0x40) //检查CCS标志 { SD_Type = SD_TYPE_V2HC; } else { SD_Type = SD_TYPE_V2; } //-----------鉴别SDSC SDHC版本卡的流程结束----------- } }/*!< SD chip select high */ SD_CS_HIGH(); /*!< Send dummy byte: 8 Clock pulses of delay */ SD_WriteByte(SD_DUMMY_BYTE);//初始化正常返回return SD_RESPONSE_NO_ERROR;}/** * @brief Put SD in Idle state. * @param None * @retval The SD Response: * - SD_RESPONSE_FAILURE: Sequence failed * - SD_RESPONSE_NO_ERROR: Sequence succeed */SD_Error SD_GoIdleState(void){ /*!< SD chip select low */ SD_CS_LOW(); /*!< Send CMD0 (SD_CMD_GO_IDLE_STATE) to put SD in SPI mode */ SD_SendCmd(SD_CMD_GO_IDLE_STATE, 0, 0x95); /*!< Wait for In Idle State Response (R1 Format) equal to 0x01 */ if (SD_GetResponse(SD_IN_IDLE_STATE)) { /*!< No Idle State Response: return response failue */ return SD_RESPONSE_FAILURE; }SD_CS_HIGH();/*!< Send Dummy byte 0xFF */SD_WriteByte(SD_DUMMY_BYTE);//正常返回return SD_RESPONSE_NO_ERROR ;}// 软件SPI写入一个字节uint8_t SD_WriteByte(uint8_t data){ uint8_t i, receive = 0; for(i = 0; i < 8; i++) { // 设置MOSI输出 if(data & 0x80) MySPI_W_MOSI(1); else MySPI_W_MOSI(0); data <<= 1; // 产生时钟下降沿 MySPI_W_SCK(0);Delay_us(1);//Delay_us(5); // 产生时钟上升沿 MySPI_W_SCK(1); // 读取MISO输入 receive <<= 1; if(MySPI_R_MISO()) receive |= 0x01; //Delay_us(5);Delay_us(1); } return receive;}// 软件SPI读取一个字节uint8_t SD_ReadByte(void){ return SD_WriteByte(0xFF); // 发送0xFF同时接收数据}/** * @brief 读取文件数据,通过循环读取一小部分数据实现 * @param FIL* fp:文件对象指针 * @param void* buff:存放读出数据的首地址 * @param UINT btr:读取数据的字节数 * @param UINT* br:指示成功读取的字节个数 * @retval 操作结果 */ FRESULT f_read_co(FIL* fp, void* buff, UINT btr, UINT* br){FRESULT rc = FR_OK; // 函数返回值UINT ui_index = 0; // 当前要读的位置UINT ui_read_back = 0; // 从f_read()返回的当前读了多少个字节UINT ui_read_once = 0; // 本地调用f_read(), 要读取多少字节if (NULL != br) {*br = 0;// 如果传入的br参数不为空,则将其值设置为0}for (ui_index = 0; ui_index = SD_BLOCKSIZE) ? SD_BLOCKSIZE : (btr - ui_index);ui_read_back = 0;// 每次循环前将ui_read_back重置为0rc = f_read(fp, (BYTE*)buff + ui_index, ui_read_once, &ui_read_back);// 调用f_read()读取数据ui_index += ui_read_back;// 更新已读取的字节数if (NULL != br) {*br += ui_read_back;// 如果传入的br参数不为空,更新br的值}if (ui_read_once != ui_read_back) {break; // 如果本次读取未达到预期字节数,跳出循环,表示读取完成}}return rc;// 返回函数执行状态}/** * @brief 写入文件数据,通过循环写入一小部分数据实现 * @param FIL* fp:文件对象指针 * @param void* buff:存放写入数据的首地址 * @param UINT btr:写入数据的字节数 * @param UINT* br:指示成功写入的字节个数 * @retval 操作结果 */ FRESULT f_write_co(FIL* fp, const void* buff, UINT btw, UINT* bw){FRESULT rc = FR_OK; // 函数返回值UINT ui_index = 0; // 当前要写的内容的位置索引UINT ui_write_back = 0; // 由f_write返回的写了多少字节UINT ui_write_once = 0; // 一次写多少个字节, 必须 <= 512字节, 否则FatFs写失败(只有前512字节正确, 后面都是0)if (NULL != bw) {*bw = 0;// 如果传入的bw参数不为空,则将其值设置为0}for (ui_index = 0; ui_index = SD_BLOCKSIZE) ? SD_BLOCKSIZE : (btw - ui_index);ui_write_back = 0;// 每次循环前将ui_write_back重置为0rc = f_write(fp, (BYTE*)buff + ui_index, ui_write_once, &ui_write_back);// 调用f_write()写入数据ui_index += ui_write_back;// 更新已写入的字节数if (NULL != bw) {*bw += ui_write_back;// 如果传入的bw参数不为空,更新bw的值}if (ui_write_once != ui_write_back) {break; // 如果本次写入未达到预期字节数,跳出循环,表示写入完成}}return rc;// 返回函数执行状态}/** * @brief 写入陀螺仪数据 * @retval 操作结果 */FRESULT write_data(FIL* file, char *filename, char *time, double ax, double ay, double az, double roll, double gx,double gy, double gz,double ax2, double ay2, double az2, double roll2, double gx2, double gy2, double gz2){FRESULT res_sd; /* 文件操作结果 */UINT fnum; /* 文件成功读写数量 */char data[200];sprintf(data,\"%s,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f\\r\\n\",time,ax,ay,az,roll,gx,gy,gz,ax2,ay2,az2,roll2,gx2,gy2,gz2);//f_lseek(file,f_size(file));if(res_sd == FR_OK){res_sd=f_write(file,data,strlen(data),&fnum);if(res_sd==FR_OK){printf(\"》文件写入成功,写入字节数据:%d\\n\",fnum);}else{printf(\"!!文件写入失败:(%d)\\n\",res_sd);} }/* 不再读写,关闭文件 */return res_sd;}/** * @brief 对写入数据文件格式初始化*@param filename :写入文件名* @retval 操作结果 */FRESULT create_data_file(FIL* file,char *filename){FRESULT res_sd; /* 文件操作结果 */UINT fnum; /* 文件成功读写数量 */char data[200];sprintf(data, \"time,ax,ay,az,roll,gx,gy,gz,ax2,ay2,az2,roll2,gx2,gy2,gz2\\r\\n\");res_sd = f_open(file, filename, FA_WRITE | FA_CREATE_ALWAYS);if(res_sd == FR_OK){res_sd=f_write(file, data,strlen(data),&fnum);if(res_sd==FR_OK){printf(\"》文件格式初始化成功,写入字节数据:%d\\n\",fnum);}else{printf(\"!!文件写入失败:(%d)\\n\",res_sd);} }/* 不再读写,关闭文件 */return res_sd;}/** * @} *//** * @} *//** * @} */ /******************* (C) COPYRIGHT 2011 STMicroelectronics *****END OF FILE****/
6.调试与常见问题解决

SD卡未响应首先要排查能否正确发送命令,数据线不能接错MOSI连接MOSI,MISO连接MISO。SPI交换数据是一定要按照时序来操作,如果不能成功的话,可以适当增加延时。