找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
查看: 7674|回复: 0
打印 上一主题 下一主题
收起左侧

移植SD卡驱动(最大支持32GB)

[复制链接]
跳转到指定楼层
楼主
ID:75926 发表于 2015-4-10 17:14 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
移植之前只需要实现
void SD_LowLevel_Init(void);//初始化IO
uint8_t SD_WriteByte(uint8_t Data);//使用SPI 方式写8位数据
uint8_t SD_ReadByte(void)//使用SPI方式读取8位数据
#define SD_CS_LOW()     //拉高CS
#define SD_CS_HIGH()    //拉低CS
这三个函数和2个宏的具体实现就可以在不同的平台上使用SD卡
  1. SD_Error SD_Init(void)
  2. {
  3.   uint32_t i = 0;

  4.   /*!< Initialize SD_SPI */
  5.   SD_LowLevel_Init();

  6.   /*!< SD chip select high */
  7.   SD_CS_HIGH();

  8.   /*!< Send dummy byte 0xFF, 10 times with CS high */
  9.   /*!< Rise CS and MOSI for 80 clocks cycles */
  10.   for (i = 0; i <= 9; i++)
  11.   {
  12.     /*!< Send dummy byte 0xFF */
  13.     SD_WriteByte(SD_DUMMY_BYTE);
  14.   }
  15.   /*------------Put SD in SPI mode--------------*/
  16.   /*!< SD initialized and set to SPI mode properly */
  17.   return (SD_GoIdleState());
  18. }

  19. /**
  20.   * @brief  Returns information about specific card.
  21.   * @param  cardinfo: pointer to a SD_CardInfo structure that contains all SD
  22.   *         card information.
  23.   * @retval The SD Response:
  24.   *         - SD_RESPONSE_FAILURE: Sequence failed
  25.   *         - SD_RESPONSE_NO_ERROR: Sequence succeed
  26.   */
  27. SD_Error SD_GetCardInfo(SD_CardInfo *cardinfo)
  28. {
  29.   SD_Error status = SD_RESPONSE_FAILURE;

  30.   status = SD_GetCSDRegister(&(cardinfo->SD_csd));
  31.   status = SD_GetCIDRegister(&(cardinfo->SD_cid));
  32.   cardinfo->CardCapacity = (cardinfo->SD_csd.DeviceSize + 1) ;
  33.   cardinfo->CardCapacity *= (1 << (cardinfo->SD_csd.DeviceSizeMul + 2));
  34.   cardinfo->CardBlockSize = 1 << (cardinfo->SD_csd.RdBlockLen);
  35.   cardinfo->CardCapacity *= cardinfo->CardBlockSize;

  36.   /*!< Returns the reponse */
  37.   return status;
  38. }

  39. /**
  40.   * @brief  Reads a block of data from the SD.
  41.   * @param  pBuffer: pointer to the buffer that receives the data read from the
  42.   *                  SD.
  43.   * @param  ReadAddr: SD's internal address to read from.
  44.   * @param  BlockSize: the SD card Data block size.
  45.   * @retval The SD Response:
  46.   *         - SD_RESPONSE_FAILURE: Sequence failed
  47.   *         - SD_RESPONSE_NO_ERROR: Sequence succeed
  48.   */
  49. SD_Error SD_ReadBlock(uint8_t* pBuffer, uint32_t ReadAddr, uint16_t BlockSize)
  50. {
  51.   uint32_t i = 0;
  52.   SD_Error rvalue = SD_RESPONSE_FAILURE;

  53.   /*!< SD chip select low */
  54.   SD_CS_LOW();
  55.   
  56.   /*!< Send CMD17 (SD_CMD_READ_SINGLE_BLOCK) to read one block */
  57.   SD_SendCmd(SD_CMD_READ_SINGLE_BLOCK, ReadAddr, 0xFF);
  58.   
  59.   /*!< Check if the SD acknowledged the read block command: R1 response (0x00: no errors) */
  60.   if (!SD_GetResponse(SD_RESPONSE_NO_ERROR))
  61.   {
  62.     /*!< Now look for the data token to signify the start of the data */
  63.     if (!SD_GetResponse(SD_START_DATA_SINGLE_BLOCK_READ))
  64.     {
  65.       /*!< Read the SD block data : read NumByteToRead data */
  66.       for (i = 0; i < BlockSize; i++)
  67.       {
  68.         /*!< Save the received data */
  69.         *pBuffer = SD_ReadByte();
  70.       
  71.         /*!< Point to the next location where the byte read will be saved */
  72.         pBuffer++;
  73.       }
  74.       /*!< Get CRC bytes (not really needed by us, but required by SD) */
  75.       SD_ReadByte();
  76.       SD_ReadByte();
  77.       /*!< Set response value to success */
  78.       rvalue = SD_RESPONSE_NO_ERROR;
  79.     }
  80.   }
  81.   /*!< SD chip select high */
  82.   SD_CS_HIGH();
  83.   
  84.   /*!< Send dummy byte: 8 Clock pulses of delay */
  85.   SD_WriteByte(SD_DUMMY_BYTE);
  86.   
  87.   /*!< Returns the reponse */
  88.   return rvalue;
  89. }

  90. /**
  91.   * @brief  Reads multiple block of data from the SD.
  92.   * @param  pBuffer: pointer to the buffer that receives the data read from the
  93.   *                  SD.
  94.   * @param  ReadAddr: SD's internal address to read from.
  95.   * @param  BlockSize: the SD card Data block size.
  96.   * @param  NumberOfBlocks: number of blocks to be read.
  97.   * @retval The SD Response:
  98.   *         - SD_RESPONSE_FAILURE: Sequence failed
  99.   *         - SD_RESPONSE_NO_ERROR: Sequence succeed
  100.   */
  101. SD_Error SD_ReadMultiBlocks(uint8_t* pBuffer, uint32_t ReadAddr, uint16_t BlockSize, uint32_t NumberOfBlocks)
  102. {
  103.   uint32_t i = 0, Offset = 0;
  104.   SD_Error rvalue = SD_RESPONSE_FAILURE;
  105.   
  106.   /*!< SD chip select low */
  107.   SD_CS_LOW();
  108.   /*!< Data transfer */
  109.   while (NumberOfBlocks--)
  110.   {
  111.     /*!< Send CMD17 (SD_CMD_READ_SINGLE_BLOCK) to read one block */
  112.     SD_SendCmd (SD_CMD_READ_SINGLE_BLOCK, ReadAddr + Offset, 0xFF);
  113.     /*!< Check if the SD acknowledged the read block command: R1 response (0x00: no errors) */
  114.     if (SD_GetResponse(SD_RESPONSE_NO_ERROR))
  115.     {
  116.       return  SD_RESPONSE_FAILURE;
  117.     }
  118.     /*!< Now look for the data token to signify the start of the data */
  119.     if (!SD_GetResponse(SD_START_DATA_SINGLE_BLOCK_READ))
  120.     {
  121.       /*!< Read the SD block data : read NumByteToRead data */
  122.       for (i = 0; i < BlockSize; i++)
  123.       {
  124.         /*!< Read the pointed data */
  125.         *pBuffer = SD_ReadByte();
  126.         /*!< Point to the next location where the byte read will be saved */
  127.         pBuffer++;
  128.       }
  129.       /*!< Set next read address*/
  130.       Offset += 512;
  131.       /*!< get CRC bytes (not really needed by us, but required by SD) */
  132.       SD_ReadByte();
  133.       SD_ReadByte();
  134.       /*!< Set response value to success */
  135.       rvalue = SD_RESPONSE_NO_ERROR;
  136.     }
  137.     else
  138.     {
  139.       /*!< Set response value to failure */
  140.       rvalue = SD_RESPONSE_FAILURE;
  141.     }
  142.   }
  143.   /*!< SD chip select high */
  144.   SD_CS_HIGH();
  145.   /*!< Send dummy byte: 8 Clock pulses of delay */
  146.   SD_WriteByte(SD_DUMMY_BYTE);
  147.   /*!< Returns the reponse */
  148.   return rvalue;
  149. }

  150. /**
  151.   * @brief  Writes a block on the SD
  152.   * @param  pBuffer: pointer to the buffer containing the data to be written on
  153.   *                  the SD.
  154.   * @param  WriteAddr: address to write on.
  155.   * @param  BlockSize: the SD card Data block size.
  156.   * @retval The SD Response:
  157.   *         - SD_RESPONSE_FAILURE: Sequence failed
  158.   *         - SD_RESPONSE_NO_ERROR: Sequence succeed
  159.   */
  160. SD_Error SD_WriteBlock(uint8_t* pBuffer, uint32_t WriteAddr, uint16_t BlockSize)
  161. {
  162.   uint32_t i = 0;
  163.   SD_Error rvalue = SD_RESPONSE_FAILURE;

  164.   /*!< SD chip select low */
  165.   SD_CS_LOW();

  166.   /*!< Send CMD24 (SD_CMD_WRITE_SINGLE_BLOCK) to write multiple block */
  167.   SD_SendCmd(SD_CMD_WRITE_SINGLE_BLOCK, WriteAddr, 0xFF);
  168.   
  169.   /*!< Check if the SD acknowledged the write block command: R1 response (0x00: no errors) */
  170.   if (!SD_GetResponse(SD_RESPONSE_NO_ERROR))
  171.   {
  172.     /*!< Send a dummy byte */
  173.     SD_WriteByte(SD_DUMMY_BYTE);

  174.     /*!< Send the data token to signify the start of the data */
  175.     SD_WriteByte(0xFE);

  176.     /*!< Write the block data to SD : write count data by block */
  177.     for (i = 0; i < BlockSize; i++)
  178.     {
  179.       /*!< Send the pointed byte */
  180.       SD_WriteByte(*pBuffer);
  181.       /*!< Point to the next location where the byte read will be saved */
  182.       pBuffer++;
  183.     }
  184.     /*!< Put CRC bytes (not really needed by us, but required by SD) */
  185.     SD_ReadByte();
  186.     SD_ReadByte();

  187.     /*!< Read data response */
  188.     if (SD_GetDataResponse() == SD_DATA_OK)
  189.     {
  190.       rvalue = SD_RESPONSE_NO_ERROR;
  191.     }
  192.   }
  193.   /*!< SD chip select high */
  194.   SD_CS_HIGH();
  195.   /*!< Send dummy byte: 8 Clock pulses of delay */
  196.   SD_WriteByte(SD_DUMMY_BYTE);

  197.   /*!< Returns the reponse */
  198.   return rvalue;
  199. }

  200. /**
  201.   * @brief  Writes many blocks on the SD
  202.   * @param  pBuffer: pointer to the buffer containing the data to be written on
  203.   *                  the SD.
  204.   * @param  WriteAddr: address to write on.
  205.   * @param  BlockSize: the SD card Data block size.
  206.   * @param  NumberOfBlocks: number of blocks to be written.
  207.   * @retval The SD Response:
  208.   *         - SD_RESPONSE_FAILURE: Sequence failed
  209.   *         - SD_RESPONSE_NO_ERROR: Sequence succeed
  210.   */
  211. SD_Error SD_WriteMultiBlocks(uint8_t* pBuffer, uint32_t WriteAddr, uint16_t BlockSize, uint32_t NumberOfBlocks)
  212. {
  213.   uint32_t i = 0, Offset = 0;
  214.   SD_Error rvalue = SD_RESPONSE_FAILURE;

  215.   /*!< SD chip select low */
  216.   SD_CS_LOW();
  217.   /*!< Data transfer */
  218.   while (NumberOfBlocks--)
  219.   {
  220.     /*!< Send CMD24 (SD_CMD_WRITE_SINGLE_BLOCK) to write blocks */
  221.     SD_SendCmd(SD_CMD_WRITE_SINGLE_BLOCK, WriteAddr + Offset, 0xFF);
  222.     /*!< Check if the SD acknowledged the write block command: R1 response (0x00: no errors) */
  223.     if (SD_GetResponse(SD_RESPONSE_NO_ERROR))
  224.     {
  225.       return SD_RESPONSE_FAILURE;
  226.     }
  227.     /*!< Send dummy byte */
  228.     SD_WriteByte(SD_DUMMY_BYTE);
  229.     /*!< Send the data token to signify the start of the data */
  230.     SD_WriteByte(SD_START_DATA_SINGLE_BLOCK_WRITE);
  231.     /*!< Write the block data to SD : write count data by block */
  232.     for (i = 0; i < BlockSize; i++)
  233.     {
  234.       /*!< Send the pointed byte */
  235.       SD_WriteByte(*pBuffer);
  236.       /*!< Point to the next location where the byte read will be saved */
  237.       pBuffer++;
  238.     }
  239.     /*!< Set next write address */
  240.     Offset += 512;
  241.     /*!< Put CRC bytes (not really needed by us, but required by SD) */
  242.     SD_ReadByte();
  243.     SD_ReadByte();
  244.     /*!< Read data response */
  245.     if (SD_GetDataResponse() == SD_DATA_OK)
  246.     {
  247.       /*!< Set response value to success */
  248.       rvalue = SD_RESPONSE_NO_ERROR;
  249.     }
  250.     else
  251.     {
  252.       /*!< Set response value to failure */
  253.       rvalue = SD_RESPONSE_FAILURE;
  254.     }
  255.   }
  256.   /*!< SD chip select high */
  257.   SD_CS_HIGH();
  258.   /*!< Send dummy byte: 8 Clock pulses of delay */
  259.   SD_WriteByte(SD_DUMMY_BYTE);
  260.   /*!< Returns the reponse */
  261.   return rvalue;
  262. }

  263. /**
  264.   * @brief  Read the CSD card register.
  265.   *         Reading the contents of the CSD register in SPI mode is a simple
  266.   *         read-block transaction.
  267.   * @param  SD_csd: pointer on an SCD register structure
  268.   * @retval The SD Response:
  269.   *         - SD_RESPONSE_FAILURE: Sequence failed
  270.   *         - SD_RESPONSE_NO_ERROR: Sequence succeed
  271.   */
  272. SD_Error SD_GetCSDRegister(SD_CSD* SD_csd)
  273. {
  274.   uint32_t i = 0;
  275.   SD_Error rvalue = SD_RESPONSE_FAILURE;
  276.   uint8_t CSD_Tab[16];

  277.   /*!< SD chip select low */
  278.   SD_CS_LOW();
  279.   /*!< Send CMD9 (CSD register) or CMD10(CSD register) */
  280.   SD_SendCmd(SD_CMD_SEND_CSD, 0, 0xFF);
  281.   /*!< Wait for response in the R1 format (0x00 is no errors) */
  282.   if (!SD_GetResponse(SD_RESPONSE_NO_ERROR))
  283.   {
  284.     if (!SD_GetResponse(SD_START_DATA_SINGLE_BLOCK_READ))
  285.     {
  286.       for (i = 0; i < 16; i++)
  287.       {
  288.         /*!< Store CSD register value on CSD_Tab */
  289.         CSD_Tab[i] = SD_ReadByte();
  290.       }
  291.     }
  292.     /*!< Get CRC bytes (not really needed by us, but required by SD) */
  293.     SD_WriteByte(SD_DUMMY_BYTE);
  294.     SD_WriteByte(SD_DUMMY_BYTE);
  295.     /*!< Set response value to success */
  296.     rvalue = SD_RESPONSE_NO_ERROR;
  297.   }
  298.   /*!< SD chip select high */
  299.   SD_CS_HIGH();
  300.   /*!< Send dummy byte: 8 Clock pulses of delay */
  301.   SD_WriteByte(SD_DUMMY_BYTE);

  302.   /*!< Byte 0 */
  303.   SD_csd->CSDStruct = (CSD_Tab[0] & 0xC0) >> 6;
  304.   SD_csd->SysSpecVersion = (CSD_Tab[0] & 0x3C) >> 2;
  305.   SD_csd->Reserved1 = CSD_Tab[0] & 0x03;

  306.   /*!< Byte 1 */
  307.   SD_csd->TAAC = CSD_Tab[1];

  308.   /*!< Byte 2 */
  309.   SD_csd->NSAC = CSD_Tab[2];

  310.   /*!< Byte 3 */
  311.   SD_csd->MaxBusClkFrec = CSD_Tab[3];

  312.   /*!< Byte 4 */
  313.   SD_csd->CardComdClasses = CSD_Tab[4] << 4;

  314.   /*!< Byte 5 */
  315.   SD_csd->CardComdClasses |= (CSD_Tab[5] & 0xF0) >> 4;
  316.   SD_csd->RdBlockLen = CSD_Tab[5] & 0x0F;

  317.   /*!< Byte 6 */
  318.   SD_csd->PartBlockRead = (CSD_Tab[6] & 0x80) >> 7;
  319.   SD_csd->WrBlockMisalign = (CSD_Tab[6] & 0x40) >> 6;
  320.   SD_csd->RdBlockMisalign = (CSD_Tab[6] & 0x20) >> 5;
  321.   SD_csd->DSRImpl = (CSD_Tab[6] & 0x10) >> 4;
  322.   SD_csd->Reserved2 = 0; /*!< Reserved */

  323.   SD_csd->DeviceSize = (CSD_Tab[6] & 0x03) << 10;

  324.   /*!< Byte 7 */
  325.   SD_csd->DeviceSize |= (CSD_Tab[7]) << 2;

  326.   /*!< Byte 8 */
  327.   SD_csd->DeviceSize |= (CSD_Tab[8] & 0xC0) >> 6;

  328.   SD_csd->MaxRdCurrentVDDMin = (CSD_Tab[8] & 0x38) >> 3;
  329.   SD_csd->MaxRdCurrentVDDMax = (CSD_Tab[8] & 0x07);

  330.   /*!< Byte 9 */
  331.   SD_csd->MaxWrCurrentVDDMin = (CSD_Tab[9] & 0xE0) >> 5;
  332.   SD_csd->MaxWrCurrentVDDMax = (CSD_Tab[9] & 0x1C) >> 2;
  333.   SD_csd->DeviceSizeMul = (CSD_Tab[9] & 0x03) << 1;
  334.   /*!< Byte 10 */
  335.   SD_csd->DeviceSizeMul |= (CSD_Tab[10] & 0x80) >> 7;
  336.    
  337.   SD_csd->EraseGrSize = (CSD_Tab[10] & 0x40) >> 6;
  338.   SD_csd->EraseGrMul = (CSD_Tab[10] & 0x3F) << 1;

  339.   /*!< Byte 11 */
  340.   SD_csd->EraseGrMul |= (CSD_Tab[11] & 0x80) >> 7;
  341.   SD_csd->WrProtectGrSize = (CSD_Tab[11] & 0x7F);

  342.   /*!< Byte 12 */
  343.   SD_csd->WrProtectGrEnable = (CSD_Tab[12] & 0x80) >> 7;
  344.   SD_csd->ManDeflECC = (CSD_Tab[12] & 0x60) >> 5;
  345.   SD_csd->WrSpeedFact = (CSD_Tab[12] & 0x1C) >> 2;
  346.   SD_csd->MaxWrBlockLen = (CSD_Tab[12] & 0x03) << 2;

  347.   /*!< Byte 13 */
  348.   SD_csd->MaxWrBlockLen |= (CSD_Tab[13] & 0xC0) >> 6;
  349.   SD_csd->WriteBlockPaPartial = (CSD_Tab[13] & 0x20) >> 5;
  350.   SD_csd->Reserved3 = 0;
  351.   SD_csd->ContentProtectAppli = (CSD_Tab[13] & 0x01);

  352.   /*!< Byte 14 */
  353.   SD_csd->FileFormatGrouop = (CSD_Tab[14] & 0x80) >> 7;
  354.   SD_csd->CopyFlag = (CSD_Tab[14] & 0x40) >> 6;
  355.   SD_csd->PermWrProtect = (CSD_Tab[14] & 0x20) >> 5;
  356.   SD_csd->TempWrProtect = (CSD_Tab[14] & 0x10) >> 4;
  357.   SD_csd->FileFormat = (CSD_Tab[14] & 0x0C) >> 2;
  358.   SD_csd->ECC = (CSD_Tab[14] & 0x03);

  359.   /*!< Byte 15 */
  360.   SD_csd->CSD_CRC = (CSD_Tab[15] & 0xFE) >> 1;
  361.   SD_csd->Reserved4 = 1;

  362.   /*!< Return the reponse */
  363.   return rvalue;
  364. }

  365. /**
  366.   * @brief  Read the CID card register.
  367.   *         Reading the contents of the CID register in SPI mode is a simple
  368.   *         read-block transaction.
  369.   * @param  SD_cid: pointer on an CID register structure
  370.   * @retval The SD Response:
  371.   *         - SD_RESPONSE_FAILURE: Sequence failed
  372.   *         - SD_RESPONSE_NO_ERROR: Sequence succeed
  373.   */
  374. SD_Error SD_GetCIDRegister(SD_CID* SD_cid)
  375. {
  376.   uint32_t i = 0;
  377.   SD_Error rvalue = SD_RESPONSE_FAILURE;
  378.   uint8_t CID_Tab[16];
  379.   
  380.   /*!< SD chip select low */
  381.   SD_CS_LOW();
  382.   
  383.   /*!< Send CMD10 (CID register) */
  384.   SD_SendCmd(SD_CMD_SEND_CID, 0, 0xFF);
  385.   
  386.   /*!< Wait for response in the R1 format (0x00 is no errors) */
  387.   if (!SD_GetResponse(SD_RESPONSE_NO_ERROR))
  388.   {
  389.     if (!SD_GetResponse(SD_START_DATA_SINGLE_BLOCK_READ))
  390.     {
  391.       /*!< Store CID register value on CID_Tab */
  392.       for (i = 0; i < 16; i++)
  393.       {
  394.         CID_Tab[i] = SD_ReadByte();
  395.       }
  396.     }
  397.     /*!< Get CRC bytes (not really needed by us, but required by SD) */
  398.     SD_WriteByte(SD_DUMMY_BYTE);
  399.     SD_WriteByte(SD_DUMMY_BYTE);
  400.     /*!< Set response value to success */
  401.     rvalue = SD_RESPONSE_NO_ERROR;
  402.   }
  403.   /*!< SD chip select high */
  404.   SD_CS_HIGH();
  405.   /*!< Send dummy byte: 8 Clock pulses of delay */
  406.   SD_WriteByte(SD_DUMMY_BYTE);

  407.   /*!< Byte 0 */
  408.   SD_cid->ManufacturerID = CID_Tab[0];

  409.   /*!< Byte 1 */
  410.   SD_cid->OEM_AppliID = CID_Tab[1] << 8;

  411.   /*!< Byte 2 */
  412.   SD_cid->OEM_AppliID |= CID_Tab[2];

  413.   /*!< Byte 3 */
  414.   SD_cid->ProdName1 = CID_Tab[3] << 24;

  415.   /*!< Byte 4 */
  416.   SD_cid->ProdName1 |= CID_Tab[4] << 16;

  417.   /*!< Byte 5 */
  418.   SD_cid->ProdName1 |= CID_Tab[5] << 8;

  419.   /*!< Byte 6 */
  420.   SD_cid->ProdName1 |= CID_Tab[6];

  421.   /*!< Byte 7 */
  422.   SD_cid->ProdName2 = CID_Tab[7];

  423.   /*!< Byte 8 */
  424.   SD_cid->ProdRev = CID_Tab[8];

  425.   /*!< Byte 9 */
  426.   SD_cid->ProdSN = CID_Tab[9] << 24;

  427.   /*!< Byte 10 */
  428.   SD_cid->ProdSN |= CID_Tab[10] << 16;

  429.   /*!< Byte 11 */
  430.   SD_cid->ProdSN |= CID_Tab[11] << 8;

  431.   /*!< Byte 12 */
  432.   SD_cid->ProdSN |= CID_Tab[12];

  433.   /*!< Byte 13 */
  434.   SD_cid->Reserved1 |= (CID_Tab[13] & 0xF0) >> 4;
  435.   SD_cid->ManufactDate = (CID_Tab[13] & 0x0F) << 8;

  436.   /*!< Byte 14 */
  437.   SD_cid->ManufactDate |= CID_Tab[14];

  438.   /*!< Byte 15 */
  439.   SD_cid->CID_CRC = (CID_Tab[15] & 0xFE) >> 1;
  440.   SD_cid->Reserved2 = 1;

  441.   /*!< Return the reponse */
  442.   return rvalue;
  443. }

  444. /**
  445.   * @brief  Send 5 bytes command to the SD card.
  446.   * @param  Cmd: The user expected command to send to SD card.
  447.   * @param  Arg: The command argument.
  448.   * @param  Crc: The CRC.
  449.   * @retval None
  450.   */
  451. void SD_SendCmd(uint8_t Cmd, uint32_t Arg, uint8_t Crc)
  452. {
  453.   uint32_t i = 0x00;
  454.   
  455.   uint8_t Frame[6];
  456.   
  457.   Frame[0] = (Cmd | 0x40); /*!< Construct byte 1 */
  458.   
  459.   Frame[1] = (uint8_t)(Arg >> 24); /*!< Construct byte 2 */
  460.   
  461.   Frame[2] = (uint8_t)(Arg >> 16); /*!< Construct byte 3 */
  462.   
  463.   Frame[3] = (uint8_t)(Arg >> 8); /*!< Construct byte 4 */
  464.   
  465.   Frame[4] = (uint8_t)(Arg); /*!< Construct byte 5 */
  466.   
  467.   Frame[5] = (Crc); /*!< Construct CRC: byte 6 */
  468.   
  469.   for (i = 0; i < 6; i++)
  470.   {
  471.     SD_WriteByte(Frame[i]); /*!< Send the Cmd bytes */
  472.   }
  473. }

  474. /**
  475.   * @brief  Get SD card data response.
  476.   * @param  None
  477.   * @retval The SD status: Read data response xxx0<status>1
  478.   *         - status 010: Data accecpted
  479.   *         - status 101: Data rejected due to a crc error
  480.   *         - status 110: Data rejected due to a Write error.
  481.   *         - status 111: Data rejected due to other error.
  482.   */
  483. uint8_t SD_GetDataResponse(void)
  484. {
  485.   uint32_t i = 0;
  486.   uint8_t response, rvalue;

  487.   while (i <= 64)
  488.   {
  489.     /*!< Read resonse */
  490.     response = SD_ReadByte();
  491.     /*!< Mask unused bits */
  492.     response &= 0x1F;
  493.     switch (response)
  494.     {
  495.       case SD_DATA_OK:
  496.       {
  497.         rvalue = SD_DATA_OK;
  498.         break;
  499.       }
  500.       case SD_DATA_CRC_ERROR:
  501.         return SD_DATA_CRC_ERROR;
  502.       case SD_DATA_WRITE_ERROR:
  503.         return SD_DATA_WRITE_ERROR;
  504.       default:
  505.       {
  506.         rvalue = SD_DATA_OTHER_ERROR;
  507.         break;
  508.       }
  509.     }
  510.     /*!< Exit loop in case of data ok */
  511.     if (rvalue == SD_DATA_OK)
  512.       break;
  513.     /*!< Increment loop counter */
  514.     i++;
  515.   }

  516.   /*!< Wait null data */
  517.   while (SD_ReadByte() == 0);

  518.   /*!< Return response */
  519.   return response;
  520. }

  521. /**
  522.   * @brief  Returns the SD response.
  523.   * @param  None
  524.   * @retval The SD Response:
  525.   *         - SD_RESPONSE_FAILURE: Sequence failed
  526.   *         - SD_RESPONSE_NO_ERROR: Sequence succeed
  527.   */
  528. SD_Error SD_GetResponse(uint8_t Response)
  529. {
  530.   uint32_t Count = 0xFFF;

  531.   /*!< Check if response is got or a timeout is happen */
  532.   while ((SD_ReadByte() != Response) && Count)
  533.   {
  534.     Count--;
  535.   }
  536.   if (Count == 0)
  537.   {
  538.     /*!< After time out */
  539.     return SD_RESPONSE_FAILURE;
  540.   }
  541.   else
  542.   {
  543.     /*!< Right response got */
  544.     return SD_RESPONSE_NO_ERROR;
  545.   }
  546. }

  547. /**
  548.   * @brief  Returns the SD status.
  549.   * @param  None
  550.   * @retval The SD status.
  551.   */
  552. uint16_t SD_GetStatus(void)
  553. {
  554.   uint16_t Status = 0;

  555.   /*!< SD chip select low */
  556.   SD_CS_LOW();

  557.   /*!< Send CMD13 (SD_SEND_STATUS) to get SD status */
  558.   SD_SendCmd(SD_CMD_SEND_STATUS, 0, 0xFF);

  559.   Status = SD_ReadByte();
  560.   Status |= (uint16_t)(SD_ReadByte() << 8);

  561.   /*!< SD chip select high */
  562.   SD_CS_HIGH();

  563.   /*!< Send dummy byte 0xFF */
  564.   SD_WriteByte(SD_DUMMY_BYTE);

  565.   return Status;
  566. }

  567. /**
  568.   * @brief  Put SD in Idle state.
  569.   * @param  None
  570.   * @retval The SD Response:
  571.   *         - SD_RESPONSE_FAILURE: Sequence failed
  572.   *         - SD_RESPONSE_NO_ERROR: Sequence succeed
  573.   */
  574. SD_Error SD_GoIdleState(void)
  575. {
  576.   /*!< SD chip select low */
  577.   SD_CS_LOW();
  578.   
  579.   /*!< Send CMD0 (SD_CMD_GO_IDLE_STATE) to put SD in SPI mode */
  580.   SD_SendCmd(SD_CMD_GO_IDLE_STATE, 0, 0x95);
  581.   
  582.   /*!< Wait for In Idle State Response (R1 Format) equal to 0x01 */
  583.   if (SD_GetResponse(SD_IN_IDLE_STATE))
  584.   {
  585.     /*!< No Idle State Response: return response failue */
  586.     return SD_RESPONSE_FAILURE;
  587.   }
  588.   /*----------Activates the card initialization process-----------*/
  589.   do
  590.   {
  591.     /*!< SD chip select high */
  592.     SD_CS_HIGH();
  593.    
  594.     /*!< Send Dummy byte 0xFF */
  595.     SD_WriteByte(SD_DUMMY_BYTE);
  596.    
  597.     /*!< SD chip select low */
  598.     SD_CS_LOW();
  599.    
  600.     /*!< Send CMD1 (Activates the card process) until response equal to 0x0 */
  601.     SD_SendCmd(SD_CMD_SEND_OP_COND, 0, 0xFF);
  602.     /*!< Wait for no error Response (R1 Format) equal to 0x00 */
  603.   }
  604.   while (SD_GetResponse(SD_RESPONSE_NO_ERROR));
  605.   
  606.   /*!< SD chip select high */
  607.   SD_CS_HIGH();
  608.   
  609.   /*!< Send dummy byte 0xFF */
  610.   SD_WriteByte(SD_DUMMY_BYTE);
  611.   
  612.   return SD_RESPONSE_NO_ERROR;
  613. }




  614. /*******************************************************END**************************************/

  615. typedef enum
  616. {
  617. /**
  618.   * @brief  SD reponses and error flags
  619.   */
  620.   SD_RESPONSE_NO_ERROR      = (0x00),
  621.   SD_IN_IDLE_STATE          = (0x01),
  622.   SD_ERASE_RESET            = (0x02),
  623.   SD_ILLEGAL_COMMAND        = (0x04),
  624.   SD_COM_CRC_ERROR          = (0x08),
  625.   SD_ERASE_SEQUENCE_ERROR   = (0x10),
  626.   SD_ADDRESS_ERROR          = (0x20),
  627.   SD_PARAMETER_ERROR        = (0x40),
  628.   SD_RESPONSE_FAILURE       = (0xFF),

  629. /**
  630.   * @brief  Data response error
  631.   */
  632.   SD_DATA_OK                = (0x05),
  633.   SD_DATA_CRC_ERROR         = (0x0B),
  634.   SD_DATA_WRITE_ERROR       = (0x0D),
  635.   SD_DATA_OTHER_ERROR       = (0xFF)
  636. } SD_Error;

  637. /**
  638.   * @brief  Card Specific Data: CSD Register   
  639.   */
  640. typedef struct
  641. {
  642.   __IO uint8_t  CSDStruct;            /*!< CSD structure */
  643.   __IO uint8_t  SysSpecVersion;       /*!< System specification version */
  644.   __IO uint8_t  Reserved1;            /*!< Reserved */
  645.   __IO uint8_t  TAAC;                 /*!< Data read access-time 1 */
  646.   __IO uint8_t  NSAC;                 /*!< Data read access-time 2 in CLK cycles */
  647.   __IO uint8_t  MaxBusClkFrec;        /*!< Max. bus clock frequency */
  648.   __IO uint16_t CardComdClasses;      /*!< Card command classes */
  649.   __IO uint8_t  RdBlockLen;           /*!< Max. read data block length */
  650.   __IO uint8_t  PartBlockRead;        /*!< Partial blocks for read allowed */
  651.   __IO uint8_t  WrBlockMisalign;      /*!< Write block misalignment */
  652.   __IO uint8_t  RdBlockMisalign;      /*!< Read block misalignment */
  653.   __IO uint8_t  DSRImpl;              /*!< DSR implemented */
  654.   __IO uint8_t  Reserved2;            /*!< Reserved */
  655.   __IO uint32_t DeviceSize;           /*!< Device Size */
  656.   __IO uint8_t  MaxRdCurrentVDDMin;   /*!< Max. read current @ VDD min */
  657.   __IO uint8_t  MaxRdCurrentVDDMax;   /*!< Max. read current @ VDD max */
  658.   __IO uint8_t  MaxWrCurrentVDDMin;   /*!< Max. write current @ VDD min */
  659.   __IO uint8_t  MaxWrCurrentVDDMax;   /*!< Max. write current @ VDD max */
  660.   __IO uint8_t  DeviceSizeMul;        /*!< Device size multiplier */
  661.   __IO uint8_t  EraseGrSize;          /*!< Erase group size */
  662.   __IO uint8_t  EraseGrMul;           /*!< Erase group size multiplier */
  663.   __IO uint8_t  WrProtectGrSize;      /*!< Write protect group size */
  664.   __IO uint8_t  WrProtectGrEnable;    /*!< Write protect group enable */
  665.   __IO uint8_t  ManDeflECC;           /*!< Manufacturer default ECC */
  666.   __IO uint8_t  WrSpeedFact;          /*!< Write speed factor */
  667.   __IO uint8_t  MaxWrBlockLen;        /*!< Max. write data block length */
  668.   __IO uint8_t  WriteBlockPaPartial;  /*!< Partial blocks for write allowed */
  669.   __IO uint8_t  Reserved3;            /*!< Reserded */
  670.   __IO uint8_t  ContentProtectAppli;  /*!< Content protection application */
  671.   __IO uint8_t  FileFormatGrouop;     /*!< File format group */
  672.   __IO uint8_t  CopyFlag;             /*!< Copy flag (OTP) */
  673.   __IO uint8_t  PermWrProtect;        /*!< Permanent write protection */
  674.   __IO uint8_t  TempWrProtect;        /*!< Temporary write protection */
  675.   __IO uint8_t  FileFormat;           /*!< File Format */
  676.   __IO uint8_t  ECC;                  /*!< ECC code */
  677.   __IO uint8_t  CSD_CRC;              /*!< CSD CRC */
  678.   __IO uint8_t  Reserved4;            /*!< always 1*/
  679. } SD_CSD;

  680. /**
  681.   * @brief  Card Identification Data: CID Register   
  682.   */
  683. typedef struct
  684. {
  685.   __IO uint8_t  ManufacturerID;       /*!< ManufacturerID */
  686.   __IO uint16_t OEM_AppliID;          /*!< OEM/Application ID */
  687.   __IO uint32_t ProdName1;            /*!< Product Name part1 */
  688.   __IO uint8_t  ProdName2;            /*!< Product Name part2*/
  689.   __IO uint8_t  ProdRev;              /*!< Product Revision */
  690.   __IO uint32_t ProdSN;               /*!< Product Serial Number */
  691.   __IO uint8_t  Reserved1;            /*!< Reserved1 */
  692.   __IO uint16_t ManufactDate;         /*!< Manufacturing Date */
  693.   __IO uint8_t  CID_CRC;              /*!< CID CRC */
  694.   __IO uint8_t  Reserved2;            /*!< always 1 */
  695. } SD_CID;

  696. /**
  697.   * @brief SD Card information
  698.   */
  699. typedef struct
  700. {
  701.   SD_CSD SD_csd;
  702.   SD_CID SD_cid;
  703.   uint32_t CardCapacity;  /*!< Card Capacity */
  704.   uint32_t CardBlockSize; /*!< Card Block Size */
  705. } SD_CardInfo;


  706. #define SD_BLOCK_SIZE    0x200


  707. #define SD_DUMMY_BYTE   0xFF


  708. #define SD_START_DATA_SINGLE_BLOCK_READ    0xFE  /*!< Data token start byte, Start Single Block Read */
  709. #define SD_START_DATA_MULTIPLE_BLOCK_READ  0xFE  /*!< Data token start byte, Start Multiple Block Read */
  710. #define SD_START_DATA_SINGLE_BLOCK_WRITE   0xFE  /*!< Data token start byte, Start Single Block Write */
  711. #define SD_START_DATA_MULTIPLE_BLOCK_WRITE 0xFD  /*!< Data token start byte, Start Multiple Block Write */
  712. #define SD_STOP_DATA_MULTIPLE_BLOCK_WRITE  0xFD  /*!< Data toke stop byte, Stop Multiple Block Write */


  713. #define SD_PRESENT        ((uint8_t)0x01)
  714. #define SD_NOT_PRESENT    ((uint8_t)0x00)


  715. #define SD_CMD_GO_IDLE_STATE          0   /*!< CMD0 = 0x40 */
  716. #define SD_CMD_SEND_OP_COND           1   /*!< CMD1 = 0x41 */
  717. #define SD_CMD_SEND_CSD               9   /*!< CMD9 = 0x49 */
  718. #define SD_CMD_SEND_CID               10  /*!< CMD10 = 0x4A */
  719. #define SD_CMD_STOP_TRANSMISSION      12  /*!< CMD12 = 0x4C */
  720. #define SD_CMD_SEND_STATUS            13  /*!< CMD13 = 0x4D */
  721. #define SD_CMD_SET_BLOCKLEN           16  /*!< CMD16 = 0x50 */
  722. #define SD_CMD_READ_SINGLE_BLOCK      17  /*!< CMD17 = 0x51 */
  723. #define SD_CMD_READ_MULT_BLOCK        18  /*!< CMD18 = 0x52 */
  724. #define SD_CMD_SET_BLOCK_COUNT        23  /*!< CMD23 = 0x57 */
  725. #define SD_CMD_WRITE_SINGLE_BLOCK     24  /*!< CMD24 = 0x58 */
  726. #define SD_CMD_WRITE_MULT_BLOCK       25  /*!< CMD25 = 0x59 */
  727. #define SD_CMD_PROG_CSD               27  /*!< CMD27 = 0x5B */
  728. #define SD_CMD_SET_WRITE_PROT         28  /*!< CMD28 = 0x5C */
  729. #define SD_CMD_CLR_WRITE_PROT         29  /*!< CMD29 = 0x5D */
  730. #define SD_CMD_SEND_WRITE_PROT        30  /*!< CMD30 = 0x5E */
  731. #define SD_CMD_SD_ERASE_GRP_START     32  /*!< CMD32 = 0x60 */
  732. #define SD_CMD_SD_ERASE_GRP_END       33  /*!< CMD33 = 0x61 */
  733. #define SD_CMD_UNTAG_SECTOR           34  /*!< CMD34 = 0x62 */
  734. #define SD_CMD_ERASE_GRP_START        35  /*!< CMD35 = 0x63 */
  735. #define SD_CMD_ERASE_GRP_END          36  /*!< CMD36 = 0x64 */
  736. #define SD_CMD_UNTAG_ERASE_GROUP      37  /*!< CMD37 = 0x65 */
  737. #define SD_CMD_ERASE                  38  /*!< CMD38 = 0x66 */





  738. SD_Error SD_Init(void);
  739. uint8_t SD_Detect(void);
  740. SD_Error SD_GetCardInfo(SD_CardInfo *cardinfo);
  741. SD_Error SD_ReadBlock(uint8_t* pBuffer, uint32_t ReadAddr, uint16_t BlockSize);
  742. SD_Error SD_ReadMultiBlocks(uint8_t* pBuffer, uint32_t ReadAddr, uint16_t BlockSize, uint32_t NumberOfBlocks);
  743. SD_Error SD_WriteBlock(uint8_t* pBuffer, uint32_t WriteAddr, uint16_t BlockSize);
  744. SD_Error SD_WriteMultiBlocks(uint8_t* pBuffer, uint32_t WriteAddr, uint16_t BlockSize, uint32_t NumberOfBlocks);
  745. SD_Error SD_GetCSDRegister(SD_CSD* SD_csd);
  746. SD_Error SD_GetCIDRegister(SD_CID* SD_cid);

  747. void SD_SendCmd(uint8_t Cmd, uint32_t Arg, uint8_t Crc);
  748. SD_Error SD_GetResponse(uint8_t Response);
  749. uint8_t SD_GetDataResponse(void);
  750. SD_Error SD_GoIdleState(void);
  751. uint16_t SD_GetStatus(void);

  752. uint8_t SD_WriteByte(uint8_t byte);
  753. uint8_t SD_ReadByte(void);
复制代码



分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏2 分享淘帖 顶 踩
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

手机版|小黑屋|51黑电子论坛 |51黑电子论坛6群 QQ 管理员QQ:125739409;技术交流QQ群281945664

Powered by 单片机教程网

快速回复 返回顶部 返回列表