2 * This file is part of Cleanflight and Betaflight.
4 * Cleanflight and Betaflight are free software. You can redistribute
5 * this software and/or modify this software under the terms of the
6 * GNU General Public License as published by the Free Software
7 * Foundation, either version 3 of the License, or (at your option)
10 * Cleanflight and Betaflight are distributed in the hope that they
11 * will be useful, but WITHOUT ANY WARRANTY; without even the implied
12 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13 * See the GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this software.
18 * If not, see <http://www.gnu.org/licenses/>.
22 * Original author: Alain (https://github.com/aroyer-qc)
23 * Modified for BF source: Chris Hockuba (https://github.com/conkerkh)
26 /* Include(s) -------------------------------------------------------------------------------------------------------*/
33 #ifdef USE_SDCARD_SDIO
35 #include "sdmmc_sdio.h"
36 #include "stm32f7xx.h"
40 #include "drivers/io.h"
41 #include "drivers/io_impl.h"
42 #include "drivers/nvic.h"
43 #include "drivers/time.h"
44 #include "drivers/rcc.h"
45 #include "drivers/dma.h"
46 #include "drivers/light_led.h"
48 #include "build/debug.h"
50 #define BLOCK_SIZE ((uint32_t)(512))
52 #define IFCR_CLEAR_MASK_STREAM3 (DMA_LIFCR_CTCIF3 | DMA_LIFCR_CHTIF3 | DMA_LIFCR_CTEIF3 | DMA_LIFCR_CDMEIF3 | DMA_LIFCR_CFEIF3)
53 #define IFCR_CLEAR_MASK_STREAM6 (DMA_HIFCR_CTCIF6 | DMA_HIFCR_CHTIF6 | DMA_HIFCR_CTEIF6 | DMA_HIFCR_CDMEIF6 | DMA_HIFCR_CFEIF6)
55 #define SDMMC_ICR_STATIC_FLAGS ((uint32_t)(SDMMC_ICR_CCRCFAILC | SDMMC_ICR_DCRCFAILC | SDMMC_ICR_CTIMEOUTC |\
56 SDMMC_ICR_DTIMEOUTC | SDMMC_ICR_TXUNDERRC | SDMMC_ICR_RXOVERRC |\
57 SDMMC_ICR_CMDRENDC | SDMMC_ICR_CMDSENTC | SDMMC_ICR_DATAENDC |\
60 #define SD_SOFTWARE_COMMAND_TIMEOUT ((uint32_t)0x00020000)
62 #define SD_OCR_ADDR_OUT_OF_RANGE ((uint32_t)0x80000000)
63 #define SD_OCR_ADDR_MISALIGNED ((uint32_t)0x40000000)
64 #define SD_OCR_BLOCK_LEN_ERR ((uint32_t)0x20000000)
65 #define SD_OCR_ERASE_SEQ_ERR ((uint32_t)0x10000000)
66 #define SD_OCR_BAD_ERASE_PARAM ((uint32_t)0x08000000)
67 #define SD_OCR_WRITE_PROT_VIOLATION ((uint32_t)0x04000000)
68 #define SD_OCR_LOCK_UNLOCK_FAILED ((uint32_t)0x01000000)
69 #define SD_OCR_COM_CRC_FAILED ((uint32_t)0x00800000)
70 #define SD_OCR_ILLEGAL_CMD ((uint32_t)0x00400000)
71 #define SD_OCR_CARD_ECC_FAILED ((uint32_t)0x00200000)
72 #define SD_OCR_CC_ERROR ((uint32_t)0x00100000)
73 #define SD_OCR_GENERAL_UNKNOWN_ERROR ((uint32_t)0x00080000)
74 #define SD_OCR_STREAM_READ_UNDERRUN ((uint32_t)0x00040000)
75 #define SD_OCR_STREAM_WRITE_OVERRUN ((uint32_t)0x00020000)
76 #define SD_OCR_CID_CSD_OVERWRITE ((uint32_t)0x00010000)
77 #define SD_OCR_WP_ERASE_SKIP ((uint32_t)0x00008000)
78 #define SD_OCR_CARD_ECC_DISABLED ((uint32_t)0x00004000)
79 #define SD_OCR_ERASE_RESET ((uint32_t)0x00002000)
80 #define SD_OCR_AKE_SEQ_ERROR ((uint32_t)0x00000008)
81 #define SD_OCR_ERRORBITS ((uint32_t)0xFDFFE008)
83 #define SD_R6_GENERAL_UNKNOWN_ERROR ((uint32_t)0x00002000)
84 #define SD_R6_ILLEGAL_CMD ((uint32_t)0x00004000)
85 #define SD_R6_COM_CRC_FAILED ((uint32_t)0x00008000)
87 #define SD_VOLTAGE_WINDOW_SD ((uint32_t)0x80100000)
88 #define SD_RESP_HIGH_CAPACITY ((uint32_t)0x40000000)
89 #define SD_RESP_STD_CAPACITY ((uint32_t)0x00000000)
90 #define SD_CHECK_PATTERN ((uint32_t)0x000001AA)
92 #define SD_MAX_VOLT_TRIAL ((uint32_t)0x0000FFFF)
93 #define SD_ALLZERO ((uint32_t)0x00000000)
95 #define SD_WIDE_BUS_SUPPORT ((uint32_t)0x00040000)
96 #define SD_SINGLE_BUS_SUPPORT ((uint32_t)0x00010000)
97 #define SD_CARD_LOCKED ((uint32_t)0x02000000)
99 #define SD_0TO7BITS ((uint32_t)0x000000FF)
100 #define SD_8TO15BITS ((uint32_t)0x0000FF00)
101 #define SD_16TO23BITS ((uint32_t)0x00FF0000)
102 #define SD_24TO31BITS ((uint32_t)0xFF000000)
103 #define SD_MAX_DATA_LENGTH ((uint32_t)0x01FFFFFF)
105 #define SD_CCCC_ERASE ((uint32_t)0x00000020)
107 #define SD_SDMMC_SEND_IF_COND ((uint32_t)SD_CMD_HS_SEND_EXT_CSD)
111 #define SD_BUS_WIDE_1B ((uint32_t)0x00000000)
112 #define SD_BUS_WIDE_4B SDMMC_CLKCR_WIDBUS_0
113 #define SD_BUS_WIDE_8B SDMMC_CLKCR_WIDBUS_1
115 #define SD_CMD_RESPONSE_SHORT SDMMC_CMD_WAITRESP_0
116 #define SD_CMD_RESPONSE_LONG SDMMC_CMD_WAITRESP
118 #define SD_DATABLOCK_SIZE_8B (SDMMC_DCTRL_DBLOCKSIZE_0|SDMMC_DCTRL_DBLOCKSIZE_1)
119 #define SD_DATABLOCK_SIZE_64B (SDMMC_DCTRL_DBLOCKSIZE_1|SDMMC_DCTRL_DBLOCKSIZE_2)
120 #define SD_DATABLOCK_SIZE_512B (SDMMC_DCTRL_DBLOCKSIZE_0|SDMMC_DCTRL_DBLOCKSIZE_3)
122 #define CLKCR_CLEAR_MASK ((uint32_t)(SDMMC_CLKCR_CLKDIV | SDMMC_CLKCR_PWRSAV |\
123 SDMMC_CLKCR_BYPASS | SDMMC_CLKCR_WIDBUS |\
124 SDMMC_CLKCR_NEGEDGE | SDMMC_CLKCR_HWFC_EN))
126 #define DCTRL_CLEAR_MASK ((uint32_t)(SDMMC_DCTRL_DTEN | SDMMC_DCTRL_DTDIR |\
127 SDMMC_DCTRL_DTMODE | SDMMC_DCTRL_DBLOCKSIZE))
129 #define CMD_CLEAR_MASK ((uint32_t)(SDMMC_CMD_CMDINDEX | SDMMC_CMD_WAITRESP |\
130 SDMMC_CMD_WAITINT | SDMMC_CMD_WAITPEND |\
131 SDMMC_CMD_CPSMEN | SDMMC_CMD_SDMMC1SUSPEND))
133 #define SDMMC_INIT_CLK_DIV ((uint8_t)0x76)
134 #define SDMMC_CLK_DIV ((uint8_t)0x00)
137 #define SD_CMD_GO_IDLE_STATE ((uint8_t)0) // Resets the SD memory card.
138 #define SD_CMD_SEND_OP_COND ((uint8_t)1) // Sends host capacity support information and activates the card's initialization process.
139 #define SD_CMD_ALL_SEND_CID ((uint8_t)2) // Asks any card connected to the host to send the CID numbers on the CMD line.
140 #define SD_CMD_SET_REL_ADDR ((uint8_t)3) // Asks the card to publish a new relative address (RCA).
141 #define SD_CMD_HS_SWITCH ((uint8_t)6) // Checks switchable function (mode 0) and switch card function (mode 1).
142 #define SD_CMD_SEL_DESEL_CARD ((uint8_t)7) // Selects the card by its own relative address and gets deselected by any other address
143 #define SD_CMD_HS_SEND_EXT_CSD ((uint8_t)8) // Sends SD Memory Card interface condition, which includes host supply voltage information
144 // and asks the card whether card supports voltage.
145 #define SD_CMD_SEND_CSD ((uint8_t)9) // Addressed card sends its card specific data (CSD) on the CMD line.
146 #define SD_CMD_SEND_CID ((uint8_t)10) // Addressed card sends its card identification (CID) on the CMD line.
147 #define SD_CMD_STOP_TRANSMISSION ((uint8_t)12) // Forces the card to stop transmission.
148 #define SD_CMD_SEND_STATUS ((uint8_t)13) // Addressed card sends its status register.
149 #define SD_CMD_SET_BLOCKLEN ((uint8_t)16) // Sets the block length (in bytes for SDSC) for all following block commands
150 // (read, write, lock). Default block length is fixed to 512 Bytes. Not effective
151 // for SDHS and SDXC.
152 #define SD_CMD_READ_SINGLE_BLOCK ((uint8_t)17) // Reads single block of size selected by SET_BLOCKLEN in case of SDSC, and a block of
153 // fixed 512 bytes in case of SDHC and SDXC.
154 #define SD_CMD_READ_MULT_BLOCK ((uint8_t)18) // Continuously transfers data blocks from card to host until interrupted by
155 // STOP_TRANSMISSION command.
156 #define SD_CMD_WRITE_SINGLE_BLOCK ((uint8_t)24) // Writes single block of size selected by SET_BLOCKLEN in case of SDSC, and a block of
157 // fixed 512 bytes in case of SDHC and SDXC.
158 #define SD_CMD_WRITE_MULT_BLOCK ((uint8_t)25) // Continuously writes blocks of data until a STOP_TRANSMISSION follows.
159 #define SD_CMD_SD_ERASE_GRP_START ((uint8_t)32) // Sets the address of the first write block to be erased. (For SD card only).
160 #define SD_CMD_SD_ERASE_GRP_END ((uint8_t)33) // Sets the address of the last write block of the continuous range to be erased.
161 // system set by switch function command (CMD6).
162 #define SD_CMD_ERASE ((uint8_t)38) // Reserved for SD security applications.
163 #define SD_CMD_FAST_IO ((uint8_t)39) // SD card doesn't support it (Reserved).
164 #define SD_CMD_APP_CMD ((uint8_t)55) // Indicates to the card that the next command is an application specific command rather
165 // than a standard command.
167 /* Following commands are SD Card Specific commands.
168 SDMMC_APP_CMD should be sent before sending these commands. */
169 #define SD_CMD_APP_SD_SET_BUSWIDTH ((uint8_t)6) // (ACMD6) Defines the data bus width to be used for data transfer. The allowed data bus
170 // widths are given in SCR register.
171 #define SD_CMD_SD_APP_STATUS ((uint8_t)13) // (ACMD13) Sends the SD status.
172 #define SD_CMD_SD_APP_OP_COND ((uint8_t)41) // (ACMD41) Sends host capacity support information (HCS) and asks the accessed card to
173 // send its operating condition register (OCR) content in the response on the CMD line.
174 #define SD_CMD_SD_APP_SEND_SCR ((uint8_t)51) // Reads the SD Configuration Register (SCR).
176 #define SDMMC_DIR_TX 1
177 #define SDMMC_DIR_RX 0
179 #define SDMMC_DMA_ST3 1
182 /* Typedef(s) -------------------------------------------------------------------------------------------------------*/
186 SD_SINGLE_BLOCK
= 0, // Single block operation
187 SD_MULTIPLE_BLOCK
= 1, // Multiple blocks operation
193 uint32_t CSD
[4]; // SD card specific data table
194 uint32_t CID
[4]; // SD card identification number table
195 volatile uint32_t TransferComplete
; // SD transfer complete flag in non blocking mode
196 volatile uint32_t TransferError
; // SD transfer error flag in non blocking mode
197 volatile uint32_t RXCplt
; // SD RX Complete is equal 0 when no transfer
198 volatile uint32_t TXCplt
; // SD TX Complete is equal 0 when no transfer
199 volatile uint32_t Operation
; // SD transfer operation (read/write)
204 SD_CARD_READY
= ((uint32_t)0x00000001), // Card state is ready
205 SD_CARD_IDENTIFICATION
= ((uint32_t)0x00000002), // Card is in identification state
206 SD_CARD_STANDBY
= ((uint32_t)0x00000003), // Card is in standby state
207 SD_CARD_TRANSFER
= ((uint32_t)0x00000004), // Card is in transfer state
208 SD_CARD_SENDING
= ((uint32_t)0x00000005), // Card is sending an operation
209 SD_CARD_RECEIVING
= ((uint32_t)0x00000006), // Card is receiving operation information
210 SD_CARD_PROGRAMMING
= ((uint32_t)0x00000007), // Card is in programming state
211 SD_CARD_DISCONNECTED
= ((uint32_t)0x00000008), // Card is disconnected
212 SD_CARD_ERROR
= ((uint32_t)0x000000FF) // Card is in error state
215 /* Variable(s) ------------------------------------------------------------------------------------------------------*/
217 static SD_Handle_t SD_Handle
;
218 SD_CardInfo_t SD_CardInfo
;
219 static uint32_t SD_Status
;
220 static uint32_t SD_CardRCA
;
221 SD_CardType_t SD_CardType
;
222 static volatile uint32_t TimeOut
;
223 DMA_Stream_TypeDef
*dmaStream
;
226 /* Private function(s) ----------------------------------------------------------------------------------------------*/
228 static void SD_DataTransferInit (uint32_t Size
, uint32_t DataBlockSize
, bool IsItReadFromCard
);
229 static SD_Error_t
SD_TransmitCommand (uint32_t Command
, uint32_t Argument
, int8_t ResponseType
);
230 static SD_Error_t
SD_CmdResponse (uint8_t SD_CMD
, int8_t ResponseType
);
231 static void SD_GetResponse (uint32_t* pResponse
);
232 static SD_Error_t
CheckOCR_Response (uint32_t Response_R1
);
233 static void SD_DMA_Complete (DMA_Stream_TypeDef
* pDMA_Stream
);
234 static SD_Error_t
SD_InitializeCard (void);
236 static SD_Error_t
SD_PowerON (void);
237 static SD_Error_t
SD_WideBusOperationConfig (uint32_t WideMode
);
238 static SD_Error_t
SD_FindSCR (uint32_t *pSCR
);
240 void SDMMC_DMA_ST3_IRQHandler(dmaChannelDescriptor_t
*dma
);
241 void SDMMC_DMA_ST6_IRQHandler(dmaChannelDescriptor_t
*dma
);
243 //static void SD_PowerOFF (void);
245 /** -----------------------------------------------------------------------------------------------------------------*/
248 * @brief Prepare the state machine for transfer
249 * @param SD_TransferType_e TransfertDir
250 * @param SD_CARD_BlockSize_e Size
252 static void SD_DataTransferInit(uint32_t Size
, uint32_t DataBlockSize
, bool IsItReadFromCard
)
256 SDMMC1
->DTIMER
= SD_DATATIMEOUT
; // Set the SDMMC1 Data TimeOut value
257 SDMMC1
->DLEN
= Size
; // Set the SDMMC1 DataLength value
258 Direction
= (IsItReadFromCard
== true) ? SDMMC_DCTRL_DTDIR
: 0;
259 SDMMC1
->DCTRL
|= (uint32_t)(DataBlockSize
| Direction
| SDMMC_DCTRL_DTEN
| 0x01);
264 /** -----------------------------------------------------------------------------------------------------------------*/
265 /** SD_TransmitCommand
267 * @brief Send the commande to SDMMC1
268 * @param uint32_t Command
269 * @param uint32_t Argument Must provide the response size
270 * @param uint8_t ResponseType
271 * @retval SD Card error state
273 static SD_Error_t
SD_TransmitCommand(uint32_t Command
, uint32_t Argument
, int8_t ResponseType
)
275 SD_Error_t ErrorState
;
277 WRITE_REG(SDMMC1
->ICR
, SDMMC_ICR_STATIC_FLAGS
); // Clear the Command Flags
278 WRITE_REG(SDMMC1
->ARG
, (uint32_t)Argument
); // Set the SDMMC1 Argument value
279 WRITE_REG(SDMMC1
->CMD
, (uint32_t)(Command
| SDMMC_CMD_CPSMEN
)); // Set SDMMC1 command parameters
280 if((Argument
== 0) && (ResponseType
== 0)) ResponseType
= -1; // Go idle command
281 ErrorState
= SD_CmdResponse(Command
& SDMMC_CMD_CMDINDEX
, ResponseType
);
282 WRITE_REG(SDMMC1
->ICR
, SDMMC_ICR_STATIC_FLAGS
); // Clear the Command Flags
288 /** -----------------------------------------------------------------------------------------------------------------*/
290 * @brief Checks for error conditions for any response.
291 * - R2 (CID or CSD) response.
292 * - R3 (OCR) response.
294 * @param SD_CMD: The sent command Index
295 * @retval SD Card error state
297 static SD_Error_t
SD_CmdResponse(uint8_t SD_CMD
, int8_t ResponseType
)
299 uint32_t Response_R1
;
303 if(ResponseType
== -1) {
304 Flag
= SDMMC_STA_CMDSENT
;
306 Flag
= SDMMC_STA_CCRCFAIL
| SDMMC_STA_CMDREND
| SDMMC_STA_CTIMEOUT
;
309 TimeOut
= SD_SOFTWARE_COMMAND_TIMEOUT
;
312 SD_Status
= SDMMC1
->STA
;
315 while(((SD_Status
& Flag
) == 0) && (TimeOut
> 0));
317 if(ResponseType
<= 0)
320 return SD_CMD_RSP_TIMEOUT
;
326 if((SDMMC1
->STA
& SDMMC_STA_CTIMEOUT
) != 0) {
327 return SD_CMD_RSP_TIMEOUT
;
329 if(ResponseType
== 3)
332 return SD_CMD_RSP_TIMEOUT
; // Card is not V2.0 compliant or card does not support the set voltage range
334 return SD_OK
; // Card is SD V2.0 compliant
338 if((SDMMC1
->STA
& SDMMC_STA_CCRCFAIL
) != 0) {
339 return SD_CMD_CRC_FAIL
;
341 if(ResponseType
== 2) {
344 if((uint8_t)SDMMC1
->RESPCMD
!= SD_CMD
) {
345 return SD_ILLEGAL_CMD
; // Check if response is of desired command
348 Response_R1
= SDMMC1
->RESP1
; // We have received response, retrieve it for analysis
350 if(ResponseType
== 1)
352 return CheckOCR_Response(Response_R1
);
354 else if(ResponseType
== 6)
356 if((Response_R1
& (SD_R6_GENERAL_UNKNOWN_ERROR
| SD_R6_ILLEGAL_CMD
| SD_R6_COM_CRC_FAILED
)) == SD_ALLZERO
)
358 SD_CardRCA
= Response_R1
;
360 if((Response_R1
& SD_R6_GENERAL_UNKNOWN_ERROR
) == SD_R6_GENERAL_UNKNOWN_ERROR
) {
361 return SD_GENERAL_UNKNOWN_ERROR
;
363 if((Response_R1
& SD_R6_ILLEGAL_CMD
) == SD_R6_ILLEGAL_CMD
) {
364 return SD_ILLEGAL_CMD
;
366 if((Response_R1
& SD_R6_COM_CRC_FAILED
) == SD_R6_COM_CRC_FAILED
) {
367 return SD_COM_CRC_FAILED
;
375 /** -----------------------------------------------------------------------------------------------------------------*/
377 * @brief Analyze the OCR response and return the appropriate error code
378 * @param Response_R1: OCR Response code
379 * @retval SD Card error state
381 static SD_Error_t
CheckOCR_Response(uint32_t Response_R1
)
383 if((Response_R1
& SD_OCR_ERRORBITS
) == SD_ALLZERO
) return SD_OK
;
384 if((Response_R1
& SD_OCR_ADDR_OUT_OF_RANGE
) == SD_OCR_ADDR_OUT_OF_RANGE
) return SD_ADDR_OUT_OF_RANGE
;
385 if((Response_R1
& SD_OCR_ADDR_MISALIGNED
) == SD_OCR_ADDR_MISALIGNED
) return SD_ADDR_MISALIGNED
;
386 if((Response_R1
& SD_OCR_BLOCK_LEN_ERR
) == SD_OCR_BLOCK_LEN_ERR
) return SD_BLOCK_LEN_ERR
;
387 if((Response_R1
& SD_OCR_ERASE_SEQ_ERR
) == SD_OCR_ERASE_SEQ_ERR
) return SD_ERASE_SEQ_ERR
;
388 if((Response_R1
& SD_OCR_BAD_ERASE_PARAM
) == SD_OCR_BAD_ERASE_PARAM
) return SD_BAD_ERASE_PARAM
;
389 if((Response_R1
& SD_OCR_WRITE_PROT_VIOLATION
) == SD_OCR_WRITE_PROT_VIOLATION
) return SD_WRITE_PROT_VIOLATION
;
390 if((Response_R1
& SD_OCR_LOCK_UNLOCK_FAILED
) == SD_OCR_LOCK_UNLOCK_FAILED
) return SD_LOCK_UNLOCK_FAILED
;
391 if((Response_R1
& SD_OCR_COM_CRC_FAILED
) == SD_OCR_COM_CRC_FAILED
) return SD_COM_CRC_FAILED
;
392 if((Response_R1
& SD_OCR_ILLEGAL_CMD
) == SD_OCR_ILLEGAL_CMD
) return SD_ILLEGAL_CMD
;
393 if((Response_R1
& SD_OCR_CARD_ECC_FAILED
) == SD_OCR_CARD_ECC_FAILED
) return SD_CARD_ECC_FAILED
;
394 if((Response_R1
& SD_OCR_CC_ERROR
) == SD_OCR_CC_ERROR
) return SD_CC_ERROR
;
395 if((Response_R1
& SD_OCR_GENERAL_UNKNOWN_ERROR
) == SD_OCR_GENERAL_UNKNOWN_ERROR
)return SD_GENERAL_UNKNOWN_ERROR
;
396 if((Response_R1
& SD_OCR_STREAM_READ_UNDERRUN
) == SD_OCR_STREAM_READ_UNDERRUN
) return SD_STREAM_READ_UNDERRUN
;
397 if((Response_R1
& SD_OCR_STREAM_WRITE_OVERRUN
) == SD_OCR_STREAM_WRITE_OVERRUN
) return SD_STREAM_WRITE_OVERRUN
;
398 if((Response_R1
& SD_OCR_CID_CSD_OVERWRITE
) == SD_OCR_CID_CSD_OVERWRITE
) return SD_CID_CSD_OVERWRITE
;
399 if((Response_R1
& SD_OCR_WP_ERASE_SKIP
) == SD_OCR_WP_ERASE_SKIP
) return SD_WP_ERASE_SKIP
;
400 if((Response_R1
& SD_OCR_CARD_ECC_DISABLED
) == SD_OCR_CARD_ECC_DISABLED
) return SD_CARD_ECC_DISABLED
;
401 if((Response_R1
& SD_OCR_ERASE_RESET
) == SD_OCR_ERASE_RESET
) return SD_ERASE_RESET
;
402 if((Response_R1
& SD_OCR_AKE_SEQ_ERROR
) == SD_OCR_AKE_SEQ_ERROR
) return SD_AKE_SEQ_ERROR
;
408 /** -----------------------------------------------------------------------------------------------------------------*/
411 * @brief Get response from SD device
412 * @param uint32_t* pResponse
414 static void SD_GetResponse(uint32_t* pResponse
)
416 pResponse
[0] = SDMMC1
->RESP1
;
417 pResponse
[1] = SDMMC1
->RESP2
;
418 pResponse
[2] = SDMMC1
->RESP3
;
419 pResponse
[3] = SDMMC1
->RESP4
;
423 /** -----------------------------------------------------------------------------------------------------------------*/
425 * @brief SD DMA transfer complete RX and TX callback.
426 * @param DMA_Stream_TypeDef* pDMA_Stream
428 static void SD_DMA_Complete(DMA_Stream_TypeDef
* pDMA_Stream
)
430 if (SD_Handle
.RXCplt
) {
431 if (SD_Handle
.Operation
== ((SDMMC_DIR_RX
<< 1) | SD_MULTIPLE_BLOCK
)) {
432 /* Send stop command in multiblock write */
433 SD_TransmitCommand((SD_CMD_STOP_TRANSMISSION
| SD_CMD_RESPONSE_SHORT
), 0, 1);
436 /* Disable the DMA transfer for transmit request by setting the DMAEN bit
437 in the SD DCTRL register */
438 SDMMC1
->DCTRL
&= (uint32_t)~((uint32_t)SDMMC_DCTRL_DMAEN
);
440 /* Clear all the static flags */
441 SDMMC1
->ICR
= SDMMC_ICR_STATIC_FLAGS
;
444 SD_Handle
.RXCplt
= 0;
446 /* Disable the stream */
447 pDMA_Stream
->CR
&= ~DMA_SxCR_EN
;
449 /* Enable Dataend IE */
450 SDMMC1
->MASK
|= SDMMC_MASK_DATAENDIE
;
455 /** -----------------------------------------------------------------------------------------------------------------*/
457 * @brief Initializes all cards or single card as the case may be Card(s) come
458 * into standby state.
459 * @retval SD Card error state
461 static SD_Error_t
SD_InitializeCard(void)
463 SD_Error_t ErrorState
= SD_OK
;
465 if((SDMMC1
->POWER
& SDMMC_POWER_PWRCTRL
) != 0) // Power off
467 if(SD_CardType
!= SD_SECURE_DIGITAL_IO
)
469 // Send CMD2 ALL_SEND_CID
470 if((ErrorState
= SD_TransmitCommand((SD_CMD_ALL_SEND_CID
| SD_CMD_RESPONSE_LONG
), 0, 2)) != SD_OK
)
475 // Get Card identification number data
476 SD_GetResponse(SD_Handle
.CID
);
479 if((SD_CardType
== SD_STD_CAPACITY_V1_1
) || (SD_CardType
== SD_STD_CAPACITY_V2_0
) ||
480 (SD_CardType
== SD_SECURE_DIGITAL_IO_COMBO
) || (SD_CardType
== SD_HIGH_CAPACITY
))
482 // Send CMD3 SET_REL_ADDR with argument 0
483 // SD Card publishes its RCA.
484 if((ErrorState
= SD_TransmitCommand((SD_CMD_SET_REL_ADDR
| SD_CMD_RESPONSE_SHORT
), 0, 6)) != SD_OK
)
490 if(SD_CardType
!= SD_SECURE_DIGITAL_IO
)
492 // Send CMD9 SEND_CSD with argument as card's RCA
493 if((ErrorState
= SD_TransmitCommand((SD_CMD_SEND_CSD
| SD_CMD_RESPONSE_LONG
), SD_CardRCA
, 2)) == SD_OK
)
495 // Get Card Specific Data
496 SD_GetResponse(SD_Handle
.CSD
);
502 ErrorState
= SD_REQUEST_NOT_APPLICABLE
;
509 /** -----------------------------------------------------------------------------------------------------------------*/
511 * @brief Prepre the DMA transfer
512 * @param pDMA: DMA Stream to use for the DMA operation
513 * @param pBuffer: Pointer to the buffer that will contain the data to transmit
514 * @param BlockSize: The SD card Data block size
515 * @note BlockSize must be 512 bytes.
516 * @param NumberOfBlocks: Number of blocks to write
517 * @retval SD Card error state
519 static void SD_StartBlockTransfert(uint32_t* pBuffer
, uint32_t BlockSize
, uint32_t NumberOfBlocks
, uint8_t dir
)
521 DMA_Stream_TypeDef
*pDMA
= dmaStream
;
523 SDMMC1
->DCTRL
= 0; // Initialize data control register
524 SD_Handle
.TransferComplete
= 0; // Initialize handle flags
525 SD_Handle
.TransferError
= SD_OK
;
526 SD_Handle
.Operation
= (NumberOfBlocks
> 1) ? SD_MULTIPLE_BLOCK
: SD_SINGLE_BLOCK
; // Initialize SD Read operation
527 SD_Handle
.Operation
|= dir
<< 1;
529 if (dir
== SDMMC_DIR_RX
) {
530 SDMMC1
->MASK
|= (SDMMC_MASK_DCRCFAILIE
| SDMMC_MASK_DTIMEOUTIE
| // Enable transfer interrupts
531 SDMMC_MASK_DATAENDIE
| SDMMC_MASK_RXOVERRIE
);
533 SDMMC1
->MASK
|= (SDMMC_MASK_DCRCFAILIE
| SDMMC_MASK_DTIMEOUTIE
| // Enable transfer interrupts
534 SDMMC_MASK_TXUNDERRIE
);
536 if (dir
== SDMMC_DIR_TX
) {
537 SDMMC1
->DCTRL
|= SDMMC_DCTRL_DMAEN
; // Enable SDMMC1 DMA transfer
539 pDMA
->CR
&= ~DMA_SxCR_EN
; // Disable the Peripheral
540 while (pDMA
->CR
& DMA_SxCR_EN
);
541 pDMA
->NDTR
= (uint32_t) (BlockSize
* NumberOfBlocks
) / 4; // Configure DMA Stream data length
542 pDMA
->M0AR
= (uint32_t) pBuffer
; // Configure DMA Stream memory address
543 if (dir
== SDMMC_DIR_RX
) {
544 pDMA
->CR
&= ~(0x01U
<< 6U); // Sets peripheral to memory
546 pDMA
->CR
|= DMA_MEMORY_TO_PERIPH
; // Sets memory to peripheral
548 if (dmaStream
== DMA2_Stream3
) {
549 DMA2
->LIFCR
= DMA_LIFCR_CTEIF3
| DMA_LIFCR_CDMEIF3
|
550 DMA_LIFCR_CFEIF3
| DMA_LIFCR_CHTIF3
| DMA_LIFCR_CTCIF3
; // Clear the transfer error flag
552 DMA2
->HIFCR
= DMA_HIFCR_CTEIF6
| DMA_HIFCR_CDMEIF6
|
553 DMA_HIFCR_CFEIF6
| DMA_HIFCR_CHTIF6
| DMA_HIFCR_CTCIF6
; // Clear the transfer error flag
555 pDMA
->CR
|= DMA_SxCR_TCIE
| DMA_SxCR_HTIE
| DMA_SxCR_TEIE
| DMA_SxCR_DMEIE
; // Enable all interrupts
556 pDMA
->FCR
|= DMA_SxFCR_FEIE
;
557 pDMA
->CR
|= DMA_SxCR_EN
; // Enable the Peripheral
558 if (dir
== SDMMC_DIR_RX
) {
559 SDMMC1
->DCTRL
|= SDMMC_DCTRL_DMAEN
; // Enable SDMMC1 DMA transfer
564 /** -----------------------------------------------------------------------------------------------------------------*/
566 * @brief Reads block(s) from a specified address in a card. The Data transfer
567 * is managed by DMA mode.
568 * @note This API should be followed by the function SD_CheckOperation()
569 * to check the completion of the read process
570 * @param pReadBuffer: Pointer to the buffer that will contain the received data
571 * @param ReadAddr: Address from where data is to be read
572 * @param BlockSize: SD card Data block size
573 * @note BlockSize must be 512 bytes.
574 * @param NumberOfBlocks: Number of blocks to read.
575 * @retval SD Card error state
577 SD_Error_t
SD_ReadBlocks_DMA(uint64_t ReadAddress
, uint32_t *buffer
, uint32_t BlockSize
, uint32_t NumberOfBlocks
)
579 SD_Error_t ErrorState
;
581 SD_Handle
.RXCplt
= 1;
583 //printf("Reading at %ld into %p %ld blocks\n", (uint32_t)ReadAddress, (void*)buffer, NumberOfBlocks);
585 if(SD_CardType
!= SD_HIGH_CAPACITY
)
590 SD_StartBlockTransfert(buffer
, BlockSize
, NumberOfBlocks
, SDMMC_DIR_RX
);
592 // Configure the SD DPSM (Data Path State Machine)
593 SD_DataTransferInit(BlockSize
* NumberOfBlocks
, SD_DATABLOCK_SIZE_512B
, true);
595 // Set Block Size for Card
596 ErrorState
= SD_TransmitCommand((SD_CMD_SET_BLOCKLEN
| SD_CMD_RESPONSE_SHORT
), BlockSize
, 1);
598 // Send CMD18 READ_MULT_BLOCK with argument data address
599 // or send CMD17 READ_SINGLE_BLOCK depending on number of block
600 uint8_t retries
= 10;
601 CmdIndex
= (NumberOfBlocks
> 1) ? SD_CMD_READ_MULT_BLOCK
: SD_CMD_READ_SINGLE_BLOCK
;
603 ErrorState
= SD_TransmitCommand((CmdIndex
| SD_CMD_RESPONSE_SHORT
), (uint32_t)ReadAddress
, 1);
604 if (ErrorState
!= SD_OK
&& retries
--) {
605 ErrorState
= SD_TransmitCommand((SD_CMD_APP_CMD
| SD_CMD_RESPONSE_SHORT
), 0, 1);
607 } while (ErrorState
!= SD_OK
&& retries
);
609 if (ErrorState
!= SD_OK
) {
610 SD_Handle
.RXCplt
= 0;
613 // Update the SD transfer error in SD handle
614 SD_Handle
.TransferError
= ErrorState
;
620 /** -----------------------------------------------------------------------------------------------------------------*/
622 * @brief Writes block(s) to a specified address in a card. The Data transfer
623 * is managed by DMA mode.
624 * @note This API should be followed by the function SD_CheckOperation()
625 * to check the completion of the write process (by SD current status polling).
626 * @param pWriteBuffer: pointer to the buffer that will contain the data to transmit
627 * @param WriteAddress: Address from where data is to be read
628 * @param BlockSize: the SD card Data block size
629 * @note BlockSize must be 512 bytes.
630 * @param NumberOfBlocks: Number of blocks to write
631 * @retval SD Card error state
633 SD_Error_t
SD_WriteBlocks_DMA(uint64_t WriteAddress
, uint32_t *buffer
, uint32_t BlockSize
, uint32_t NumberOfBlocks
)
635 SD_Error_t ErrorState
;
637 SD_Handle
.TXCplt
= 1;
639 //printf("Reading at %ld into %p %ld blocks\n", (uint32_t)WriteAddress, (void*)buffer, NumberOfBlocks);
641 if(SD_CardType
!= SD_HIGH_CAPACITY
)
646 // Check number of blocks command
647 // Send CMD24 WRITE_SINGLE_BLOCK
648 // Send CMD25 WRITE_MULT_BLOCK with argument data address
649 CmdIndex
= (NumberOfBlocks
> 1) ? SD_CMD_WRITE_MULT_BLOCK
: SD_CMD_WRITE_SINGLE_BLOCK
;
651 // Set Block Size for Card
652 uint8_t retries
= 10;
654 ErrorState
= SD_TransmitCommand((CmdIndex
| SD_CMD_RESPONSE_SHORT
), (uint32_t)WriteAddress
, 1);
655 if (ErrorState
!= SD_OK
&& retries
--) {
656 ErrorState
= SD_TransmitCommand((SD_CMD_APP_CMD
| SD_CMD_RESPONSE_SHORT
), 0, 1);
658 } while(ErrorState
!= SD_OK
&& retries
);
660 if (ErrorState
!= SD_OK
) {
661 SD_Handle
.TXCplt
= 0;
665 SD_StartBlockTransfert(buffer
, BlockSize
, NumberOfBlocks
, SDMMC_DIR_TX
);
667 // Configure the SD DPSM (Data Path State Machine)
668 SD_DataTransferInit(BlockSize
* NumberOfBlocks
, SD_DATABLOCK_SIZE_512B
, false);
670 SD_Handle
.TransferError
= ErrorState
;
675 SD_Error_t
SD_CheckWrite(void) {
676 if (SD_Handle
.TXCplt
!= 0) return SD_BUSY
;
680 SD_Error_t
SD_CheckRead(void) {
681 if (SD_Handle
.RXCplt
!= 0) return SD_BUSY
;
685 /** -----------------------------------------------------------------------------------------------------------------*/
687 * @brief This function waits until the SD DMA data wirte or read transfer is finished.
688 * This should be called after WriteBlocks_DMA or SD_ReadBlocks_DMA() function
689 * to insure that all data sent is already transferred by the DMA controller.
690 * @retval SD Card error state
693 SD_Error_t SD_CheckOperation(uint32_t Flag)
695 SD_Error_t ErrorState = SD_OK;
701 // Wait for DMA/SD transfer end or SD error variables to be in SD handle
702 Temp1 = SD_Handle.DMA_XferComplete;
703 Temp2 = SD_Handle.TransferComplete;
704 Temp3 = (SD_Error_t)SD_Handle.TransferError;
706 if (((Temp1 & Temp2) == 0) && (Temp3 == SD_OK) && (TimeOut > 0))
708 Temp1 = SD_Handle.DMA_XferComplete;
709 Temp2 = SD_Handle.TransferComplete;
710 Temp3 = (SD_Error_t)SD_Handle.TransferError;
715 // Wait until the Rx transfer is no longer active
716 if (((SDMMC1->STA & Flag) != 0) && (TimeOut > 0))
722 // Send stop command in multi block read
723 if(SD_Handle.Operation & 0x01 == SD_MULTIPLE_BLOCK)
725 ErrorState = SD_TransmitCommand((SD_CMD_STOP_TRANSMISSION | SD_CMD_RESPONSE_SHORT), 0, 1);
728 if((TimeOut == 0) && (ErrorState == SD_OK))
730 ErrorState = SD_DATA_TIMEOUT;
733 // Return error state
734 if(SD_Handle.TransferError != SD_OK)
736 return (SD_Error_t)(SD_Handle.TransferError);
743 /** -----------------------------------------------------------------------------------------------------------------*/
745 * @brief Erases the specified memory area of the given SD card.
746 * @param StartAddress: Start byte address
747 * @param EndAddress: End byte address
748 * @retval SD Card error state
751 SD_Error_t SD_Erase(uint64_t StartAddress, uint64_t EndAddress)
753 SD_Error_t ErrorState;
758 // Check if the card command class supports erase command
759 if(((SD_Handle.CSD[1] >> 20) & SD_CCCC_ERASE) == 0)
761 return SD_REQUEST_NOT_APPLICABLE;
764 // Get max delay value
765 MaxDelay = 120000 / (((SDMMC1->CLKCR) & 0xFF) + 2);
767 if((SDMMC1->RESP1 & SD_CARD_LOCKED) == SD_CARD_LOCKED)
769 return SD_LOCK_UNLOCK_FAILED;
772 // Get start and end block for high capacity cards
773 if(SD_CardType == SD_HIGH_CAPACITY)
779 // According to sd-card spec 1.0 ERASE_GROUP_START (CMD32) and erase_group_end(CMD33)
780 if ((SD_CardType == SD_STD_CAPACITY_V1_1) || (SD_CardType == SD_STD_CAPACITY_V2_0) ||
781 (SD_CardType == SD_HIGH_CAPACITY))
783 // Send CMD32 SD_ERASE_GRP_START with argument as addr
784 if((ErrorState = SD_TransmitCommand((SD_CMD_SD_ERASE_GRP_START | SDMMC_CMD_RESPONSE_SHORT), (uint32_t)StartAddress, 1)) != SD_OK)
789 // Send CMD33 SD_ERASE_GRP_END with argument as addr
790 if((ErrorState = SD_TransmitCommand((SD_CMD_SD_ERASE_GRP_END | SDMMC_CMD_RESPONSE_SHORT), (uint32_t)EndAddress, 1)) != SD_OK)
797 if((ErrorState = SD_TransmitCommand((SD_CMD_ERASE | SDMMC_CMD_RESPONSE_SHORT), 0, 1)) != SD_OK)
802 for(Delay = 0; Delay < MaxDelay; Delay++);
804 // Wait until the card is in programming state
805 ErrorState = SD_IsCardProgramming(&CardState);
807 Delay = SD_DATATIMEOUT;
808 while((Delay > 0) && (ErrorState == SD_OK) && ((CardState == SD_CARD_PROGRAMMING) || (CardState == SD_CARD_RECEIVING)))
810 ErrorState = SD_IsCardProgramming( &CardState);
819 /** -----------------------------------------------------------------------------------------------------------------*/
821 * @brief Returns information about specific card.
822 * contains all SD cardinformation
823 * @retval SD Card error state
825 SD_Error_t
SD_GetCardInfo(void)
827 SD_Error_t ErrorState
= SD_OK
;
831 Temp
= (SD_Handle
.CSD
[0] & 0xFF000000) >> 24;
832 SD_CardInfo
.SD_csd
.CSDStruct
= (uint8_t)((Temp
& 0xC0) >> 6);
833 SD_CardInfo
.SD_csd
.SysSpecVersion
= (uint8_t)((Temp
& 0x3C) >> 2);
834 SD_CardInfo
.SD_csd
.Reserved1
= Temp
& 0x03;
837 Temp
= (SD_Handle
.CSD
[0] & 0x00FF0000) >> 16;
838 SD_CardInfo
.SD_csd
.TAAC
= (uint8_t)Temp
;
841 Temp
= (SD_Handle
.CSD
[0] & 0x0000FF00) >> 8;
842 SD_CardInfo
.SD_csd
.NSAC
= (uint8_t)Temp
;
845 Temp
= SD_Handle
.CSD
[0] & 0x000000FF;
846 SD_CardInfo
.SD_csd
.MaxBusClkFrec
= (uint8_t)Temp
;
849 Temp
= (SD_Handle
.CSD
[1] & 0xFF000000) >> 24;
850 SD_CardInfo
.SD_csd
.CardComdClasses
= (uint16_t)(Temp
<< 4);
853 Temp
= (SD_Handle
.CSD
[1] & 0x00FF0000) >> 16;
854 SD_CardInfo
.SD_csd
.CardComdClasses
|= (uint16_t)((Temp
& 0xF0) >> 4);
855 SD_CardInfo
.SD_csd
.RdBlockLen
= (uint8_t)(Temp
& 0x0F);
858 Temp
= (SD_Handle
.CSD
[1] & 0x0000FF00) >> 8;
859 SD_CardInfo
.SD_csd
.PartBlockRead
= (uint8_t)((Temp
& 0x80) >> 7);
860 SD_CardInfo
.SD_csd
.WrBlockMisalign
= (uint8_t)((Temp
& 0x40) >> 6);
861 SD_CardInfo
.SD_csd
.RdBlockMisalign
= (uint8_t)((Temp
& 0x20) >> 5);
862 SD_CardInfo
.SD_csd
.DSRImpl
= (uint8_t)((Temp
& 0x10) >> 4);
863 SD_CardInfo
.SD_csd
.Reserved2
= 0; /*!< Reserved */
865 if((SD_CardType
== SD_STD_CAPACITY_V1_1
) || (SD_CardType
== SD_STD_CAPACITY_V2_0
))
867 SD_CardInfo
.SD_csd
.DeviceSize
= (Temp
& 0x03) << 10;
870 Temp
= (uint8_t)(SD_Handle
.CSD
[1] & 0x000000FF);
871 SD_CardInfo
.SD_csd
.DeviceSize
|= (Temp
) << 2;
874 Temp
= (uint8_t)((SD_Handle
.CSD
[2] & 0xFF000000) >> 24);
875 SD_CardInfo
.SD_csd
.DeviceSize
|= (Temp
& 0xC0) >> 6;
877 SD_CardInfo
.SD_csd
.MaxRdCurrentVDDMin
= (Temp
& 0x38) >> 3;
878 SD_CardInfo
.SD_csd
.MaxRdCurrentVDDMax
= (Temp
& 0x07);
881 Temp
= (uint8_t)((SD_Handle
.CSD
[2] & 0x00FF0000) >> 16);
882 SD_CardInfo
.SD_csd
.MaxWrCurrentVDDMin
= (Temp
& 0xE0) >> 5;
883 SD_CardInfo
.SD_csd
.MaxWrCurrentVDDMax
= (Temp
& 0x1C) >> 2;
884 SD_CardInfo
.SD_csd
.DeviceSizeMul
= (Temp
& 0x03) << 1;
887 Temp
= (uint8_t)((SD_Handle
.CSD
[2] & 0x0000FF00) >> 8);
888 SD_CardInfo
.SD_csd
.DeviceSizeMul
|= (Temp
& 0x80) >> 7;
890 SD_CardInfo
.CardCapacity
= (SD_CardInfo
.SD_csd
.DeviceSize
+ 1) ;
891 SD_CardInfo
.CardCapacity
*= (1 << (SD_CardInfo
.SD_csd
.DeviceSizeMul
+ 2));
892 SD_CardInfo
.CardBlockSize
= 1 << (SD_CardInfo
.SD_csd
.RdBlockLen
);
893 SD_CardInfo
.CardCapacity
= SD_CardInfo
.CardCapacity
* SD_CardInfo
.CardBlockSize
/ 512; // In 512 byte blocks
895 else if(SD_CardType
== SD_HIGH_CAPACITY
)
898 Temp
= (uint8_t)(SD_Handle
.CSD
[1] & 0x000000FF);
899 SD_CardInfo
.SD_csd
.DeviceSize
= (Temp
& 0x3F) << 16;
902 Temp
= (uint8_t)((SD_Handle
.CSD
[2] & 0xFF000000) >> 24);
904 SD_CardInfo
.SD_csd
.DeviceSize
|= (Temp
<< 8);
907 Temp
= (uint8_t)((SD_Handle
.CSD
[2] & 0x00FF0000) >> 16);
909 SD_CardInfo
.SD_csd
.DeviceSize
|= (Temp
);
912 Temp
= (uint8_t)((SD_Handle
.CSD
[2] & 0x0000FF00) >> 8);
914 SD_CardInfo
.CardCapacity
= ((uint64_t)SD_CardInfo
.SD_csd
.DeviceSize
+ 1) * 1024;
915 SD_CardInfo
.CardBlockSize
= 512;
919 // Not supported card type
920 ErrorState
= SD_ERROR
;
923 SD_CardInfo
.SD_csd
.EraseGrSize
= (Temp
& 0x40) >> 6;
924 SD_CardInfo
.SD_csd
.EraseGrMul
= (Temp
& 0x3F) << 1;
927 Temp
= (uint8_t)(SD_Handle
.CSD
[2] & 0x000000FF);
928 SD_CardInfo
.SD_csd
.EraseGrMul
|= (Temp
& 0x80) >> 7;
929 SD_CardInfo
.SD_csd
.WrProtectGrSize
= (Temp
& 0x7F);
932 Temp
= (uint8_t)((SD_Handle
.CSD
[3] & 0xFF000000) >> 24);
933 SD_CardInfo
.SD_csd
.WrProtectGrEnable
= (Temp
& 0x80) >> 7;
934 SD_CardInfo
.SD_csd
.ManDeflECC
= (Temp
& 0x60) >> 5;
935 SD_CardInfo
.SD_csd
.WrSpeedFact
= (Temp
& 0x1C) >> 2;
936 SD_CardInfo
.SD_csd
.MaxWrBlockLen
= (Temp
& 0x03) << 2;
939 Temp
= (uint8_t)((SD_Handle
.CSD
[3] & 0x00FF0000) >> 16);
940 SD_CardInfo
.SD_csd
.MaxWrBlockLen
|= (Temp
& 0xC0) >> 6;
941 SD_CardInfo
.SD_csd
.WriteBlockPaPartial
= (Temp
& 0x20) >> 5;
942 SD_CardInfo
.SD_csd
.Reserved3
= 0;
943 SD_CardInfo
.SD_csd
.ContentProtectAppli
= (Temp
& 0x01);
946 Temp
= (uint8_t)((SD_Handle
.CSD
[3] & 0x0000FF00) >> 8);
947 SD_CardInfo
.SD_csd
.FileFormatGrouop
= (Temp
& 0x80) >> 7;
948 SD_CardInfo
.SD_csd
.CopyFlag
= (Temp
& 0x40) >> 6;
949 SD_CardInfo
.SD_csd
.PermWrProtect
= (Temp
& 0x20) >> 5;
950 SD_CardInfo
.SD_csd
.TempWrProtect
= (Temp
& 0x10) >> 4;
951 SD_CardInfo
.SD_csd
.FileFormat
= (Temp
& 0x0C) >> 2;
952 SD_CardInfo
.SD_csd
.ECC
= (Temp
& 0x03);
955 Temp
= (uint8_t)(SD_Handle
.CSD
[3] & 0x000000FF);
956 SD_CardInfo
.SD_csd
.CSD_CRC
= (Temp
& 0xFE) >> 1;
957 SD_CardInfo
.SD_csd
.Reserved4
= 1;
960 Temp
= (uint8_t)((SD_Handle
.CID
[0] & 0xFF000000) >> 24);
961 SD_CardInfo
.SD_cid
.ManufacturerID
= Temp
;
964 Temp
= (uint8_t)((SD_Handle
.CID
[0] & 0x00FF0000) >> 16);
965 SD_CardInfo
.SD_cid
.OEM_AppliID
= Temp
<< 8;
968 Temp
= (uint8_t)((SD_Handle
.CID
[0] & 0x000000FF00) >> 8);
969 SD_CardInfo
.SD_cid
.OEM_AppliID
|= Temp
;
972 Temp
= (uint8_t)(SD_Handle
.CID
[0] & 0x000000FF);
973 SD_CardInfo
.SD_cid
.ProdName1
= Temp
<< 24;
976 Temp
= (uint8_t)((SD_Handle
.CID
[1] & 0xFF000000) >> 24);
977 SD_CardInfo
.SD_cid
.ProdName1
|= Temp
<< 16;
980 Temp
= (uint8_t)((SD_Handle
.CID
[1] & 0x00FF0000) >> 16);
981 SD_CardInfo
.SD_cid
.ProdName1
|= Temp
<< 8;
984 Temp
= (uint8_t)((SD_Handle
.CID
[1] & 0x0000FF00) >> 8);
985 SD_CardInfo
.SD_cid
.ProdName1
|= Temp
;
988 Temp
= (uint8_t)(SD_Handle
.CID
[1] & 0x000000FF);
989 SD_CardInfo
.SD_cid
.ProdName2
= Temp
;
992 Temp
= (uint8_t)((SD_Handle
.CID
[2] & 0xFF000000) >> 24);
993 SD_CardInfo
.SD_cid
.ProdRev
= Temp
;
996 Temp
= (uint8_t)((SD_Handle
.CID
[2] & 0x00FF0000) >> 16);
997 SD_CardInfo
.SD_cid
.ProdSN
= Temp
<< 24;
1000 Temp
= (uint8_t)((SD_Handle
.CID
[2] & 0x0000FF00) >> 8);
1001 SD_CardInfo
.SD_cid
.ProdSN
|= Temp
<< 16;
1004 Temp
= (uint8_t)(SD_Handle
.CID
[2] & 0x000000FF);
1005 SD_CardInfo
.SD_cid
.ProdSN
|= Temp
<< 8;
1008 Temp
= (uint8_t)((SD_Handle
.CID
[3] & 0xFF000000) >> 24);
1009 SD_CardInfo
.SD_cid
.ProdSN
|= Temp
;
1012 Temp
= (uint8_t)((SD_Handle
.CID
[3] & 0x00FF0000) >> 16);
1013 SD_CardInfo
.SD_cid
.Reserved1
|= (Temp
& 0xF0) >> 4;
1014 SD_CardInfo
.SD_cid
.ManufactDate
= (Temp
& 0x0F) << 8;
1017 Temp
= (uint8_t)((SD_Handle
.CID
[3] & 0x0000FF00) >> 8);
1018 SD_CardInfo
.SD_cid
.ManufactDate
|= Temp
;
1021 Temp
= (uint8_t)(SD_Handle
.CID
[3] & 0x000000FF);
1022 SD_CardInfo
.SD_cid
.CID_CRC
= (Temp
& 0xFE) >> 1;
1023 SD_CardInfo
.SD_cid
.Reserved2
= 1;
1029 /** -----------------------------------------------------------------------------------------------------------------*/
1031 * @brief Enables wide bus operation for the requested card if supported by
1033 * @param WideMode: Specifies the SD card wide bus mode
1034 * This parameter can be one of the following values:
1035 * @arg SD_BUS_WIDE_8B: 8-bit data transfer (Only for MMC)
1036 * @arg SD_BUS_WIDE_4B: 4-bit data transfer
1037 * @arg SD_BUS_WIDE_1B: 1-bit data transfer
1038 * @retval SD Card error state
1040 static SD_Error_t
SD_WideBusOperationConfig(uint32_t WideMode
)
1042 SD_Error_t ErrorState
= SD_OK
;
1044 uint32_t SCR
[2] = {0, 0};
1046 if((SD_CardType
== SD_STD_CAPACITY_V1_1
) || (SD_CardType
== SD_STD_CAPACITY_V2_0
) ||\
1047 (SD_CardType
== SD_HIGH_CAPACITY
))
1049 if(WideMode
== SD_BUS_WIDE_8B
)
1051 ErrorState
= SD_UNSUPPORTED_FEATURE
;
1053 else if((WideMode
== SD_BUS_WIDE_4B
) ||
1054 (WideMode
== SD_BUS_WIDE_1B
))
1056 if((SDMMC1
->RESP1
& SD_CARD_LOCKED
) != SD_CARD_LOCKED
)
1059 ErrorState
= SD_FindSCR(SCR
);
1060 if(ErrorState
== SD_OK
)
1062 Temp
= (WideMode
== SD_BUS_WIDE_4B
) ? SD_WIDE_BUS_SUPPORT
: SD_SINGLE_BUS_SUPPORT
;
1064 // If requested card supports wide bus operation
1065 if((SCR
[1] & Temp
) != SD_ALLZERO
)
1067 // Send CMD55 APP_CMD with argument as card's RCA.
1068 ErrorState
= SD_TransmitCommand((SD_CMD_APP_CMD
| SD_CMD_RESPONSE_SHORT
), SD_CardRCA
, 1);
1069 if(ErrorState
== SD_OK
)
1071 Temp
= (WideMode
== SD_BUS_WIDE_4B
) ? 2 : 0;
1073 // Send ACMD6 APP_CMD with argument as 2 for wide bus mode
1074 ErrorState
= SD_TransmitCommand((SD_CMD_APP_SD_SET_BUSWIDTH
| SD_CMD_RESPONSE_SHORT
), Temp
, 1);
1079 ErrorState
= SD_REQUEST_NOT_APPLICABLE
;
1085 ErrorState
= SD_LOCK_UNLOCK_FAILED
;
1090 ErrorState
= SD_INVALID_PARAMETER
; // WideMode is not a valid argument
1093 if(ErrorState
== SD_OK
)
1095 // Configure the SDMMC1 peripheral, we need this delay for some reason...
1096 while ((READ_REG(SDMMC1
->CLKCR
) & 0x800) != WideMode
) {
1097 MODIFY_REG(SDMMC1
->CLKCR
, CLKCR_CLEAR_MASK
, (uint32_t) WideMode
);
1102 ErrorState
= SD_UNSUPPORTED_FEATURE
;
1110 /** -----------------------------------------------------------------------------------------------------------------*/
1112 * @brief Switches the SD card to High Speed mode.
1113 * This API must be used after "Transfer State"
1114 * @retval SD Card error state
1117 SD_Error_t HAL_SD_HighSpeed(void)
1119 SD_Error_t ErrorState;
1120 uint8_t SD_hs[64] = {0};
1121 uint32_t SD_scr[2] = {0, 0};
1122 uint32_t SD_SPEC = 0;
1124 uint32_t* Buffer = (uint32_t *)SD_hs;
1126 // Initialize the Data control register
1130 if((ErrorState = SD_FindSCR(SD_scr)) != SD_OK)
1135 // Test the Version supported by the card
1136 SD_SPEC = (SD_scr[1] & 0x01000000) | (SD_scr[1] & 0x02000000);
1138 if(SD_SPEC != SD_ALLZERO)
1140 // Set Block Size for Card
1141 if((ErrorState = SD_TransmitCommand((SD_CMD_SET_BLOCKLEN | SDMMC_CMD_RESPONSE_SHORT), 64, 1)) != SD_OK)
1146 // Configure the SD DPSM (Data Path State Machine)
1147 SD_DataTransferInit(64, SDMMC_DATABLOCK_SIZE_64B, true);
1149 // Send CMD6 switch mode
1150 if((ErrorState =SD_TransmitCommand((SD_CMD_HS_SWITCH | SDMMC_CMD_RESPONSE_SHORT), 0x80FFFF01, 1)) != SD_OK)
1155 while((SDMMC1->STA & (SDMMC_STA_RXOVERR | SDMMC_STA_DCRCFAIL | SDMMC_STA_DTIMEOUT | SDMMC_STA_DBCKEND)) == 0)
1157 if((SDMMC1->STA & SDMMC_STA_RXFIFOHF) != 0)
1159 for(Count = 0; Count < 8; Count++)
1161 *(Buffer + Count) = SDMMC1->FIFO;
1168 if((SDMMC1->STA & SDMMC_STA_DTIMEOUT) != 0) return SD_DATA_TIMEOUT;
1169 else if((SDMMC1->STA & SDMMC_STA_DCRCFAIL) != 0) return SD_DATA_CRC_FAIL;
1170 else if((SDMMC1->STA & SDMMC_STA_RXOVERR) != 0) return SD_RX_OVERRUN;
1172 Count = SD_DATATIMEOUT;
1174 while(((SDMMC1->STA & SDMMC_STA_RXDAVL) != 0) && (Count > 0))
1176 *Buffer = SDMMC1->FIFO;
1181 // Test if the switch mode HS is ok
1182 if((SD_hs[13] & 2) != 2)
1184 ErrorState = SD_UNSUPPORTED_FEATURE;
1194 /** -----------------------------------------------------------------------------------------------------------------*/
1196 * @brief Gets the current card's data status.
1197 * @retval Data Transfer state
1199 SD_Error_t
SD_GetStatus(void)
1201 SD_Error_t ErrorState
;
1203 SD_CardState_t CardState
;
1206 // Send Status command
1207 if((ErrorState
= SD_TransmitCommand((SD_CMD_SEND_STATUS
| SD_CMD_RESPONSE_SHORT
), SD_CardRCA
, 1)) == SD_OK
)
1209 Response1
= SDMMC1
->RESP1
;
1210 CardState
= (SD_CardState_t
)((Response1
>> 9) & 0x0F);
1212 // Find SD status according to card state
1213 if (CardState
== SD_CARD_TRANSFER
) ErrorState
= SD_OK
;
1214 else if(CardState
== SD_CARD_ERROR
) ErrorState
= SD_ERROR
;
1215 else ErrorState
= SD_BUSY
;
1219 ErrorState
= SD_CARD_ERROR
;
1226 /** -----------------------------------------------------------------------------------------------------------------*/
1228 * @brief Gets the SD card status.
1229 * @retval SD Card error state
1231 SD_Error_t
SD_GetCardStatus(SD_CardStatus_t
* pCardStatus
)
1233 SD_Error_t ErrorState
;
1235 uint32_t Status
[16];
1238 // Check SD response
1239 if((SDMMC1
->RESP1
& SD_CARD_LOCKED
) == SD_CARD_LOCKED
)
1241 return SD_LOCK_UNLOCK_FAILED
;
1244 // Set block size for card if it is not equal to current block size for card
1245 if((ErrorState
= SD_TransmitCommand((SD_CMD_SET_BLOCKLEN
| SD_CMD_RESPONSE_SHORT
), 64, 1)) != SD_OK
)
1251 if((ErrorState
= SD_TransmitCommand((SD_CMD_APP_CMD
| SD_CMD_RESPONSE_SHORT
), SD_CardRCA
, 1)) != SD_OK
)
1256 // Configure the SD DPSM (Data Path State Machine)
1257 SD_DataTransferInit(64, SD_DATABLOCK_SIZE_64B
, true);
1259 // Send ACMD13 (SD_APP_STAUS) with argument as card's RCA
1260 if((ErrorState
= SD_TransmitCommand((SD_CMD_SD_APP_STATUS
| SD_CMD_RESPONSE_SHORT
), 0, 1)) != SD_OK
)
1266 while((SDMMC1
->STA
& (SDMMC_STA_RXOVERR
| SDMMC_STA_DCRCFAIL
| SDMMC_STA_DTIMEOUT
| SDMMC_STA_DBCKEND
)) == 0)
1268 if((SDMMC1
->STA
& SDMMC_STA_RXFIFOHF
) != 0)
1270 for(Count
= 0; Count
< 8; Count
++)
1272 Status
[Count
] = SDMMC1
->FIFO
;
1277 if((SDMMC1
->STA
& SDMMC_STA_DTIMEOUT
) != 0) return SD_DATA_TIMEOUT
;
1278 else if((SDMMC1
->STA
& SDMMC_STA_DCRCFAIL
) != 0) return SD_DATA_CRC_FAIL
;
1279 else if((SDMMC1
->STA
& SDMMC_STA_RXOVERR
) != 0) return SD_RX_OVERRUN
;
1283 this part from the HAL is very strange has it is possible to overflow the provide buffer... and this originate from ST HAL
1285 Count = SD_DATATIMEOUT;
1286 while(((SDMMC1->STA & SDMMC_STA_RXDAVL) != 0) && (Count > 0))
1288 *pSDstatus = SDMMC1->FIFO;
1296 Temp
= (Status
[0] & 0xC0) >> 6;
1297 pCardStatus
->DAT_BUS_WIDTH
= (uint8_t)Temp
;
1300 Temp
= (Status
[0] & 0x20) >> 5;
1301 pCardStatus
->SECURED_MODE
= (uint8_t)Temp
;
1304 Temp
= (Status
[2] & 0xFF);
1305 pCardStatus
->SD_CARD_TYPE
= (uint8_t)(Temp
<< 8);
1308 Temp
= (Status
[3] & 0xFF);
1309 pCardStatus
->SD_CARD_TYPE
|= (uint8_t)Temp
;
1312 Temp
= (Status
[4] & 0xFF);
1313 pCardStatus
->SIZE_OF_PROTECTED_AREA
= (uint8_t)(Temp
<< 24);
1316 Temp
= (Status
[5] & 0xFF);
1317 pCardStatus
->SIZE_OF_PROTECTED_AREA
|= (uint8_t)(Temp
<< 16);
1320 Temp
= (Status
[6] & 0xFF);
1321 pCardStatus
->SIZE_OF_PROTECTED_AREA
|= (uint8_t)(Temp
<< 8);
1324 Temp
= (Status
[7] & 0xFF);
1325 pCardStatus
->SIZE_OF_PROTECTED_AREA
|= (uint8_t)Temp
;
1328 Temp
= (Status
[8] & 0xFF);
1329 pCardStatus
->SPEED_CLASS
= (uint8_t)Temp
;
1332 Temp
= (Status
[9] & 0xFF);
1333 pCardStatus
->PERFORMANCE_MOVE
= (uint8_t)Temp
;
1336 Temp
= (Status
[10] & 0xF0) >> 4;
1337 pCardStatus
->AU_SIZE
= (uint8_t)Temp
;
1340 Temp
= (Status
[11] & 0xFF);
1341 pCardStatus
->ERASE_SIZE
= (uint8_t)(Temp
<< 8);
1344 Temp
= (Status
[12] & 0xFF);
1345 pCardStatus
->ERASE_SIZE
|= (uint8_t)Temp
;
1348 Temp
= (Status
[13] & 0xFC) >> 2;
1349 pCardStatus
->ERASE_TIMEOUT
= (uint8_t)Temp
;
1352 Temp
= (Status
[13] & 0x3);
1353 pCardStatus
->ERASE_OFFSET
= (uint8_t)Temp
;
1359 /** -----------------------------------------------------------------------------------------------------------------*/
1361 * @brief Enquires cards about their operating voltage and configures clock
1362 * controls and stores SD information that will be needed in future
1364 * @retval SD Card error state
1366 static SD_Error_t
SD_PowerON(void)
1368 SD_Error_t ErrorState
;
1371 uint32_t ValidVoltage
;
1373 //uint32_t TickStart;
1377 SD_Type
= SD_RESP_STD_CAPACITY
;
1379 // Power ON Sequence -------------------------------------------------------
1380 SDMMC1
->CLKCR
&= ~SDMMC_CLKCR_CLKEN
; // Disable SDMMC1 Clock
1381 SDMMC1
->POWER
= SDMMC_POWER_PWRCTRL
; // Set Power State to ON
1383 // 1ms: required power up waiting time before starting the SD initialization sequence (make it 2 to be safe)
1386 SDMMC1
->CLKCR
|= SDMMC_CLKCR_CLKEN
; // Enable SDMMC1 Clock
1388 // CMD0: GO_IDLE_STATE -----------------------------------------------------
1389 // No CMD response required
1390 if((ErrorState
= SD_TransmitCommand(SD_CMD_GO_IDLE_STATE
, 0, 0)) != SD_OK
)
1392 // CMD Response Timeout (wait for CMDSENT flag)
1396 // CMD8: SEND_IF_COND ------------------------------------------------------
1397 // Send CMD8 to verify SD card interface operating condition
1398 // Argument: - [31:12]: Reserved (shall be set to '0')
1399 //- [11:8]: Supply Voltage (VHS) 0x1 (Range: 2.7-3.6 V)
1400 //- [7:0]: Check Pattern (recommended 0xAA)
1401 // CMD Response: R7 */
1402 if((ErrorState
= SD_TransmitCommand((SD_SDMMC_SEND_IF_COND
| SD_CMD_RESPONSE_SHORT
), SD_CHECK_PATTERN
, 7)) == SD_OK
)
1405 SD_CardType
= SD_STD_CAPACITY_V2_0
;
1406 SD_Type
= SD_RESP_HIGH_CAPACITY
;
1410 // If ErrorState is Command Timeout, it is a MMC card
1411 // If ErrorState is SD_OK it is a SD card: SD card 2.0 (voltage range mismatch) or SD card 1.x
1412 if((ErrorState
= SD_TransmitCommand((SD_CMD_APP_CMD
| SD_CMD_RESPONSE_SHORT
), 0, 1)) == SD_OK
)
1415 // Send ACMD41 SD_APP_OP_COND with Argument 0x80100000
1416 while((ValidVoltage
== 0) && (Count
< SD_MAX_VOLT_TRIAL
))
1418 // SEND CMD55 APP_CMD with RCA as 0
1419 if((ErrorState
= SD_TransmitCommand((SD_CMD_APP_CMD
| SD_CMD_RESPONSE_SHORT
), 0, 1)) != SD_OK
)
1425 if((ErrorState
= SD_TransmitCommand((SD_CMD_SD_APP_OP_COND
| SD_CMD_RESPONSE_SHORT
), SD_VOLTAGE_WINDOW_SD
| SD_Type
, 3)) != SD_OK
)
1430 Response
= SDMMC1
->RESP1
; // Get command response
1431 ValidVoltage
= (((Response
>> 31) == 1) ? 1 : 0); // Get operating voltage
1435 if(Count
>= SD_MAX_VOLT_TRIAL
)
1437 return SD_INVALID_VOLTRANGE
;
1440 if((Response
& SD_RESP_HIGH_CAPACITY
) == SD_RESP_HIGH_CAPACITY
)
1442 SD_CardType
= SD_HIGH_CAPACITY
;
1450 /** -----------------------------------------------------------------------------------------------------------------*/
1452 * @brief Turns the SDMMC1 output signals off.
1453 * @retval SD Card error state
1456 static void SD_PowerOFF(void)
1458 // Set Power State to OFF
1459 SDMMC1
->POWER
= (uint32_t)0;
1464 /** -----------------------------------------------------------------------------------------------------------------*/
1466 * @brief Finds the SD card SCR register value.
1467 * @param pSCR: pointer to the buffer that will contain the SCR value
1468 * @retval SD Card error state
1470 static SD_Error_t
SD_FindSCR(uint32_t *pSCR
)
1472 SD_Error_t ErrorState
;
1474 uint32_t tempscr
[2] = {0, 0};
1476 // Set Block Size To 8 Bytes
1477 // Send CMD55 APP_CMD with argument as card's RCA
1478 if((ErrorState
= SD_TransmitCommand((SD_CMD_SET_BLOCKLEN
| SD_CMD_RESPONSE_SHORT
), 8, 1)) == SD_OK
)
1480 // Send CMD55 APP_CMD with argument as card's RCA
1481 if((ErrorState
= SD_TransmitCommand((SD_CMD_APP_CMD
| SD_CMD_RESPONSE_SHORT
), SD_CardRCA
, 1)) == SD_OK
)
1483 SD_DataTransferInit(8, SD_DATABLOCK_SIZE_8B
, true);
1485 // Send ACMD51 SD_APP_SEND_SCR with argument as 0
1486 if((ErrorState
= SD_TransmitCommand((SD_CMD_SD_APP_SEND_SCR
| SD_CMD_RESPONSE_SHORT
), 0, 1)) == SD_OK
)
1488 while((SDMMC1
->STA
& (SDMMC_STA_RXOVERR
| SDMMC_STA_DCRCFAIL
| SDMMC_STA_DTIMEOUT
| SDMMC_STA_DBCKEND
)) == 0)
1490 if((SDMMC1
->STA
& SDMMC_STA_RXDAVL
) != 0)
1492 *(tempscr
+ Index
) = SDMMC1
->FIFO
;
1497 if ((SDMMC1
->STA
& SDMMC_STA_DTIMEOUT
) != 0) ErrorState
= SD_DATA_TIMEOUT
;
1498 else if((SDMMC1
->STA
& SDMMC_STA_DCRCFAIL
) != 0) ErrorState
= SD_DATA_CRC_FAIL
;
1499 else if((SDMMC1
->STA
& SDMMC_STA_RXOVERR
) != 0) ErrorState
= SD_RX_OVERRUN
;
1500 else if((SDMMC1
->STA
& SDMMC_STA_RXDAVL
) != 0) ErrorState
= SD_OUT_OF_BOUND
;
1503 *(pSCR
+ 1) = ((tempscr
[0] & SD_0TO7BITS
) << 24) | ((tempscr
[0] & SD_8TO15BITS
) << 8) |
1504 ((tempscr
[0] & SD_16TO23BITS
) >> 8) | ((tempscr
[0] & SD_24TO31BITS
) >> 24);
1506 *(pSCR
) = ((tempscr
[1] & SD_0TO7BITS
) << 24) | ((tempscr
[1] & SD_8TO15BITS
) << 8) |
1507 ((tempscr
[1] & SD_16TO23BITS
) >> 8) | ((tempscr
[1] & SD_24TO31BITS
) >> 24);
1518 /** -----------------------------------------------------------------------------------------------------------------*/
1520 * @brief Checks if the SD card is in programming state.
1521 * @param pStatus: pointer to the variable that will contain the SD card state
1522 * @retval SD Card error state
1525 static SD_Error_t SD_IsCardProgramming(uint8_t *pStatus)
1527 uint32_t Response_R1;
1529 SD_TransmitCommand((SD_CMD_SEND_STATUS | SDMMC_CMD_RESPONSE_SHORT), SD_CardRCA, 0);
1530 if((SDMMC1->STA & SDMMC_STA_CTIMEOUT) != 0) return SD_CMD_RSP_TIMEOUT;
1531 else if((SDMMC1->STA & SDMMC_STA_CCRCFAIL) != 0) return SD_CMD_CRC_FAIL;
1532 if((uint32_t)SDMMC1->RESPCMD != SD_CMD_SEND_STATUS) return SD_ILLEGAL_CMD; // Check if is of desired command
1533 Response_R1 = SDMMC1->RESP1; // We have received response, retrieve it for analysis
1534 *pStatus = (uint8_t)((Response_R1 >> 9) & 0x0000000F); // Find out card status
1536 return CheckOCR_Response(Response_R1);
1540 /** -----------------------------------------------------------------------------------------------------------------*/
1542 * @brief Initialize the SDMMC1 module, DMA, and IO
1544 bool SD_Initialize_LL(DMA_Stream_TypeDef
*dma
)
1546 const dmaIdentifier_e dmaIdentifier
= dmaGetIdentifier((dmaResource_t
*)dmaStream
);
1547 if (!(dma
== DMA2_Stream3
|| dma
== DMA2_Stream6
) || !dmaAllocate(dmaIdentifier
, OWNER_SDCARD
, 0)) {
1551 // Reset SDMMC1 Module
1552 RCC
->APB2RSTR
|= RCC_APB2RSTR_SDMMC1RST
;
1554 RCC
->APB2RSTR
&= ~RCC_APB2RSTR_SDMMC1RST
;
1557 // Enable SDMMC1 clock
1558 RCC
->APB2ENR
|= RCC_APB2ENR_SDMMC1EN
;
1560 // Enable DMA2 clocks
1561 RCC
->AHB1ENR
|= RCC_AHB1ENR_DMA2EN
;
1564 RCC
->AHB1ENR
|= RCC_AHB1ENR_GPIOCEN
| RCC_AHB1ENR_GPIODEN
;
1566 uint8_t is4BitWidth
= sdioConfig()->use4BitWidth
;
1568 const IO_t d0
= IOGetByTag(IO_TAG(PC8
));
1569 const IO_t d1
= IOGetByTag(IO_TAG(PC9
));
1570 const IO_t d2
= IOGetByTag(IO_TAG(PC10
));
1571 const IO_t d3
= IOGetByTag(IO_TAG(PC11
));
1572 const IO_t clk
= IOGetByTag(IO_TAG(PC12
));
1573 const IO_t cmd
= IOGetByTag(IO_TAG(PD2
));
1575 IOInit(d0
, OWNER_SDCARD
, 0);
1577 IOInit(d1
, OWNER_SDCARD
, 0);
1578 IOInit(d2
, OWNER_SDCARD
, 0);
1579 IOInit(d3
, OWNER_SDCARD
, 0);
1581 IOInit(clk
, OWNER_SDCARD
, 0);
1582 IOInit(cmd
, OWNER_SDCARD
, 0);
1584 #define SDMMC_DATA IO_CONFIG(GPIO_MODE_AF_PP, GPIO_SPEED_FREQ_VERY_HIGH, GPIO_NOPULL)
1585 #define SDMMC_CMD IO_CONFIG(GPIO_MODE_AF_PP, GPIO_SPEED_FREQ_VERY_HIGH, GPIO_NOPULL)
1586 #define SDMMC_CLK IO_CONFIG(GPIO_MODE_AF_PP, GPIO_SPEED_FREQ_VERY_HIGH, GPIO_NOPULL)
1588 IOConfigGPIOAF(d0
, SDMMC_DATA
, GPIO_AF12_SDMMC1
);
1590 IOConfigGPIOAF(d1
, SDMMC_DATA
, GPIO_AF12_SDMMC1
);
1591 IOConfigGPIOAF(d2
, SDMMC_DATA
, GPIO_AF12_SDMMC1
);
1592 IOConfigGPIOAF(d3
, SDMMC_DATA
, GPIO_AF12_SDMMC1
);
1594 IOConfigGPIOAF(clk
, SDMMC_CLK
, GPIO_AF12_SDMMC1
);
1595 IOConfigGPIOAF(cmd
, SDMMC_CMD
, GPIO_AF12_SDMMC1
);
1597 uint32_t PriorityGroup
= NVIC_GetPriorityGrouping();
1599 // NVIC configuration for SDIO interrupts
1600 NVIC_SetPriority(SDMMC1_IRQn
, NVIC_EncodePriority(PriorityGroup
, 1, 0));
1601 NVIC_EnableIRQ(SDMMC1_IRQn
);
1604 RCC
->AHB1ENR
|= RCC_AHB1ENR_DMA2EN
;
1607 dmaStream
->CR
= 0; // Reset DMA Stream control register
1608 dmaStream
->PAR
= (uint32_t)&SDMMC1
->FIFO
;
1609 if (dmaStream
== DMA2_Stream3
) {
1610 DMA2
->LIFCR
= IFCR_CLEAR_MASK_STREAM3
; // Clear all interrupt flags
1612 DMA2
->HIFCR
= IFCR_CLEAR_MASK_STREAM6
; // Clear all interrupt flags
1614 dmaStream
->CR
= (DMA_CHANNEL_4
| DMA_SxCR_PFCTRL
| // Prepare the DMA Stream configuration
1615 DMA_MINC_ENABLE
| DMA_PDATAALIGN_WORD
| // And write to DMA Stream CR register
1616 DMA_MDATAALIGN_WORD
| DMA_PRIORITY_VERY_HIGH
|
1617 DMA_MBURST_INC4
| DMA_PBURST_INC4
|
1618 DMA_MEMORY_TO_PERIPH
);
1619 dmaStream
->FCR
= (DMA_SxFCR_DMDIS
| DMA_SxFCR_FTH
); // Configuration FIFO control register
1620 dmaEnable(dmaIdentifier
);
1621 if (dmaStream
== DMA2_Stream3
) {
1622 dmaSetHandler(dmaIdentifier
, SDMMC_DMA_ST3_IRQHandler
, 1, 0);
1624 dmaSetHandler(dmaIdentifier
, SDMMC_DMA_ST6_IRQHandler
, 1, 0);
1631 /** -----------------------------------------------------------------------------------------------------------------*/
1632 bool SD_GetState(void)
1634 // Check SDCARD status
1635 if(SD_GetStatus() == SD_OK
) return true;
1640 /** -----------------------------------------------------------------------------------------------------------------*/
1641 static SD_Error_t
SD_DoInit(void)
1643 SD_Error_t errorState
;
1645 __HAL_RCC_SDMMC1_CLK_ENABLE();
1647 // Initialize SDMMC1 peripheral interface with default configuration for SD card initialization.
1648 MODIFY_REG(SDMMC1
->CLKCR
, CLKCR_CLEAR_MASK
, (uint32_t) SDMMC_INIT_CLK_DIV
);
1650 // Identify card operating voltage.
1651 errorState
= SD_PowerON();
1652 if (errorState
!= SD_OK
) {
1656 // Initialize the present card and put them in idle state.
1657 errorState
= SD_InitializeCard();
1658 if (errorState
!= SD_OK
) {
1662 // Read CSD/CID MSD registers.
1663 errorState
= SD_GetCardInfo();
1664 if (errorState
!= SD_OK
) {
1668 // Select the Card - Send CMD7 SDMMC_SEL_DESEL_CARD.
1669 errorState
= SD_TransmitCommand((SD_CMD_SEL_DESEL_CARD
| SD_CMD_RESPONSE_SHORT
), SD_CardRCA
, 1);
1670 // Configure SDMMC1 peripheral interface.
1671 MODIFY_REG(SDMMC1
->CLKCR
, CLKCR_CLEAR_MASK
, (uint32_t) SDMMC_CLK_DIV
);
1673 // Configure SD Bus width.
1674 if (errorState
== SD_OK
)
1676 // Enable wide operation.
1677 if (sdioConfig()->use4BitWidth
) {
1678 errorState
= SD_WideBusOperationConfig(SD_BUS_WIDE_4B
);
1680 errorState
= SD_WideBusOperationConfig(SD_BUS_WIDE_1B
);
1687 SD_Error_t
SD_Init(void)
1689 static bool sdInitAttempted
= false;
1690 static SD_Error_t result
= SD_ERROR
;
1692 if (sdInitAttempted
) {
1696 sdInitAttempted
= true;
1698 result
= SD_DoInit();
1704 /** -----------------------------------------------------------------------------------------------------------------*/
1706 * @brief This function handles SD card interrupt request.
1708 void SDMMC1_IRQHandler(void) {
1709 // Check for SDMMC1 interrupt flags
1710 if ((SDMMC1
->STA
& SDMMC_STA_DATAEND
) != 0) {
1711 SDMMC1
->ICR
= SDMMC_ICR_DATAENDC
;
1712 SDMMC1
->ICR
= SDMMC_ICR_STATIC_FLAGS
;
1713 SDMMC1
->MASK
&= ~(SDMMC_MASK_DATAENDIE
| SDMMC_MASK_DCRCFAILIE
| SDMMC_MASK_DTIMEOUTIE
| \
1714 SDMMC_MASK_TXUNDERRIE
| SDMMC_MASK_RXOVERRIE
| SDMMC_MASK_TXFIFOHEIE
| SDMMC_MASK_RXFIFOHFIE
);
1716 /* Currently doesn't implement multiple block write handling */
1717 if ((SD_Handle
.Operation
& 0x02) == (SDMMC_DIR_TX
<< 1)) {
1718 /* Disable the stream */
1719 dmaStream
->CR
&= ~DMA_SxCR_EN
;
1720 SDMMC1
->DCTRL
&= ~(SDMMC_DCTRL_DMAEN
);
1721 /* Transfer is complete */
1722 SD_Handle
.TXCplt
= 0;
1723 if ((SD_Handle
.Operation
& 0x01) == SD_MULTIPLE_BLOCK
) {
1724 /* Send stop command in multiblock write */
1725 SD_TransmitCommand((SD_CMD_STOP_TRANSMISSION
| SD_CMD_RESPONSE_SHORT
), 0, 1);
1728 SD_Handle
.TransferComplete
= 1;
1729 SD_Handle
.TransferError
= SD_OK
; // No transfer error
1731 else if ((SDMMC1
->STA
& SDMMC_STA_DCRCFAIL
) != 0)
1732 SD_Handle
.TransferError
= SD_DATA_CRC_FAIL
;
1733 else if ((SDMMC1
->STA
& SDMMC_STA_DTIMEOUT
) != 0)
1734 SD_Handle
.TransferError
= SD_DATA_TIMEOUT
;
1735 else if ((SDMMC1
->STA
& SDMMC_STA_RXOVERR
) != 0)
1736 SD_Handle
.TransferError
= SD_RX_OVERRUN
;
1737 else if ((SDMMC1
->STA
& SDMMC_STA_TXUNDERR
) != 0)
1738 SD_Handle
.TransferError
= SD_TX_UNDERRUN
;
1740 SDMMC1
->ICR
= SDMMC_ICR_STATIC_FLAGS
;
1742 // Disable all SDMMC1 peripheral interrupt sources
1743 SDMMC1
->MASK
&= ~(SDMMC_MASK_DCRCFAILIE
| SDMMC_MASK_DTIMEOUTIE
1744 | SDMMC_MASK_DATAENDIE
|
1745 SDMMC_MASK_TXFIFOHEIE
| SDMMC_MASK_RXFIFOHFIE
| SDMMC_MASK_TXUNDERRIE
|
1746 SDMMC_MASK_RXOVERRIE
);
1749 /** -----------------------------------------------------------------------------------------------------------------*/
1751 * @brief This function handles DMA2 Stream 3 interrupt request.
1753 void SDMMC_DMA_ST3_IRQHandler(dmaChannelDescriptor_t
*dma
)
1756 // Transfer Error Interrupt management
1757 if((DMA2
->LISR
& DMA_LISR_TEIF3
) != 0)
1759 if((DMA2_Stream3
->CR
& DMA_SxCR_TEIE
) != 0)
1761 DMA2_Stream3
->CR
&= ~DMA_SxCR_TEIE
; // Disable the transfer error interrupt
1762 DMA2
->LIFCR
= DMA_LIFCR_CTEIF3
; // Clear the transfer error flag
1766 // FIFO Error Interrupt management
1767 if((DMA2
->LISR
& DMA_LISR_FEIF3
) != 0)
1769 if((DMA2_Stream3
->FCR
& DMA_SxFCR_FEIE
) != 0)
1771 DMA2_Stream3
->FCR
&= ~DMA_SxFCR_FEIE
; // Disable the FIFO Error interrupt
1772 DMA2
->LIFCR
= DMA_LIFCR_CFEIF3
; // Clear the FIFO error flag
1776 // Direct Mode Error Interrupt management
1777 if((DMA2
->LISR
& DMA_LISR_DMEIF3
) != 0)
1779 if((DMA2_Stream3
->CR
& DMA_SxCR_DMEIE
) != 0)
1781 DMA2_Stream3
->CR
&= ~DMA_SxCR_DMEIE
; // Disable the direct mode Error interrupt
1782 DMA2
->LIFCR
= DMA_LIFCR_CDMEIF3
; // Clear the FIFO error flag
1786 // Half Transfer Complete Interrupt management
1787 if((DMA2
->LISR
& DMA_LISR_HTIF3
) != 0)
1789 if((DMA2_Stream3
->CR
& DMA_SxCR_HTIE
) != 0)
1791 if(((DMA2_Stream3
->CR
) & (uint32_t)(DMA_SxCR_DBM
)) != 0) // Multi_Buffering mode enabled
1793 DMA2
->LIFCR
= DMA_LIFCR_CHTIF3
; // Clear the half transfer complete flag
1797 if((DMA2_Stream3
->CR
& DMA_SxCR_CIRC
) == 0) // Disable the half transfer interrupt if the DMA mode is not CIRCULAR
1799 DMA2_Stream3
->CR
&= ~DMA_SxCR_HTIE
; // Disable the half transfer interrupt
1802 DMA2
->LIFCR
= DMA_LIFCR_CHTIF3
; // Clear the half transfer complete flag
1807 // Transfer Complete Interrupt management
1808 if((DMA2
->LISR
& DMA_LISR_TCIF3
) != 0)
1810 if((DMA2_Stream3
->CR
& DMA_SxCR_TCIE
) != 0)
1812 if((DMA2_Stream3
->CR
& (uint32_t)(DMA_SxCR_DBM
)) != 0)
1814 DMA2
->LIFCR
= DMA_LIFCR_CTCIF3
; // Clear the transfer complete flag
1816 else //Disable the transfer complete interrupt if the DMA mode is not CIRCULAR
1818 if((DMA2_Stream3
->CR
& DMA_SxCR_CIRC
) == 0)
1820 DMA2_Stream3
->CR
&= ~DMA_SxCR_TCIE
; // Disable the transfer complete interrupt
1823 DMA2
->LIFCR
= DMA_LIFCR_CTCIF3
; // Clear the transfer complete flag
1824 SD_DMA_Complete(DMA2_Stream3
);
1831 /** -----------------------------------------------------------------------------------------------------------------*/
1833 * @brief This function handles DMA2 Stream 6 interrupt request.
1835 void SDMMC_DMA_ST6_IRQHandler(dmaChannelDescriptor_t
*dma
)
1838 // Transfer Error Interrupt management
1839 if((DMA2
->HISR
& DMA_HISR_TEIF6
) != 0)
1841 if((DMA2_Stream6
->CR
& DMA_SxCR_TEIE
) != 0)
1843 DMA2_Stream6
->CR
&= ~DMA_SxCR_TEIE
; // Disable the transfer error interrupt
1844 DMA2
->HIFCR
= DMA_HIFCR_CTEIF6
; // Clear the transfer error flag
1848 // FIFO Error Interrupt management
1849 if((DMA2
->HISR
& DMA_HISR_FEIF6
) != 0)
1851 if((DMA2_Stream6
->FCR
& DMA_SxFCR_FEIE
) != 0)
1853 DMA2_Stream6
->FCR
&= ~DMA_SxFCR_FEIE
; // Disable the FIFO Error interrupt
1854 DMA2
->HIFCR
= DMA_HIFCR_CFEIF6
; // Clear the FIFO error flag
1858 // Direct Mode Error Interrupt management
1859 if((DMA2
->HISR
& DMA_HISR_DMEIF6
) != 0)
1861 if((DMA2_Stream6
->CR
& DMA_SxCR_DMEIE
) != 0)
1863 DMA2_Stream6
->CR
&= ~DMA_SxCR_DMEIE
; // Disable the direct mode Error interrupt
1864 DMA2
->HIFCR
= DMA_HIFCR_CDMEIF6
; // Clear the FIFO error flag
1868 // Half Transfer Complete Interrupt management
1869 if((DMA2
->HISR
& DMA_HISR_HTIF6
) != 0)
1871 if((DMA2_Stream6
->CR
& DMA_SxCR_HTIE
) != 0)
1873 if(((DMA2_Stream6
->CR
) & (uint32_t)(DMA_SxCR_DBM
)) != 0) // Multi_Buffering mode enabled
1875 DMA2
->HIFCR
= DMA_HIFCR_CHTIF6
; // Clear the half transfer complete flag
1879 if((DMA2_Stream6
->CR
& DMA_SxCR_CIRC
) == 0) // Disable the half transfer interrupt if the DMA mode is not CIRCULAR
1881 DMA2_Stream6
->CR
&= ~DMA_SxCR_HTIE
; // Disable the half transfer interrupt
1884 DMA2
->HIFCR
= DMA_HIFCR_CHTIF6
; // Clear the half transfer complete flag
1889 // Transfer Complete Interrupt management
1890 if((DMA2
->HISR
& DMA_HISR_TCIF6
) != 0)
1892 if((DMA2_Stream6
->CR
& DMA_SxCR_TCIE
) != 0)
1894 if((DMA2_Stream6
->CR
& (uint32_t)(DMA_SxCR_DBM
)) != 0)
1896 DMA2
->HIFCR
= DMA_HIFCR_CTCIF6
; // Clear the transfer complete flag
1898 else //Disable the transfer complete interrupt if the DMA mode is not CIRCULAR
1900 if((DMA2_Stream6
->CR
& DMA_SxCR_CIRC
) == 0)
1902 DMA2_Stream6
->CR
&= ~DMA_SxCR_TCIE
; // Disable the transfer complete interrupt
1905 DMA2
->HIFCR
= DMA_HIFCR_CTCIF6
; // Clear the transfer complete flag
1906 SD_DMA_Complete(DMA2_Stream6
);
1912 /* ------------------------------------------------------------------------------------------------------------------*/