×
单片机 > 单片机程序设计 > 详情

STM32之SDIO例程

发布时间:2020-06-06 发布时间:
|

移植ST官方demo,做了部分修改


#include "stm32f10x.h"

#include "sdio_sd.h"

 

/* RCC时钟配置 */

void RCC_config(void)

ErrorStatus HSEStartUpStatus;

 

/* RCC寄存器设置为默认配置 */

RCC_DeInit();

/* 打开外部高速时钟 */

RCC_HSEConfig(RCC_HSE_ON);

/* 等待外部高速时钟稳定 */

HSEStartUpStatus = RCC_WaitForHSEStartUp();

if(HSEStartUpStatus == SUCCESS) 

/* 设置HCLK = SYSCLK */

RCC_HCLKConfig(RCC_SYSCLK_Div1);

/* 设置PCLK2 = HCLK */

RCC_PCLK2Config(RCC_HCLK_Div1);

/* 设置PCLK1 = HCLK / 2 */

RCC_PCLK1Config(RCC_HCLK_Div2);

/* 设置FLASH代码延时 */

FLASH_SetLatency(FLASH_Latency_2);

/* 使能预取址缓存 */

FLASH_PrefetchBufferCmd(FLASH_PrefetchBuffer_Enable);

/* 设置PLL时钟源为HSE倍频9 72MHz */

RCC_PLLConfig(RCC_PLLSource_HSE_Div1, RCC_PLLMul_9);

/* 使能PLL */

RCC_PLLCmd(ENABLE);

/* 等待PLL稳定 */

while(RCC_GetFlagStatus(RCC_FLAG_PLLRDY) == RESET);

/* 设置PLL为系统时钟源 */

RCC_SYSCLKConfig(RCC_SYSCLKSource_PLLCLK);

/* 等待系统时钟源切换到PLL */

while(RCC_GetSYSCLKSource() != 0x08);

}

}

 

/* 中断配置 */

void NVIC_config(void)

{

/* 选择中断分组2 */

NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);

}

 

uint8_t wbuf[512];

uint8_t rbuf[512];

 

int main(void)

{

/* 时钟配置 */

RCC_config();


/* 中断配置 */

NVIC_config();

 

if(SD_Init() == SD_OK)

{

for(uint16_t i = 0; i < 512; i++)

wbuf[i] = i+1;

 

    SD_WriteBlock(wbuf, 0x00, 512);

    SD_WaitWriteOperation();

    while(SD_GetStatus() != SD_TRANSFER_OK);

 

    SD_ReadBlock(rbuf, 0x00, 512);

    SD_WaitReadOperation();

    while(SD_GetStatus() != SD_TRANSFER_OK);

}


while(1)

{

 

}

}

/**

  ******************************************************************************

  * @file    stm32_eval_sdio_sd.h

  * @author  MCD Application Team

  * @version V4.5.0

  * @date    07-March-2011

  * @brief   This file contains all the functions prototypes for the SD Card 

  *          stm32_eval_sdio_sd driver firmware library.

  ******************************************************************************

  * @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_SDIO_SD_H

#define __STM32_EVAL_SDIO_SD_H

 

#ifdef __cplusplus

 extern "C" {

#endif

 

/* Includes ------------------------------------------------------------------*/

#include "stm32f10x.h"

 

/** @addtogroup Utilities

  * @{

  */

  

/** @addtogroup STM32_EVAL

  * @{

  */ 

 

/** @addtogroup Common

  * @{

  */

  

/** @addtogroup STM32_EVAL_SDIO_SD

  * @{

  */

 

#define SDIO_FIFO_ADDRESS                ((uint32_t)0x40018080)

/** 

  * @brief  SDIO Intialization Frequency (400KHz max)

  */

#define SDIO_INIT_CLK_DIV                ((uint8_t)0xB2)

/** 

  * @brief  SDIO Data Transfer Frequency (25MHz max) 

  */

#define SDIO_TRANSFER_CLK_DIV            ((uint8_t)0x01) 

 

/** @defgroup STM32_EVAL_SDIO_SD_Exported_Types

  * @{

  */ 

typedef enum

{

/** 

  * @brief  SDIO specific error defines  

  */   

  SD_CMD_CRC_FAIL                    = (1), /*!< Command response received (but CRC check failed) */

  SD_DATA_CRC_FAIL                   = (2), /*!< Data bock sent/received (CRC check Failed) */

  SD_CMD_RSP_TIMEOUT                 = (3), /*!< Command response timeout */

  SD_DATA_TIMEOUT                    = (4), /*!< Data time out */

  SD_TX_UNDERRUN                     = (5), /*!< Transmit FIFO under-run */

  SD_RX_OVERRUN                      = (6), /*!< Receive FIFO over-run */

  SD_START_BIT_ERR                   = (7), /*!< Start bit not detected on all data signals in widE bus mode */

  SD_CMD_OUT_OF_RANGE                = (8), /*!< CMD's argument was out of range.*/

  SD_ADDR_MISALIGNED                 = (9), /*!< Misaligned address */

  SD_BLOCK_LEN_ERR                   = (10), /*!< Transferred block length is not allowed for the card or the number of transferred bytes does not match the block length */

  SD_ERASE_SEQ_ERR                   = (11), /*!< An error in the sequence of erase command occurs.*/

  SD_BAD_ERASE_PARAM                 = (12), /*!< An Invalid selection for erase groups */

  SD_WRITE_PROT_VIOLATION            = (13), /*!< Attempt to program a write protect block */

  SD_LOCK_UNLOCK_FAILED              = (14), /*!< Sequence or password error has been detected in unlock command or if there was an attempt to access a locked card */

  SD_COM_CRC_FAILED                  = (15), /*!< CRC check of the previous command failed */

  SD_ILLEGAL_CMD                     = (16), /*!< Command is not legal for the card state */

  SD_CARD_ECC_FAILED                 = (17), /*!< Card internal ECC was applied but failed to correct the data */

  SD_CC_ERROR                        = (18), /*!< Internal card controller error */

  SD_GENERAL_UNKNOWN_ERROR           = (19), /*!< General or Unknown error */

  SD_STREAM_READ_UNDERRUN            = (20), /*!< The card could not sustain data transfer in stream read operation. */

  SD_STREAM_WRITE_OVERRUN            = (21), /*!< The card could not sustain data programming in stream mode */

  SD_CID_CSD_OVERWRITE               = (22), /*!< CID/CSD overwrite error */

  SD_WP_ERASE_SKIP                   = (23), /*!< only partial address space was erased */

  SD_CARD_ECC_DISABLED               = (24), /*!< Command has been executed without using internal ECC */

  SD_ERASE_RESET                     = (25), /*!< Erase sequence was cleared before executing because an out of erase sequence command was received */

  SD_AKE_SEQ_ERROR                   = (26), /*!< Error in sequence of authentication. */

  SD_INVALID_VOLTRANGE               = (27),

  SD_ADDR_OUT_OF_RANGE               = (28),

  SD_SWITCH_ERROR                    = (29),

  SD_SDIO_DISABLED                   = (30),

  SD_SDIO_FUNCTION_BUSY              = (31),

  SD_SDIO_FUNCTION_FAILED            = (32),

  SD_SDIO_UNKNOWN_FUNCTION           = (33),

 

/** 

  * @brief  Standard error defines   

  */ 

  SD_INTERNAL_ERROR, 

  SD_NOT_CONFIGURED,

  SD_REQUEST_PENDING, 

  SD_REQUEST_NOT_APPLICABLE, 

  SD_INVALID_PARAMETER,  

  SD_UNSUPPORTED_FEATURE,  

  SD_UNSUPPORTED_HW,  

  SD_ERROR,  

  SD_OK = 0 

} SD_Error;

 

/** 

  * @brief  SDIO Transfer state  

  */   

typedef enum

{

  SD_TRANSFER_OK  = 0,

  SD_TRANSFER_BUSY = 1,

  SD_TRANSFER_ERROR

} SDTransferState;

 

/** 

  * @brief  SD Card States 

  */   

typedef enum

{

  SD_CARD_READY                  = ((uint32_t)0x00000001),

  SD_CARD_IDENTIFICATION         = ((uint32_t)0x00000002),

  SD_CARD_STANDBY                = ((uint32_t)0x00000003),

  SD_CARD_TRANSFER               = ((uint32_t)0x00000004),

  SD_CARD_SENDING                = ((uint32_t)0x00000005),

  SD_CARD_RECEIVING              = ((uint32_t)0x00000006),

  SD_CARD_PROGRAMMING            = ((uint32_t)0x00000007),

  SD_CARD_DISCONNECTED           = ((uint32_t)0x00000008),

  SD_CARD_ERROR                  = ((uint32_t)0x000000FF)

}SDCardState;

 

 

/** 

  * @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 Status 

  */

typedef struct

{

  __IO uint8_t DAT_BUS_WIDTH;

  __IO uint8_t SECURED_MODE;

  __IO uint16_t SD_CARD_TYPE;

  __IO uint32_t SIZE_OF_PROTECTED_AREA;

  __IO uint8_t SPEED_CLASS;

  __IO uint8_t PERFORMANCE_MOVE;

  __IO uint8_t AU_SIZE;

  __IO uint16_t ERASE_SIZE;

  __IO uint8_t ERASE_TIMEOUT;

  __IO uint8_t ERASE_OFFSET;

} SD_CardStatus;

 

 

/** 

  * @brief SD Card information 

  */

typedef struct

{

  SD_CSD SD_csd;

  SD_CID SD_cid;

  uint32_t CardCapacity;  /*!< Card Capacity */

  uint32_t CardBlockSize; /*!< Card Block Size */

  uint16_t RCA;

  uint8_t CardType;

} SD_CardInfo;

 

/**

  * @}

  */

  

/** @defgroup STM32_EVAL_SDIO_SD_Exported_Constants

  * @{

  */ 

 

/** 

  * @brief SDIO Commands  Index 

  */

#define SD_CMD_GO_IDLE_STATE                       ((uint8_t)0)

#define SD_CMD_SEND_OP_COND                        ((uint8_t)1)

#define SD_CMD_ALL_SEND_CID                        ((uint8_t)2)

#define SD_CMD_SET_REL_ADDR                        ((uint8_t)3) /*!< SDIO_SEND_REL_ADDR for SD Card */

#define SD_CMD_SET_DSR                             ((uint8_t)4)

#define SD_CMD_SDIO_SEN_OP_COND                    ((uint8_t)5)

#define SD_CMD_HS_SWITCH                           ((uint8_t)6)

#define SD_CMD_SEL_DESEL_CARD                      ((uint8_t)7)

#define SD_CMD_HS_SEND_EXT_CSD                     ((uint8_t)8)

#define SD_CMD_SEND_CSD                            ((uint8_t)9)

#define SD_CMD_SEND_CID                            ((uint8_t)10)

#define SD_CMD_READ_DAT_UNTIL_STOP                 ((uint8_t)11) /*!< SD Card doesn't support it */

#define SD_CMD_STOP_TRANSMISSION                   ((uint8_t)12)

#define SD_CMD_SEND_STATUS                         ((uint8_t)13)

#define SD_CMD_HS_BUSTEST_READ                     ((uint8_t)14)

#define SD_CMD_GO_INACTIVE_STATE                   ((uint8_t)15)

#define SD_CMD_SET_BLOCKLEN                        ((uint8_t)16)

#define SD_CMD_READ_SINGLE_BLOCK                   ((uint8_t)17)

#define SD_CMD_READ_MULT_BLOCK                     ((uint8_t)18)

#define SD_CMD_HS_BUSTEST_WRITE                    ((uint8_t)19)

#define SD_CMD_WRITE_DAT_UNTIL_STOP                ((uint8_t)20) /*!< SD Card doesn't support it */

#define SD_CMD_SET_BLOCK_COUNT                     ((uint8_t)23) /*!< SD Card doesn't support it */

#define SD_CMD_WRITE_SINGLE_BLOCK                  ((uint8_t)24)

#define SD_CMD_WRITE_MULT_BLOCK                    ((uint8_t)25)

#define SD_CMD_PROG_CID                            ((uint8_t)26) /*!< reserved for manufacturers */

#define SD_CMD_PROG_CSD                            ((uint8_t)27)

#define SD_CMD_SET_WRITE_PROT                      ((uint8_t)28)

#define SD_CMD_CLR_WRITE_PROT                      ((uint8_t)29)

#define SD_CMD_SEND_WRITE_PROT                     ((uint8_t)30)

#define SD_CMD_SD_ERASE_GRP_START                  ((uint8_t)32) /*!< To set the address of the first write

                                                                  block to be erased. (For SD card only) */

#define SD_CMD_SD_ERASE_GRP_END                    ((uint8_t)33) /*!< To set the address of the last write block of the

                                                                  continuous range to be erased. (For SD card only) */

#define SD_CMD_ERASE_GRP_START                     ((uint8_t)35) /*!< To set the address of the first write block to be erased.

                                                                  (For MMC card only spec 3.31) */

 

#define SD_CMD_ERASE_GRP_END                       ((uint8_t)36) /*!< To set the address of the last write block of the

                                                                  continuous range to be erased. (For MMC card only spec 3.31) */

 

#define SD_CMD_ERASE                               ((uint8_t)38)

#define SD_CMD_FAST_IO                             ((uint8_t)39) /*!< SD Card doesn't support it */

#define SD_CMD_GO_IRQ_STATE                        ((uint8_t)40) /*!< SD Card doesn't support it */

#define SD_CMD_LOCK_UNLOCK                         ((uint8_t)42)

#define SD_CMD_APP_CMD                             ((uint8_t)55)

#define SD_CMD_GEN_CMD                             ((uint8_t)56)

#define SD_CMD_NO_CMD                              ((uint8_t)64)

 

/** 

  * @brief Following commands are SD Card Specific commands.

  *        SDIO_APP_CMD should be sent before sending these commands. 

  */

#define SD_CMD_APP_SD_SET_BUSWIDTH                 ((uint8_t)6)  /*!< For SD Card only */

#define SD_CMD_SD_APP_STAUS                        ((uint8_t)13) /*!< For SD Card only */

#define SD_CMD_SD_APP_SEND_NUM_WRITE_BLOCKS        ((uint8_t)22) /*!< For SD Card only */

#define SD_CMD_SD_APP_OP_COND                      ((uint8_t)41) /*!< For SD Card only */

#define SD_CMD_SD_APP_SET_CLR_CARD_DETECT          ((uint8_t)42) /*!< For SD Card only */

#define SD_CMD_SD_APP_SEND_SCR                     ((uint8_t)51) /*!< For SD Card only */

#define SD_CMD_SDIO_RW_DIRECT                      ((uint8_t)52) /*!< For SD I/O Card only */

#define SD_CMD_SDIO_RW_EXTENDED                    ((uint8_t)53) /*!< For SD I/O Card only */

 

/** 

  * @brief Following commands are SD Card Specific security commands.

  *        SDIO_APP_CMD should be sent before sending these commands. 

  */

#define SD_CMD_SD_APP_GET_MKB                      ((uint8_t)43) /*!< For SD Card only */

#define SD_CMD_SD_APP_GET_MID                      ((uint8_t)44) /*!< For SD Card only */

#define SD_CMD_SD_APP_SET_CER_RN1                  ((uint8_t)45) /*!< For SD Card only */

#define SD_CMD_SD_APP_GET_CER_RN2                  ((uint8_t)46) /*!< For SD Card only */

#define SD_CMD_SD_APP_SET_CER_RES2                 ((uint8_t)47) /*!< For SD Card only */

#define SD_CMD_SD_APP_GET_CER_RES1                 ((uint8_t)48) /*!< For SD Card only */

#define SD_CMD_SD_APP_SECURE_READ_MULTIPLE_BLOCK   ((uint8_t)18) /*!< For SD Card only */

#define SD_CMD_SD_APP_SECURE_WRITE_MULTIPLE_BLOCK  ((uint8_t)25) /*!< For SD Card only */

#define SD_CMD_SD_APP_SECURE_ERASE                 ((uint8_t)38) /*!< For SD Card only */

#define SD_CMD_SD_APP_CHANGE_SECURE_AREA           ((uint8_t)49) /*!< For SD Card only */

#define SD_CMD_SD_APP_SECURE_WRITE_MKB             ((uint8_t)48) /*!< For SD Card only */

  

/* Uncomment the following line to select the SDIO Data transfer mode */  

#define SD_DMA_MODE                                ((uint32_t)0x00000000)

/*#define SD_POLLING_MODE                            ((uint32_t)0x00000002)*/

 

/**

  * @brief  SD detection on its memory slot

  */

#define SD_PRESENT                                 ((uint8_t)0x01)

#define SD_NOT_PRESENT                             ((uint8_t)0x00)

 

/** 

  * @brief Supported SD Memory Cards 

  */

#define SDIO_STD_CAPACITY_SD_CARD_V1_1             ((uint32_t)0x00000000)

#define SDIO_STD_CAPACITY_SD_CARD_V2_0             ((uint32_t)0x00000001)

#define SDIO_HIGH_CAPACITY_SD_CARD                 ((uint32_t)0x00000002)

#define SDIO_MULTIMEDIA_CARD                       ((uint32_t)0x00000003)

#define SDIO_SECURE_DIGITAL_IO_CARD                ((uint32_t)0x00000004)

#define SDIO_HIGH_SPEED_MULTIMEDIA_CARD            ((uint32_t)0x00000005)

#define SDIO_SECURE_DIGITAL_IO_COMBO_CARD          ((uint32_t)0x00000006)

#define SDIO_HIGH_CAPACITY_MMC_CARD                ((uint32_t)0x00000007)

 

/**

  * @}

  */ 

  

/** @defgroup STM32_EVAL_SDIO_SD_Exported_Macros

  * @{

  */ 

/**

  * @}

  */ 

 

/** @defgroup STM32_EVAL_SDIO_SD_Exported_Functions

  * @{

  */ 

void SD_DeInit(void);

SD_Error SD_Init(void);

SDTransferState SD_GetStatus(void);

SDCardState SD_GetState(void);

SD_Error SD_PowerON(void);

SD_Error SD_PowerOFF(void);

SD_Error SD_InitializeCards(void);

SD_Error SD_GetCardInfo(SD_CardInfo *cardinfo);

SD_Error SD_GetCardStatus(SD_CardStatus *cardstatus);

SD_Error SD_EnableWideBusOperation(uint32_t WideMode);

SD_Error SD_SelectDeselect(uint32_t addr);

SD_Error SD_ReadBlock(uint8_t *readbuff, uint32_t ReadAddr, uint16_t BlockSize);

SD_Error SD_ReadMultiBlocks(uint8_t *readbuff, uint32_t ReadAddr, uint16_t BlockSize, uint32_t NumberOfBlocks);

SD_Error SD_WriteBlock(uint8_t *writebuff, uint32_t WriteAddr, uint16_t BlockSize);

SD_Error SD_WriteMultiBlocks(uint8_t *writebuff, uint32_t WriteAddr, uint16_t BlockSize, uint32_t NumberOfBlocks);

SDTransferState SD_GetTransferState(void);

SD_Error SD_StopTransfer(void);

SD_Error SD_Erase(uint32_t startaddr, uint32_t endaddr);

SD_Error SD_SendStatus(uint32_t *pcardstatus);

SD_Error SD_SendSDStatus(uint32_t *psdstatus);

SD_Error SD_ProcessIRQSrc(void);

SD_Error SD_WaitReadOperation(void);

SD_Error SD_WaitWriteOperation(void);

#ifdef __cplusplus

}

#endif

 

#endif /* __STM32_EVAL_SDIO_SD_H */

/**

  * @}

  */

 

/**

  * @}

  */

 

/**

  * @}

  */

 

/**

  * @}

  */ 

 

/**

  * @}

  */ 

 

/******************* (C) COPYRIGHT 2011 STMicroelectronics *****END OF FILE****/

/**

  ******************************************************************************

  * @file    stm32_eval_sdio_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 SDIO SD 

  *          Card memory mounted on STM32xx-EVAL board (refer to stm32_eval.h

  *          to know about the boards supporting this memory). 

  *          

  *            

  *  @verbatim

  *

  *          ===================================================================

  *                                   How to use this driver

  *          ===================================================================

  *          It implements a high level communication layer for read and write 

  *          from/to this memory. The needed STM32 hardware resources (SDIO 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.

  *            

  *          A - SD Card Initialization and configuration

  *          ============================================    

  *            - To initialize the SD Card, use the SD_Init() function.  It 

  *              Initializes the SD Card and put it into StandBy State (Ready 

  *              for data transfer). This function provide the following operations:

  *           

  *              1 - Apply the SD Card initialization process at 400KHz and check

  *                  the SD Card type (Standard Capacity or High Capacity). You 

  *                  can change or adapt this frequency by adjusting the 

  *                  "SDIO_INIT_CLK_DIV" define inside the stm32xx_eval.h file. 

  *                  The SD Card frequency (SDIO_CK) is computed as follows:

  *                    

  *                     +---------------------------------------------+    

  *                     | SDIO_CK = SDIOCLK / (SDIO_INIT_CLK_DIV + 2) |

  *                     +---------------------------------------------+  

  *                          

  *                  In initialization mode and according to the SD Card standard, 

  *                  make sure that the SDIO_CK frequency don't exceed 400KHz.        

  *         

  *              2 - Get the SD CID and CSD data. All these information are

  *                  managed by the SDCardInfo structure. This structure provide

  *                  also ready computed SD Card capacity and Block size.   

  *

  *              3 - Configure the SD Card Data transfer frequency. By Default,

  *                  the card transfer frequency is set to 24MHz. You can change

  *                  or adapt this frequency by adjusting the "SDIO_TRANSFER_CLK_DIV" 

  *                  define inside the stm32xx_eval.h file.

  *                  The SD Card frequency (SDIO_CK) is computed as follows:

  *                    

  *                     +---------------------------------------------+    

  *                     | SDIO_CK = SDIOCLK / (SDIO_INIT_CLK_DIV + 2) |

  *                     +---------------------------------------------+     

  *                                    

  *                  In transfer mode and according to the SD Card standard, 

  *                  make sure that the SDIO_CK frequency don't exceed 25MHz

  *                  and 50MHz in High-speed mode switch.

  *                  To be able to use a frequency higher than 24MHz, you should

  *                  use the SDIO peripheral in bypass mode. Refer to the 

  *                  corresponding reference manual for more details.

  *                    

  *              4 -  Select the corresponding SD Card according to the address

  *                   read with the step 2.

  *                                   

  *              5 -  Configure the SD Card in wide bus mode: 4-bits data.                

  *

  *          B - SD Card Read operation

  *          ========================== 

  *           - You can read SD card by using two function: SD_ReadBlock() and

  *             SD_ReadMultiBlocks() functions. These functions support only

  *             512-byte block length.

  *           - The SD_ReadBlock() function read only one block (512-byte). This

  *             function can transfer the data using DMA controller or using 

  *             polling mode. To select between DMA or polling mode refer to 

  *             "SD_DMA_MODE" or "SD_POLLING_MODE" inside the stm32_eval_sdio_sd.h

  *             file and uncomment the corresponding line. By default the SD DMA

  *             mode is selected          

  *           - The SD_ReadMultiBlocks() function read only mutli blocks (multiple 

  *             of 512-byte). 

  *           - Any read operation should be followed by two functions to check

  *             if the DMA Controller and SD Card status.

  *              - SD_ReadWaitOperation(): this function insure that the DMA

  *                controller has finished all data transfer.

  *              - SD_GetStatus(): to check that the SD Card has finished the 

  *                data transfer and it is ready for data.

  *                  

  *           - The DMA transfer is finished by the SDIO Data End interrupt. User

  *             has to call the SD_ProcessIRQ() function inside the SDIO_IRQHandler().

  *             Don't forget to enable the SDIO_IRQn interrupt using the NVIC controller.      

  *                

  *          C - SD Card Write operation

  *          =========================== 

  *           - You can write SD card by using two function: SD_WriteBlock() and

  *             SD_WriteMultiBlocks() functions. These functions support only

  *             512-byte block length.   

  *           - The SD_WriteBlock() function write only one block (512-byte). This

  *             function can transfer the data using DMA controller or using 

  *             polling mode. To select between DMA or polling mode refer to 

  *             "SD_DMA_MODE" or "SD_POLLING_MODE" inside the stm32_eval_sdio_sd.h

  *             file and uncomment the corresponding line. By default the SD DMA

  *             mode is selected          

  *           - The SD_WriteMultiBlocks() function write only mutli blocks (multiple 

  *             of 512-byte). 

  *           - Any write operation should be followed by two functions to check

  *             if the DMA Controller and SD Card status.

  *              - SD_ReadWaitOperation(): this function insure that the DMA

  *                controller has finished all data transfer.

  *              - SD_GetStatus(): to check that the SD Card has finished the 

  *                data transfer and it is ready for data.         

  *                

  *           - The DMA transfer is finished by the SDIO Data End interrupt. User

  *             has to call the SD_ProcessIRQ() function inside the SDIO_IRQHandler().

  *             Don't forget to enable the SDIO_IRQn interrupt using the NVIC controller.      

               

  *             

  *          D - SD card status

  *          ================== 

  *           - At any time, you can check the SD Card status and get the SD card

  *             state by using the SD_GetStatus() function. This function checks

  *             first if the SD card is still connected and then get the internal

  *             SD Card transfer state.     

  *           - You can also get the SD card SD Status register by using the 

  *             SD_SendSDStatus() function.       

  *               

  *          E - Programming Model

  *          ===================== 

  *             Status = SD_Init(); // Initialization Step as described in section A

  *               

  *             // SDIO Interrupt ENABLE

  *             NVIC_InitStructure.NVIC_IRQChannel = SDIO_IRQn;

  *             NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;

  *             NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;

  *             NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;

  *             NVIC_Init(&NVIC_InitStructure);

  *             

  *             // Write operation as described in Section C

  *             Status = SD_WriteBlock(buffer, address, 512);

  *             Status = SD_WaitWriteOperation();

  *             while(SD_GetStatus() != SD_TRANSFER_OK); 

  *             

  *             Status = SD_WriteMultiBlocks(buffer, address, 512, NUMBEROFBLOCKS);

  *             Status = SD_WaitWriteOperation();

  *             while(SD_GetStatus() != SD_TRANSFER_OK);     

  *             

  *             // Read operation as described in Section B

  *             Status = SD_ReadBlock(buffer, address, 512);

  *             Status = SD_WaitReadOperation();

  *             while(SD_GetStatus() != SD_TRANSFER_OK);

  *             

  *             Status = SD_ReadMultiBlocks(buffer, address, 512, NUMBEROFBLOCKS);

  *             Status = SD_WaitReadOperation();

  *             while(SD_GetStatus() != SD_TRANSFER_OK);            

  *               

  *                                     

  *          STM32 SDIO Pin assignment

  *          =========================    

  *          +-----------------------------------------------------------+

  *          |                     Pin assignment                        |

  *          +-----------------------------+---------------+-------------+

  *          |  STM32 SDIO Pins            |     SD        |    Pin      |

  *          +-----------------------------+---------------+-------------+

  *          |      SDIO D2                |   D2          |    1        |

  *          |      SDIO D3                |   D3          |    2        |

  *          |      SDIO CMD               |   CMD         |    3        |

  *          |                             |   VCC         |    4 (3.3 V)|

  *          |      SDIO CLK               |   CLK         |    5        |

  *          |                             |   GND         |    6 (0 V)  |

  *          |      SDIO D0                |   D0          |    7        |

  *          |      SDIO D1                |   D1          |    8        |  

  *          +-----------------------------+---------------+-------------+  

  *              

  *  @endverbatim                

  *             

  ******************************************************************************

  * @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 "sdio_sd.h"

 

/** @addtogroup Utilities

  * @{

  */

  

/** @addtogroup STM32_EVAL

  * @{

  */ 

 

/** @addtogroup Common

  * @{

  */

  

/** @addtogroup STM32_EVAL_SDIO_SD

  * @brief      This file provides all the SD Card driver firmware functions.

  * @{

  */ 

 

/** @defgroup STM32_EVAL_SDIO_SD_Private_Types

  * @{

  */ 

/**

  * @}

  */ 

 

 

/** @defgroup STM32_EVAL_SDIO_SD_Private_Defines

  * @{

  */ 

/** 

  * @brief  SDIO Static flags, TimeOut, FIFO Address  

  */

#define NULL 0

#define SDIO_STATIC_FLAGS               ((uint32_t)0x000005FF)

#define SDIO_CMD0TIMEOUT                ((uint32_t)0x00010000)

 

/** 

  * @brief  Mask for errors Card Status R1 (OCR Register) 

  */

#define SD_OCR_ADDR_OUT_OF_RANGE        ((uint32_t)0x80000000)

#define SD_OCR_ADDR_MISALIGNED          ((uint32_t)0x40000000)

#define SD_OCR_BLOCK_LEN_ERR            ((uint32_t)0x20000000)

#define SD_OCR_ERASE_SEQ_ERR            ((uint32_t)0x10000000)

#define SD_OCR_BAD_ERASE_PARAM          ((uint32_t)0x08000000)

#define SD_OCR_WRITE_PROT_VIOLATION     ((uint32_t)0x04000000)

#define SD_OCR_LOCK_UNLOCK_FAILED       ((uint32_t)0x01000000)

#define SD_OCR_COM_CRC_FAILED           ((uint32_t)0x00800000)

#define SD_OCR_ILLEGAL_CMD              ((uint32_t)0x00400000)

#define SD_OCR_CARD_ECC_FAILED          ((uint32_t)0x00200000)

#define SD_OCR_CC_ERROR                 ((uint32_t)0x00100000)

#define SD_OCR_GENERAL_UNKNOWN_ERROR    ((uint32_t)0x00080000)

#define SD_OCR_STREAM_READ_UNDERRUN     ((uint32_t)0x00040000)

#define SD_OCR_STREAM_WRITE_OVERRUN     ((uint32_t)0x00020000)

#define SD_OCR_CID_CSD_OVERWRIETE       ((uint32_t)0x00010000)

#define SD_OCR_WP_ERASE_SKIP            ((uint32_t)0x00008000)

#define SD_OCR_CARD_ECC_DISABLED        ((uint32_t)0x00004000)

#define SD_OCR_ERASE_RESET              ((uint32_t)0x00002000)

#define SD_OCR_AKE_SEQ_ERROR            ((uint32_t)0x00000008)

#define SD_OCR_ERRORBITS                ((uint32_t)0xFDFFE008)

 

/** 

  * @brief  Masks for R6 Response 

  */

#define SD_R6_GENERAL_UNKNOWN_ERROR     ((uint32_t)0x00002000)

#define SD_R6_ILLEGAL_CMD               ((uint32_t)0x00004000)

#define SD_R6_COM_CRC_FAILED            ((uint32_t)0x00008000)

 

#define SD_VOLTAGE_WINDOW_SD            ((uint32_t)0x80100000)

#define SD_HIGH_CAPACITY                ((uint32_t)0x40000000)

#define SD_STD_CAPACITY                 ((uint32_t)0x00000000)

#define SD_CHECK_PATTERN                ((uint32_t)0x000001AA)

 

#define SD_MAX_VOLT_TRIAL               ((uint32_t)0x0000FFFF)

#define SD_ALLZERO                      ((uint32_t)0x00000000)

 

#define SD_WIDE_BUS_SUPPORT             ((uint32_t)0x00040000)

#define SD_SINGLE_BUS_SUPPORT           ((uint32_t)0x00010000)

#define SD_CARD_LOCKED                  ((uint32_t)0x02000000)

 

#define SD_DATATIMEOUT                  ((uint32_t)0xFFFFFFFF)

#define SD_0TO7BITS                     ((uint32_t)0x000000FF)

#define SD_8TO15BITS                    ((uint32_t)0x0000FF00)

#define SD_16TO23BITS                   ((uint32_t)0x00FF0000)

#define SD_24TO31BITS                   ((uint32_t)0xFF000000)

#define SD_MAX_DATA_LENGTH              ((uint32_t)0x01FFFFFF)

 

#define SD_HALFFIFO                     ((uint32_t)0x00000008)

#define SD_HALFFIFOBYTES                ((uint32_t)0x00000020)

 

/** 

  * @brief  Command Class Supported 

  */

#define SD_CCCC_LOCK_UNLOCK             ((uint32_t)0x00000080)

#define SD_CCCC_WRITE_PROT              ((uint32_t)0x00000040)

#define SD_CCCC_ERASE                   ((uint32_t)0x00000020)

 

/** 

  * @brief  Following commands are SD Card Specific commands.

  *         SDIO_APP_CMD should be sent before sending these commands. 

  */

#define SDIO_SEND_IF_COND               ((uint32_t)0x00000008)

 

/**

  * @}

  */ 

 

 

/** @defgroup STM32_EVAL_SDIO_SD_Private_Macros

  * @{

  */

/**

  * @}

  */ 

  

 

/** @defgroup STM32_EVAL_SDIO_SD_Private_Variables

  * @{

  */

static uint32_t CardType =  SDIO_STD_CAPACITY_SD_CARD_V1_1;

static uint32_t CSD_Tab[4], CID_Tab[4], RCA = 0;

static uint8_t SDSTATUS_Tab[16];

__IO uint32_t StopCondition = 0;

__IO SD_Error TransferError = SD_OK;

__IO uint32_t TransferEnd = 0;

SD_CardInfo SDCardInfo;

 

SDIO_InitTypeDef SDIO_InitStructure;

SDIO_CmdInitTypeDef SDIO_CmdInitStructure;

SDIO_DataInitTypeDef SDIO_DataInitStructure;   

/**

  * @}      

  */ 

 

 

/** @defgroup STM32_EVAL_SDIO_SD_Private_Function_Prototypes

  * @{

  */

static SD_Error CmdError(void);

static SD_Error CmdResp1Error(uint8_t cmd);

static SD_Error CmdResp7Error(void);

static SD_Error CmdResp3Error(void);

static SD_Error CmdResp2Error(void);

static SD_Error CmdResp6Error(uint8_t cmd, uint16_t *prca);

static SD_Error SDEnWideBus(FunctionalState NewState);

static SD_Error IsCardProgramming(uint8_t *pstatus);

static SD_Error FindSCR(uint16_t rca, uint32_t *pscr);

uint8_t convert_from_bytes_to_power_of_two(uint16_t NumberOfBytes);

  

/**

  * @}

  */ 

 

 

/** @defgroup STM32_EVAL_SDIO_SD_Private_Functions

  * @{

  */  

 

static void NVIC_Configuration(void)

{

NVIC_InitTypeDef NVIC_InitStructure;


// SDIO Interrupt ENABLE

NVIC_InitStructure.NVIC_IRQChannel = SDIO_IRQn;

NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;

NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;

NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;

NVIC_Init(&NVIC_InitStructure);

}

 

/**

  * @brief  DeInitializes the SDIO interface.

  * @param  None

  * @retval None

  */

void SD_LowLevel_DeInit(void)

{

  GPIO_InitTypeDef  GPIO_InitStructure;

  

  /*!< Disable SDIO Clock */

  SDIO_ClockCmd(DISABLE);

  

  /*!< Set Power State to OFF */

  SDIO_SetPowerState(SDIO_PowerState_OFF);

 

  /*!< DeInitializes the SDIO peripheral */

  SDIO_DeInit();

  

  /*!< Disable the SDIO AHB Clock */

  RCC_AHBPeriphClockCmd(RCC_AHBPeriph_SDIO, DISABLE);

 

  /*!< Configure PC.08, PC.09, PC.10, PC.11, PC.12 pin: D0, D1, D2, D3, CLK pin */

  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8 | GPIO_Pin_9 | GPIO_Pin_10 | GPIO_Pin_11 | GPIO_Pin_12;

  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;

  GPIO_Init(GPIOC, &GPIO_InitStructure);

 

  /*!< Configure PD.02 CMD line */

  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;

  GPIO_Init(GPIOD, &GPIO_InitStructure);

}

 

/**

  * @brief  Initializes the SD Card and put it into StandBy State (Ready for 

  *         data transfer).

  * @param  None

  * @retval None

  */

void SD_LowLevel_Init(void)

{

  GPIO_InitTypeDef  GPIO_InitStructure;

 

  /*!< GPIOC and GPIOD Periph clock enable */

  RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC | RCC_APB2Periph_GPIOD, ENABLE);

 

  /*!< Configure PC.08, PC.09, PC.10, PC.11, PC.12 pin: D0, D1, D2, D3, CLK pin */

  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8 | GPIO_Pin_9 | GPIO_Pin_10 | GPIO_Pin_11 | GPIO_Pin_12;

  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;

  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;

  GPIO_Init(GPIOC, &GPIO_InitStructure);

 

  /*!< Configure PD.02 CMD line */

  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;

  GPIO_Init(GPIOD, &GPIO_InitStructure);

  

  /*!< Enable the SDIO AHB Clock */

  RCC_AHBPeriphClockCmd(RCC_AHBPeriph_SDIO, ENABLE);

 

  /*!< Enable the DMA2 Clock */

  RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA2, ENABLE);

}

 

/**

  * @brief  Configures the DMA2 Channel4 for SDIO Tx request.

  * @param  BufferSRC: pointer to the source buffer

  * @param  BufferSize: buffer size

  * @retval None

  */

void SD_LowLevel_DMA_TxConfig(uint32_t *BufferSRC, uint32_t BufferSize)

{

 

  DMA_InitTypeDef DMA_InitStructure;

 

  DMA_ClearFlag(DMA2_FLAG_TC4 | DMA2_FLAG_TE4 | DMA2_FLAG_HT4 | DMA2_FLAG_GL4);

 

  /*!< DMA2 Channel4 disable */

  DMA_Cmd(DMA2_Channel4, DISABLE);

 

  /*!< DMA2 Channel4 Config */

  DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)SDIO_FIFO_ADDRESS;

  DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)BufferSRC;

  DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralDST;

  DMA_InitStructure.DMA_BufferSize = BufferSize / 4;

  DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;

  DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;

  DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Word;

  DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_Word;

  DMA_InitStructure.DMA_Mode = DMA_Mode_Normal;

  DMA_InitStructure.DMA_Priority = DMA_Priority_High;

  DMA_InitStructure.DMA_M2M = DMA_M2M_Disable;

  DMA_Init(DMA2_Channel4, &DMA_InitStructure);

 

  /*!< DMA2 Channel4 enable */

  DMA_Cmd(DMA2_Channel4, ENABLE);  

}

 

/**

  * @brief  Configures the DMA2 Channel4 for SDIO Rx request.

  * @param  BufferDST: pointer to the destination buffer

  * @param  BufferSize: buffer size

  * @retval None

  */

void SD_LowLevel_DMA_RxConfig(uint32_t *BufferDST, uint32_t BufferSize)

{

  DMA_InitTypeDef DMA_InitStructure;

 

  DMA_ClearFlag(DMA2_FLAG_TC4 | DMA2_FLAG_TE4 | DMA2_FLAG_HT4 | DMA2_FLAG_GL4);

 

  /*!< DMA2 Channel4 disable */

  DMA_Cmd(DMA2_Channel4, DISABLE);

 

  /*!< DMA2 Channel4 Config */

  DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)SDIO_FIFO_ADDRESS;

  DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)BufferDST;

  DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralSRC;

  DMA_InitStructure.DMA_BufferSize = BufferSize / 4;

  DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;

  DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;

  DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Word;

  DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_Word;

  DMA_InitStructure.DMA_Mode = DMA_Mode_Normal;

  DMA_InitStructure.DMA_Priority = DMA_Priority_High;

  DMA_InitStructure.DMA_M2M = DMA_M2M_Disable;

  DMA_Init(DMA2_Channel4, &DMA_InitStructure);

 

  /*!< DMA2 Channel4 enable */

  DMA_Cmd(DMA2_Channel4, ENABLE); 

}

 

/**

  * @brief  Returns the DMA End Of Transfer Status.

  * @param  None

  * @retval DMA SDIO Channel Status.

  */

uint32_t SD_DMAEndOfTransferStatus(void)

{

  return (uint32_t)DMA_GetFlagStatus(DMA2_FLAG_TC4);

}

 

/**

  * @brief  DeInitializes the SDIO interface.

  * @param  None

  * @retval None

  */

void SD_DeInit(void)

  SD_LowLevel_DeInit();

}

 

/**

  * @brief  Initializes the SD Card and put it into StandBy State (Ready for data 

  *         transfer).

  * @param  None

  * @retval SD_Error: SD Card Error code.

  */

SD_Error SD_Init(void)

{

  SD_Error errorstatus = SD_OK;

  

NVIC_Configuration();


  /* SDIO Peripheral Low Level Init */

  SD_LowLevel_Init();

 

  SDIO_DeInit();

 

  errorstatus = SD_PowerON();

 

  if (errorstatus != SD_OK)

  {

    /*!< CMD Response TimeOut (wait for CMDSENT flag) */

    return(errorstatus);

  }

 

  errorstatus = SD_InitializeCards();

 

  if (errorstatus != SD_OK)

  {

    /*!< CMD Response TimeOut (wait for CMDSENT flag) */

    return(errorstatus);

  }

 

  /*!< Configure the SDIO peripheral */

  /*!< SDIOCLK = HCLK, SDIO_CK = HCLK/(2 + SDIO_TRANSFER_CLK_DIV) */

  /*!< on STM32F2xx devices, SDIOCLK is fixed to 48MHz */  

  SDIO_InitStructure.SDIO_ClockDiv = SDIO_TRANSFER_CLK_DIV; 

  SDIO_InitStructure.SDIO_ClockEdge = SDIO_ClockEdge_Rising;

  SDIO_InitStructure.SDIO_ClockBypass = SDIO_ClockBypass_Disable;

  SDIO_InitStructure.SDIO_ClockPowerSave = SDIO_ClockPowerSave_Disable;

  SDIO_InitStructure.SDIO_BusWide = SDIO_BusWide_1b;

  SDIO_InitStructure.SDIO_HardwareFlowControl = SDIO_HardwareFlowControl_Disable;

  SDIO_Init(&SDIO_InitStructure);

  

  if (errorstatus == SD_OK)

  {

    /*----------------- Read CSD/CID MSD registers ------------------*/

    errorstatus = SD_GetCardInfo(&SDCardInfo);

  }

 

  if (errorstatus == SD_OK)

  {

    /*----------------- Select Card --------------------------------*/

    errorstatus = SD_SelectDeselect((uint32_t) (SDCardInfo.RCA << 16));

  }

 

  if (errorstatus == SD_OK)

  {

    errorstatus = SD_EnableWideBusOperation(SDIO_BusWide_4b);

  }  

 

  return(errorstatus);

}

 

/**

  * @brief  Gets the cuurent sd card data transfer status.

  * @param  None

  * @retval SDTransferState: Data Transfer state.

  *   This value can be: 

  *        - SD_TRANSFER_OK: No data transfer is acting

  *        - SD_TRANSFER_BUSY: Data transfer is acting

  */

SDTransferState SD_GetStatus(void)

{

  SDCardState cardstate =  SD_CARD_TRANSFER;

 

  cardstate = SD_GetState();

  

  if (cardstate == SD_CARD_TRANSFER)

  {

    return(SD_TRANSFER_OK);

  }

  else if(cardstate == SD_CARD_ERROR)

  {

    return (SD_TRANSFER_ERROR);

  }

  else

  {

    return(SD_TRANSFER_BUSY);

  }

}

 

/**

  * @brief  Returns the current card's state.

  * @param  None

  * @retval SDCardState: SD Card Error or SD Card Current State.

  */

SDCardState SD_GetState(void)

{

  uint32_t resp1 = 0;

  

if (SD_SendStatus(&resp1) != SD_OK)

{

return SD_CARD_ERROR;

}

else

{

return (SDCardState)((resp1 >> 9) & 0x0F);

}

}

 

/**

  * @brief  Enquires cards about their operating voltage and configures 

  *   clock controls.

  * @param  None

  * @retval SD_Error: SD Card Error code.

  */

SD_Error SD_PowerON(void)

{

  SD_Error errorstatus = SD_OK;

  uint32_t response = 0, count = 0, validvoltage = 0;

  uint32_t SDType = SD_STD_CAPACITY;

 

  /*!< Power ON Sequence -----------------------------------------------------*/

  /*!< Configure the SDIO peripheral */

  /*!< SDIOCLK = HCLK, SDIO_CK = HCLK/(2 + SDIO_INIT_CLK_DIV) */

  /*!< on STM32F2xx devices, SDIOCLK is fixed to 48MHz */

  /*!< SDIO_CK for initialization should not exceed 400 KHz */  

  SDIO_InitStructure.SDIO_ClockDiv = SDIO_INIT_CLK_DIV;

  SDIO_InitStructure.SDIO_ClockEdge = SDIO_ClockEdge_Rising;

  SDIO_InitStructure.SDIO_ClockBypass = SDIO_ClockBypass_Disable;

  SDIO_InitStructure.SDIO_ClockPowerSave = SDIO_ClockPowerSave_Disable;

  SDIO_InitStructure.SDIO_BusWide = SDIO_BusWide_1b;

  SDIO_InitStructure.SDIO_HardwareFlowControl = SDIO_HardwareFlowControl_Disable;

  SDIO_Init(&SDIO_InitStructure);

 

  /*!< Set Power State to ON */

  SDIO_SetPowerState(SDIO_PowerState_ON);

 

  /*!< Enable SDIO Clock */

  SDIO_ClockCmd(ENABLE);

 

  /*!< CMD0: GO_IDLE_STATE ---------------------------------------------------*/

  /*!< No CMD response required */

  SDIO_CmdInitStructure.SDIO_Argument = 0x0;

  SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_GO_IDLE_STATE;

  SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_No;

  SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;

  SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;

  SDIO_SendCommand(&SDIO_CmdInitStructure);

 

  errorstatus = CmdError();

 

  if (errorstatus != SD_OK)

  {

    /*!< CMD Response TimeOut (wait for CMDSENT flag) */

    return(errorstatus);

  }

 

  /*!< CMD8: SEND_IF_COND ----------------------------------------------------*/

  /*!< Send CMD8 to verify SD card interface operating condition */

  /*!< Argument: - [31:12]: Reserved (shall be set to '0')

               - [11:8]: Supply Voltage (VHS) 0x1 (Range: 2.7-3.6 V)

               - [7:0]: Check Pattern (recommended 0xAA) */

  /*!< CMD Response: R7 */

  SDIO_CmdInitStructure.SDIO_Argument = SD_CHECK_PATTERN;

  SDIO_CmdInitStructure.SDIO_CmdIndex = SDIO_SEND_IF_COND;

  SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Short;

  SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;

  SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;

  SDIO_SendCommand(&SDIO_CmdInitStructure);

 

  errorstatus = CmdResp7Error();

 

  if (errorstatus == SD_OK)

  {

    CardType = SDIO_STD_CAPACITY_SD_CARD_V2_0; /*!< SD Card 2.0 */

    SDType = SD_HIGH_CAPACITY;

  }

  else

  {

    /*!< CMD55 */

    SDIO_CmdInitStructure.SDIO_Argument = 0x00;

    SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_APP_CMD;

    SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Short;

    SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;

    SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;

    SDIO_SendCommand(&SDIO_CmdInitStructure);

    errorstatus = CmdResp1Error(SD_CMD_APP_CMD);

  }

  /*!< CMD55 */

  SDIO_CmdInitStructure.SDIO_Argument = 0x00;

  SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_APP_CMD;

  SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Short;

  SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;

  SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;

  SDIO_SendCommand(&SDIO_CmdInitStructure);

  errorstatus = CmdResp1Error(SD_CMD_APP_CMD);

 

  /*!< If errorstatus is Command TimeOut, it is a MMC card */

  /*!< If errorstatus is SD_OK it is a SD card: SD card 2.0 (voltage range mismatch)

     or SD card 1.x */

  if (errorstatus == SD_OK)

  {

    /*!< SD CARD */

    /*!< Send ACMD41 SD_APP_OP_COND with Argument 0x80100000 */

    while ((!validvoltage) && (count < SD_MAX_VOLT_TRIAL))

    {

 

      /*!< SEND CMD55 APP_CMD with RCA as 0 */

      SDIO_CmdInitStructure.SDIO_Argument = 0x00;

      SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_APP_CMD;

      SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Short;

      SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;

      SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;

      SDIO_SendCommand(&SDIO_CmdInitStructure);

 

      errorstatus = CmdResp1Error(SD_CMD_APP_CMD);

 

      if (errorstatus != SD_OK)

      {

        return(errorstatus);

      }

      SDIO_CmdInitStructure.SDIO_Argument = SD_VOLTAGE_WINDOW_SD | SDType;

      SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_SD_APP_OP_COND;

      SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Short;

      SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;

      SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;

      SDIO_SendCommand(&SDIO_CmdInitStructure);

 

      errorstatus = CmdResp3Error();

      if (errorstatus != SD_OK)

      {

        return(errorstatus);

      }

 

      response = SDIO_GetResponse(SDIO_RESP1);

      validvoltage = (((response >> 31) == 1) ? 1 : 0);

      count++;

    }

    if (count >= SD_MAX_VOLT_TRIAL)

    {

      errorstatus = SD_INVALID_VOLTRANGE;

      return(errorstatus);

    }

 

    if (response &= SD_HIGH_CAPACITY)

    {

      CardType = SDIO_HIGH_CAPACITY_SD_CARD;

    }

 

  }/*!< else MMC Card */

 

  return(errorstatus);

}

 

/**

  * @brief  Turns the SDIO output signals off.

  * @param  None

  * @retval SD_Error: SD Card Error code.

  */

SD_Error SD_PowerOFF(void)

{

  SD_Error errorstatus = SD_OK;

 

  /*!< Set Power State to OFF */

  SDIO_SetPowerState(SDIO_PowerState_OFF);

 

  return(errorstatus);

}

 

/**

  * @brief  Intialises all cards or single card as the case may be Card(s) come 

  *         into standby state.

  * @param  None

  * @retval SD_Error: SD Card Error code.

  */

SD_Error SD_InitializeCards(void)

{

  SD_Error errorstatus = SD_OK;

  uint16_t rca = 0x01;

 

  if (SDIO_GetPowerState() == SDIO_PowerState_OFF)

  {

    errorstatus = SD_REQUEST_NOT_APPLICABLE;

    return(errorstatus);

  }

 

  if (SDIO_SECURE_DIGITAL_IO_CARD != CardType)

  {

    /*!< Send CMD2 ALL_SEND_CID */

    SDIO_CmdInitStructure.SDIO_Argument = 0x0;

    SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_ALL_SEND_CID;

    SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Long;

    SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;

    SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;

    SDIO_SendCommand(&SDIO_CmdInitStructure);

 

    errorstatus = CmdResp2Error();

 

    if (SD_OK != errorstatus)

    {

      return(errorstatus);

    }

 

    CID_Tab[0] = SDIO_GetResponse(SDIO_RESP1);

    CID_Tab[1] = SDIO_GetResponse(SDIO_RESP2);

    CID_Tab[2] = SDIO_GetResponse(SDIO_RESP3);

    CID_Tab[3] = SDIO_GetResponse(SDIO_RESP4);

  }

  if ((SDIO_STD_CAPACITY_SD_CARD_V1_1 == CardType) ||  (SDIO_STD_CAPACITY_SD_CARD_V2_0 == CardType) ||  (SDIO_SECURE_DIGITAL_IO_COMBO_CARD == CardType)

      ||  (SDIO_HIGH_CAPACITY_SD_CARD == CardType))

  {

    /*!< Send CMD3 SET_REL_ADDR with argument 0 */

    /*!< SD Card publishes its RCA. */

    SDIO_CmdInitStructure.SDIO_Argument = 0x00;

    SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_SET_REL_ADDR;

    SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Short;

    SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;

    SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;

    SDIO_SendCommand(&SDIO_CmdInitStructure);

 

    errorstatus = CmdResp6Error(SD_CMD_SET_REL_ADDR, &rca);

 

    if (SD_OK != errorstatus)

    {

      return(errorstatus);

    }

  }

 

  if (SDIO_SECURE_DIGITAL_IO_CARD != CardType)

  {

    RCA = rca;

 

    /*!< Send CMD9 SEND_CSD with argument as card's RCA */

    SDIO_CmdInitStructure.SDIO_Argument = (uint32_t)(rca << 16);

    SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_SEND_CSD;

    SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Long;

    SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;

    SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;

    SDIO_SendCommand(&SDIO_CmdInitStructure);

 

    errorstatus = CmdResp2Error();

 

    if (SD_OK != errorstatus)

    {

      return(errorstatus);

    }

 

    CSD_Tab[0] = SDIO_GetResponse(SDIO_RESP1);

    CSD_Tab[1] = SDIO_GetResponse(SDIO_RESP2);

    CSD_Tab[2] = SDIO_GetResponse(SDIO_RESP3);

    CSD_Tab[3] = SDIO_GetResponse(SDIO_RESP4);

  }

 

  errorstatus = SD_OK; /*!< All cards get intialized */

 

  return(errorstatus);

}

 

/**

  * @brief  Returns i

『本文转载自网络,版权归原作者所有,如有侵权请联系删除』

热门文章 更多
8051单片机的函数发生器的设计