STM32标准外设库SPI读写SD卡 SPL篇20

Posted:   2020-09-12

Status:   Completed

Tags :   STM32 SPL

Categories :   STM32 SPL

Previous:   STM32标准外设库FatFs SPL篇19

Next:   STM32标准外设库FatFs SD卡 SPL篇21


参考文档

SD卡读写测试

  • 把SPI-FLASH工程复制一份
  • 新建my_SD.c,my_SD.h

编写SD卡读写程序

  • 参照SPL库Utilities\STM32_EVAL\Common文件夹内stm32_eval_spi_sd.cstm32_eval_spi_sd.c文件修改
  • my.sd.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
#ifndef __MY_SD_H
#define __MY_SD_H
#include "stm32f10x.h"
#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             GPIOA
#define SD_SPI_SCK_GPIO_CLK              RCC_APB2Periph_GPIOA

#define SD_SPI_MISO_PIN                  GPIO_Pin_6
#define SD_SPI_MISO_GPIO_PORT            GPIOA
#define SD_SPI_MISO_GPIO_CLK             RCC_APB2Periph_GPIOA

#define SD_SPI_MOSI_PIN                  GPIO_Pin_7
#define SD_SPI_MOSI_GPIO_PORT            GPIOA
#define SD_SPI_MOSI_GPIO_CLK             RCC_APB2Periph_GPIOA

#define SD_CS_PIN                        GPIO_Pin_8
#define SD_CS_GPIO_PORT                  GPIOA
#define SD_CS_GPIO_CLK                   RCC_APB2Periph_GPIOA

#define SD_CS_LOW()     GPIO_ResetBits(SD_CS_GPIO_PORT, SD_CS_PIN)

#define SD_CS_HIGH()    GPIO_SetBits(SD_CS_GPIO_PORT, SD_CS_PIN)
/**
  * @brief  Commands: CMDxx = CMD-number | 0x40
  */
#define SD_CMD_GO_IDLE_STATE          0   /*!< CMD0 = 0x40 *///复位所有的卡到idle 状态
#define SD_CMD_SEND_OP_COND           1   /*!< CMD1 = 0x41 *///发送主机支持的电压操作范围
#define SD_CMD_SEND_IF_COND						8		/*!< CMD8 = 0x48 *///发送SD 卡接口条件,包含主机支持的电压信息,并询问卡是否支持
#define SD_CMD_SEND_CSD               9   /*!< CMD9 = 0x49 *///要求卡发送其CSD 寄存器内容
#define SD_CMD_SEND_CID               10  /*!< CMD10 = 0x4A *///要求卡发送其CID 寄存器内容
#define SD_CMD_STOP_TRANSMISSION      12  /*!< CMD12 = 0x4C *///强制卡停止传输,可用于多块读写时表示结束
#define SD_CMD_SEND_STATUS            13  /*!< CMD13 = 0x4D *///要求它发送它的状态寄存器内容
#define SD_CMD_SET_BLOCKLEN           16  /*!< CMD16 = 0x50 *///对于标准SD 卡,设置块命令的长度,对于SDHC 卡块命令长度固定为512 字节
#define SD_CMD_READ_SINGLE_BLOCK      17  /*!< CMD17 = 0x51 *///对于标准卡,读取SEL_BLOCK_LEN长度字节的块;对于SDHC 卡,读取512 字节的块
#define SD_CMD_READ_MULT_BLOCK        18  /*!< CMD18 = 0x52 *///连续从SD 卡读取数据块,直到被CMD12 中断,块长度同CMD17
#define SD_CMD_SET_BLOCK_COUNT        23  /*!< CMD23 = 0x57 */
#define SD_CMD_WRITE_SINGLE_BLOCK     24  /*!< CMD24 = 0x58 *///对于标准卡,写入SEL_BLOCK_LEN长度字节的块;对于SDHC 卡,写入512字节的块
#define SD_CMD_WRITE_MULT_BLOCK       25  /*!< CMD25 = 0x59 *///连续向SD 卡写入数据块,直到被CMD12 中断。每块长度同CMD17
#define SD_CMD_PROG_CSD               27  /*!< CMD27 = 0x5B *///对CSD 的可编程位进行编程
#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_OCR								58 /*!< CMD58 *///要求SD 卡返回其 OCR 寄存器的值
#define SD_CMD_APP_CMD								55 /*!< CMD55 返回0x01*/
#define SD_ACMD_SD_SEND_OP_COND			  41 /*!< ACMD41 返回0x00*///与CMD1类似发送主机支持的电压操作范围(ACMD41 命令是特殊应用命令,其命令号为41,但发送命令号41前,需要先发送CMD55命令,以表示其为A开头的ACMD 命令)

//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

#define SD_START_DATA_SINGLE_BLOCK_READ    0xFE  /*!<单块读起始Token */
#define SD_START_DATA_MULTIPLE_BLOCK_READ  0xFE  /*!<多块读起始Token */
#define SD_START_DATA_SINGLE_BLOCK_WRITE   0xFE  /*!<单块写起始Token */
#define SD_START_DATA_MULTIPLE_BLOCK_WRITE 0xFD  /*!<多块写起始Token */
#define SD_STOP_DATA_MULTIPLE_BLOCK_WRITE  0xFD  /*!<多块写停止Token */

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;

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;

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;

typedef struct
{
  SD_CSD SD_csd;//卡的操作条件信息
  SD_CID SD_cid;//卡识别号
  uint64_t CardCapacity;  /*!< Card Capacity */
  uint32_t CardBlockSize; /*!< Card Block Size */
} SD_CardInfo;

#define SD_DUMMY_BYTE   0xFF

extern SD_CardInfo SDCardInfo;	//用于存储卡的信息

SD_Error SD_Init(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);
#endif

  • my_SD.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
#include "my_SD.h"
//记录卡的类型
uint8_t  SD_Type = SD_TYPE_NOT_SD;	//存储卡的类型
SD_CardInfo SDCardInfo;	//用于存储卡的信息
/**
  * @brief  SD卡GPIO配置
  * @param  None
  * @retval None
  */
static void GPIO_Configuration(void)
{
    GPIO_InitTypeDef  GPIO_InitStructure;
    SPI_InitTypeDef   SPI_InitStructure;

    RCC_APB2PeriphClockCmd(SD_CS_GPIO_CLK | SD_SPI_MOSI_GPIO_CLK | SD_SPI_MISO_GPIO_CLK |
                           SD_SPI_SCK_GPIO_CLK, ENABLE);
    SD_SPI_APBxClock_FUN(SD_SPI_CLK, ENABLE);

    /*!< Configure SD_SPI pins: SCK */
    GPIO_InitStructure.GPIO_Pin = SD_SPI_SCK_PIN;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    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_SPI Config */
    SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex;
    SPI_InitStructure.SPI_Mode = SPI_Mode_Master;
    SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b;
    SPI_InitStructure.SPI_CPOL = SPI_CPOL_High;
    SPI_InitStructure.SPI_CPHA = SPI_CPHA_2Edge;
    SPI_InitStructure.SPI_NSS = SPI_NSS_Soft;
    SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_2;
    SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;
    SPI_InitStructure.SPI_CRCPolynomial = 7;
    SPI_Init(SD_SPI, &SPI_InitStructure);

    SPI_Cmd(SD_SPI, ENABLE); /*!< SD_SPI enable */
}
/**
  * @brief  向SD 卡发送一个字节
  * @param  Data: 要发送的数据
  * @retval 接收到的数据
  */
uint8_t SD_WriteByte(uint8_t Data)
{
    /*!<等待至发送缓冲区为空 */
    while(SPI_I2S_GetFlagStatus(SD_SPI, SPI_I2S_FLAG_TXE) == RESET)
    {
    }

    /*!< 发送一个字节 */
    SPI_I2S_SendData(SD_SPI, Data);

    /*!< 等待接收完成*/
    while(SPI_I2S_GetFlagStatus(SD_SPI, SPI_I2S_FLAG_RXNE) == RESET)
    {
    }

    /*!< 返回接收到的数据 */
    return SPI_I2S_ReceiveData(SD_SPI);
}
/**
  * @brief  读取SD 卡一个字节
  * @param  None
  * @retval 接收到的数据
  */
uint8_t SD_ReadByte(void)
{
    uint8_t Data = 0;

    /*!< Wait until the transmit buffer is empty */
    while (SPI_I2S_GetFlagStatus(SD_SPI, SPI_I2S_FLAG_TXE) == RESET)
    {
    }
    /*!< Send the byte */
    SPI_I2S_SendData(SD_SPI, SD_DUMMY_BYTE);

    /*!< Wait until a data is received */
    while (SPI_I2S_GetFlagStatus(SD_SPI, SPI_I2S_FLAG_RXNE) == RESET)
    {
    }
    /*!< Get the received data */
    Data = SPI_I2S_ReceiveData(SD_SPI);

    /*!< Return the shifted data */
    return Data;
}
/**
  * @brief  发送SD 命令
  * @param  Cmd: 要发送的命令
  * @param  Arg: 命令参数
  * @param  Crc: 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); /*!< Construct byte 1 */

    Frame[1] = (uint8_t)(Arg >> 24); /*!< Construct byte 2 */

    Frame[2] = (uint8_t)(Arg >> 16); /*!< Construct byte 3 */

    Frame[3] = (uint8_t)(Arg >> 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  获取SD 卡的的响应
  * @param  要检查的响应类型
  * @retval SD 响应:
  *         - SD_RESPONSE_FAILURE: 失败
  *         - SD_RESPONSE_NO_ERROR: 成功
  */
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  获取SD 卡的数据响应
  * @param  None
  * @retval 返回响应状态 status: 读取到的数据响应 xxx0<status>1
  *         - status 010: 接受数据
  *         - status 101: CRC 校验错误,拒绝数据
  *         - status 110: 写入错误,拒绝数据
  *         - status 111: 其它错误,拒绝数据
  */
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  让SD 卡进入空闲模式
  * @param  None
  * @retval SD 响应:
  *         - SD_RESPONSE_FAILURE: 失败
  *         - SD_RESPONSE_NO_ERROR: 成功
  */
SD_Error SD_GoIdleState(void)
{
    /*!< 片选CS 低电平 */
    SD_CS_LOW();

    /*!< 发送 CMD0 (SD_CMD_GO_IDLE_STATE) 让SD 卡切换至SPI 模式 */
    SD_SendCmd(SD_CMD_GO_IDLE_STATE, 0, 0x95);

    /*!< 等待R1 响应返回的状态为SD_IN_IDLE_STATE */
    if (SD_GetResponse(SD_IN_IDLE_STATE))
    {
        /*!< 响应不是空闲状态,失败返回 */
        return SD_RESPONSE_FAILURE;
    }

    SD_CS_HIGH();

    /*!< 发送空字节 0xFF */
    SD_WriteByte(SD_DUMMY_BYTE);


    //正常返回
    return SD_RESPONSE_NO_ERROR ;
}
/**
  * @brief  获取SD卡的版本类型,并区分SDSC和SDHC
  * @param  无
  * @retval SD响应:
  *         - SD_RESPONSE_FAILURE: 失败
  *         - SD_RESPONSE_NO_ERROR: 成功
  */
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();

    /*!< 发送空字节 0xFF */
    SD_WriteByte(SD_DUMMY_BYTE);

    /*!< 片选信号CS 低电平 */
    SD_CS_LOW();


    /*!< 发送 CMD8 命令,带0x1AA 检查参数*/
    SD_SendCmd(SD_CMD_SEND_IF_COND, 0x1AA, 0x87);

    /*!< 等待R1 响应 */
    while (( (R1_Resp = SD_ReadByte()) == 0xFF) && Count)
    {
        Count--;
    }
    if (Count == 0)
    {
        /*!< 等待超时 */
        return SD_RESPONSE_FAILURE;
    }

    //响应 = 0x05   非V2.0的卡
    if(R1_Resp == (SD_IN_IDLE_STATE|SD_ILLEGAL_COMMAND))
    {
        /*----------激活SD 卡-----------*/
        do
        {
            /*!< 片选信号CS 高电平 */
            SD_CS_HIGH();

            /*!< 发送空字节 0xFF */
            SD_WriteByte(SD_DUMMY_BYTE);

            /*!< 片选信号CS 低电平 */
            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();
        }

        /*!< 片选信号CS 高电平 */
        SD_CS_HIGH();

        /*!< 发送空字节 0xFF */
        SD_WriteByte(SD_DUMMY_BYTE);

        /*!< 片选信号CS 低电平 */
        SD_CS_LOW();

        //判断该卡是否支持2.7-3.6V电压
        if(R7R3_Resp[2]==0x01 && R7R3_Resp[3]==0xAA)
        {
            //支持电压范围,可以操作
            Count = 200;
            //发卡初始化指令CMD55+ACMD41
            do
            {
                //CMD55,以强调下面的是ACMD命令
                SD_SendCmd(SD_CMD_APP_CMD, 0, 0xFF);
                if (!SD_GetResponse(SD_RESPONSE_NO_ERROR)) // SD_IN_IDLE_STATE
                    return 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  读取卡的CSD 寄存器
  *
  * @param  SD_csd: 存储CSD 寄存器的SD_CSD 结构体指针
  * @retval SD 响应:
  *         - SD_RESPONSE_FAILURE: 失败
  *         - SD_RESPONSE_NO_ERROR: 成功
  */
SD_Error SD_GetCSDRegister(SD_CSD* SD_csd)
{
    uint32_t i = 0;
    SD_Error rvalue = SD_RESPONSE_FAILURE;
    uint8_t CSD_Tab[16];

    /*!< 片选信号CS 低电平 */
    SD_CS_LOW();
    /*!< 发送 CMD9 (CSD register)  */
    SD_SendCmd(SD_CMD_SEND_CSD, 0, 0xFF);
    /*!< 等待 R1 响应 (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++)
            {
                /*!< 存储 CSD 寄存器的值到 CSD_Tab */
                CSD_Tab[i] = SD_ReadByte();
            }
        }
        /*!< 读取 CRC 校验字节 (此处不校验,但SD 卡有该流程,需要接收) */
        SD_WriteByte(SD_DUMMY_BYTE);
        SD_WriteByte(SD_DUMMY_BYTE);
        /*!< 设置返回值,表示成功接收到寄存器数据 */
        rvalue = SD_RESPONSE_NO_ERROR;
    }
    /*!< 片选信号CS 高电平 */
    SD_CS_HIGH();
    /*!< 发送 dummy 空字节: 8 时钟周期的延时 */
    SD_WriteByte(SD_DUMMY_BYTE);

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

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

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

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

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

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

    /*!< Byte 6 */
    SD_csd->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; /*!< Reserved */

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

    //V1卡与SDSC卡的信息
    if ((SD_Type == SD_TYPE_V1) || (SD_Type == SD_TYPE_V2))
    {
        /*!< Byte 7 */
        SD_csd->DeviceSize |= (CSD_Tab[7]) << 2;

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

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

        /*!< Byte 9 */
        SD_csd->MaxWrCurrentVDDMin = (CSD_Tab[9] & 0xE0) >> 5;
        SD_csd->MaxWrCurrentVDDMax = (CSD_Tab[9] & 0x1C) >> 2;
        SD_csd->DeviceSizeMul = (CSD_Tab[9] & 0x03) << 1;
        /*!< Byte 10 */
        SD_csd->DeviceSizeMul |= (CSD_Tab[10] & 0x80) >> 7;
    }
    //SDHC卡的信息
    else if (SD_Type == SD_TYPE_V2HC)
    {
        SD_csd->DeviceSize = (CSD_Tab[7] & 0x3F) << 16;

        SD_csd->DeviceSize |= (CSD_Tab[8] << 8);

        SD_csd->DeviceSize |= (CSD_Tab[9]);
    }


    SD_csd->EraseGrSize = (CSD_Tab[10] & 0x40) >> 6;
    SD_csd->EraseGrMul = (CSD_Tab[10] & 0x3F) << 1;

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

    /*!< Byte 12 */
    SD_csd->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;

    /*!< Byte 13 */
    SD_csd->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);

    /*!< Byte 14 */
    SD_csd->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);

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

    /*!< 返回接收状态 */
    return rvalue;
}
/**
  * @brief  读取卡的CID 寄存器
  * @param  SD_cid: 存储CSD 寄存器的SD_CSD 结构体指针
  * @retval SD 响应:
  *         - SD_RESPONSE_FAILURE: 失败
  *         - SD_RESPONSE_NO_ERROR: 成功
  */
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);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    /*!< Return the reponse */
    return rvalue;
}
/**
  * @brief  获取SD 卡的信息
  * @param  cardinfo: SD_CardInfo 结构体指针
  * @retval SD 响应:
  *         - SD_RESPONSE_FAILURE: 失败
  *         - SD_RESPONSE_NO_ERROR: 成功
  */
SD_Error SD_GetCardInfo(SD_CardInfo *cardinfo)
{
    SD_Error status = SD_RESPONSE_FAILURE;
    //读取CSD 寄存器
    status = SD_GetCSDRegister(&(cardinfo->SD_csd));
    //读取CID 寄存器
    status = SD_GetCIDRegister(&(cardinfo->SD_cid));

    if ((SD_Type == SD_TYPE_V1) || (SD_Type == SD_TYPE_V2))
    {
        //块数目基数: CSize + 1
        cardinfo->CardCapacity = (cardinfo->SD_csd.DeviceSize + 1) ;
        //块数目 = 块数目基数*块数目乘数。块数目乘数: 2 的 (C_SIZE_MULT + 2)次方
        cardinfo->CardCapacity *= (1 << (cardinfo->SD_csd.DeviceSizeMul + 2));
        // 块大小:2 的READ_BL_LEN 次方
        cardinfo->CardBlockSize = 1 << (cardinfo->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  初始化 SD/SD 卡
  * @param  None
  * @retval SD 响应::
  *         - SD_RESPONSE_FAILURE: 初始化失败
  *         - SD_RESPONSE_NO_ERROR: 初始化成功
  */
SD_Error SD_Init(void)
{
    uint32_t i = 0;

    /*!< 初始化 SD_SPI */
    GPIO_Configuration();

    /*!< CS 高电平 */
    SD_CS_HIGH();

    /*!< CS 高电平期间,发送 空 字节数据 0xFF, 10 次 */
    /*!< Rise CS and MOSI for 80 clocks cycles */
    for (i = 0; i <= 9; i++)
    {
        /*!< 发送 空 字节数据 0xFF */
        SD_WriteByte(SD_DUMMY_BYTE);
    }

    //获取卡的类型,最多尝试10次
    i=0;
    do
    {
        /*------------Put SD in SPI mode--------------*/
        /*!< SD initialized and set to SPI mode properly */
        SD_GoIdleState();
        SD_GetCardType();
    } while(SD_Type == SD_TYPE_NOT_SD || i++ > 10);

    //不支持的卡
    if(SD_Type == SD_TYPE_NOT_SD)
        return SD_RESPONSE_FAILURE;

    return SD_GetCardInfo(&SDCardInfo);
}
/**
  * @brief  从SD 卡读取一个数据块
  * @param  pBuffer: 指针,用于存储读取到的数据
  * @param  ReadAddr: 要读取的SD 卡内部地址
  * @param  BlockSize: 块大小
  * @retval SD 响应::
  *         - SD_RESPONSE_FAILURE: 失败
  *         - SD_RESPONSE_NO_ERROR: 成功
  */
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,且读命令中的地址的单位是sector
    if (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  从SD 卡读取多个数据块
  * @param  pBuffer: 指针,用于存储读取到的数据
  * @param  ReadAddr: 要读取的SD 卡内部地址
  * @param  BlockSize: 块大小
  * @param  NumberOfBlocks: 块数量
  * @retval SD 响应::
  *         - SD_RESPONSE_FAILURE: 失败
  *         - SD_RESPONSE_NO_ERROR: 成功
  */
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,且读命令中的地址的单位是sector
    if (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 += 512;
            /*!< 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;
        }
    }
    /*!< 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  往SD 卡写入一个数据块
  * @param  pBuffer: 指针,指向将要写入的数据
  * @param  WriteAddr: 要写入的SD 卡内部地址
  * @param  BlockSize: 块大小
  * @retval SD 响应::
  *         - SD_RESPONSE_FAILURE: 失败
  *         - SD_RESPONSE_NO_ERROR: 成功
  */
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,且写命令中的地址的单位是sector
    if (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  往SD 卡写入多个数据块
  * @param  pBuffer: 指针,指向将要写入的数据
  * @param  ReadAddr: 要写入的SD 卡内部地址
  * @param  BlockSize: 块大小
  * @param  NumberOfBlocks: 块数量
  * @retval SD 响应::
  *         - SD_RESPONSE_FAILURE: 失败
  *         - SD_RESPONSE_NO_ERROR: 成功
  */
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,且写命令中的地址的单位是sector
    if (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 += 512;
        /*!< 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;
}

SD卡读写测试

  • main.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
#include "my_gpio.h"
#include "my_usart.h"
#include "my_SD.h"
typedef enum {FAILED = 0, PASSED = !FAILED} TestStatus;
#define BLOCK_SIZE            512 /* Block Size in Bytes */
#define NUMBER_OF_BLOCKS      10
#define MULTI_BUFFER_SIZE    (BLOCK_SIZE * NUMBER_OF_BLOCKS)

uint8_t Buffer_Block_Tx[BLOCK_SIZE], Buffer_Block_Rx[BLOCK_SIZE];
uint8_t Buffer_MultiBlock_Tx[MULTI_BUFFER_SIZE], Buffer_MultiBlock_Rx[MULTI_BUFFER_SIZE];
volatile TestStatus EraseStatus = FAILED, TransferStatus1 = FAILED, TransferStatus2 = FAILED;
SD_Error Status = SD_RESPONSE_NO_ERROR;

/**
 * @brief  板级外设初始化,所有板子上的初始化均可放在这个函数里面
 * @param  无
 * @retval 无
 */
static void BSP_Init(void)
{
    NVIC_PriorityGroupConfig( NVIC_PriorityGroup_4 );
    /* LED 初始化 */
    LED_GPIO_Config();
    /* 串口初始化	*/
    USART_Config();
}
static void Fill_Buffer(uint8_t *pBuffer, uint32_t BufferLength, uint32_t Offset)
{
    uint16_t index = 0;

    /* Put in global buffer same values */
    for (index = 0; index < BufferLength; index++)
    {
        pBuffer[index] = index + Offset;
    }
}
static TestStatus Buffercmp(uint8_t* pBuffer1, uint8_t* pBuffer2, uint32_t BufferLength)
{
    while (BufferLength--)
    {
        if (*pBuffer1 != *pBuffer2)
        {
            return FAILED;
        }

        pBuffer1++;
        pBuffer2++;
    }

    return PASSED;
}
static void SD_SingleBlockTest(void)
{
    /*------------------- Block Read/Write --------------------------*/
    /* Fill the buffer to send */
    Fill_Buffer(Buffer_Block_Tx, BLOCK_SIZE, 0x320F);

    if (Status == SD_RESPONSE_NO_ERROR)
    {
        /* Write block of 512 bytes on address 0 */
        Status = SD_WriteBlock(Buffer_Block_Tx, 0x00, BLOCK_SIZE);
        /* Check if the Transfer is finished */
    }

    if (Status == SD_RESPONSE_NO_ERROR)
    {
        /* Read block of 512 bytes from address 0 */
        Status = SD_ReadBlock(Buffer_Block_Rx, 0x00, BLOCK_SIZE);

    }

    /* Check the correctness of written data */
    if (Status == SD_RESPONSE_NO_ERROR)
    {
        TransferStatus1 = Buffercmp(Buffer_Block_Tx, Buffer_Block_Rx, BLOCK_SIZE);
    }

    if(TransferStatus1 == PASSED)
    {
        LED2(ON);
        printf("Single block success!\n");

    }
    else
    {
        LED1(ON);
        printf("Single block fail\n");

    }
}
void SD_MultiBlockTest(void)
{
    /*--------------- Multiple Block Read/Write ---------------------*/
    /* Fill the buffer to send */
    Fill_Buffer(Buffer_MultiBlock_Tx, MULTI_BUFFER_SIZE, 0x0);

    if (Status == SD_RESPONSE_NO_ERROR)
    {
        /* Write multiple block of many bytes on address 0 */
        Status = SD_WriteMultiBlocks(Buffer_MultiBlock_Tx, 0x00, BLOCK_SIZE, NUMBER_OF_BLOCKS);
        /* Check if the Transfer is finished */
    }

    if (Status == SD_RESPONSE_NO_ERROR)
    {
        /* Read block of many bytes from address 0 */
        Status = SD_ReadMultiBlocks(Buffer_MultiBlock_Rx, 0x00, BLOCK_SIZE, NUMBER_OF_BLOCKS);
        /* Check if the Transfer is finished */
    }

    /* Check the correctness of written data */
    if (Status == SD_RESPONSE_NO_ERROR)
    {
        TransferStatus2 = Buffercmp(Buffer_MultiBlock_Tx, Buffer_MultiBlock_Rx, MULTI_BUFFER_SIZE);
    }

    if(TransferStatus2 == PASSED)
    {
        LED2(ON);
        printf("Multi block success!\n");

    }
    else
    {
        LED1(ON);
        printf("Multi block fail\n");
    }
}

int main(void)
{
    BSP_Init();
    printf("***********SD TEST*********\n");
    if((Status = SD_Init()) != SD_RESPONSE_NO_ERROR)
    {
        LED1(ON);
        printf("SD init fail\n");
    }
    else
    {
        printf("SD init success!\n");
    }

    if(Status == SD_RESPONSE_NO_ERROR)
    {

        LED2(OFF);
        /*single block 读写测试*/
        SD_SingleBlockTest();

        LED2(OFF);
        /*muti block 读写测试*/
        SD_MultiBlockTest();
    }
    while(1);
}

调试

  • 编译之后下载到开发板
  • 串口调试助手可看到SD 测试的调试信息