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 F4 and BF source: Chris Hockuba (https://github.com/conkerkh)
25 * Note: On F4 due to DMA issues it is recommended that motor timers don't run on DMA2.
26 * Therefore avoid using TIM1/TIM8, use TIM2/TIM3/TIM4/TIM5/TIM6/TIM7
29 /* Include(s) -------------------------------------------------------------------------------------------------------*/
36 #ifdef USE_SDCARD_SDIO
38 #include "sdmmc_sdio.h"
39 #include "stm32f4xx_gpio.h"
43 #include "drivers/io.h"
44 #include "drivers/io_impl.h"
45 #include "drivers/nvic.h"
46 #include "drivers/time.h"
47 #include "drivers/rcc.h"
48 #include "drivers/dma.h"
49 #include "drivers/light_led.h"
51 #include "build/debug.h"
54 /* Define(s) --------------------------------------------------------------------------------------------------------*/
56 #define DMA_CHANNEL_4 ((uint32_t)0x08000000)
57 #define DMA_MEMORY_TO_PERIPH ((uint32_t)DMA_SxCR_DIR_0)
58 #define DMA_PERIPH_TO_MEMORY ((uint32_t)0x00)
59 #define DMA_MINC_ENABLE ((uint32_t)DMA_SxCR_MINC)
60 #define DMA_MDATAALIGN_WORD ((uint32_t)DMA_SxCR_MSIZE_1)
61 #define DMA_PDATAALIGN_WORD ((uint32_t)DMA_SxCR_PSIZE_1)
62 #define DMA_PRIORITY_MEDIUM ((uint32_t)DMA_Priority_Medium)
63 #define DMA_PRIORITY_HIGH ((uint32_t)DMA_Priority_High)
64 #define DMA_PRIORITY_VERY_HIGH ((uint32_t)DMA_Priority_VeryHigh)
65 #define DMA_MBURST_INC4 ((uint32_t)DMA_SxCR_MBURST_0)
66 #define DMA_PBURST_INC4 ((uint32_t)DMA_SxCR_PBURST_0)
68 #define BLOCK_SIZE ((uint32_t)(512))
70 #define IFCR_CLEAR_MASK_STREAM3 (DMA_LIFCR_CTCIF3 | DMA_LIFCR_CHTIF3 | DMA_LIFCR_CTEIF3 | DMA_LIFCR_CDMEIF3 | DMA_LIFCR_CFEIF3)
71 #define IFCR_CLEAR_MASK_STREAM6 (DMA_HIFCR_CTCIF6 | DMA_HIFCR_CHTIF6 | DMA_HIFCR_CTEIF6 | DMA_HIFCR_CDMEIF6 | DMA_HIFCR_CFEIF6)
73 #define SDIO_ICR_STATIC_FLAGS ((uint32_t)(SDIO_ICR_CCRCFAILC | SDIO_ICR_DCRCFAILC | SDIO_ICR_CTIMEOUTC |\
74 SDIO_ICR_DTIMEOUTC | SDIO_ICR_TXUNDERRC | SDIO_ICR_RXOVERRC |\
75 SDIO_ICR_CMDRENDC | SDIO_ICR_CMDSENTC | SDIO_ICR_DATAENDC |\
78 #define SD_SOFTWARE_COMMAND_TIMEOUT ((uint32_t)0x00020000)
80 #define SD_OCR_ADDR_OUT_OF_RANGE ((uint32_t)0x80000000)
81 #define SD_OCR_ADDR_MISALIGNED ((uint32_t)0x40000000)
82 #define SD_OCR_BLOCK_LEN_ERR ((uint32_t)0x20000000)
83 #define SD_OCR_ERASE_SEQ_ERR ((uint32_t)0x10000000)
84 #define SD_OCR_BAD_ERASE_PARAM ((uint32_t)0x08000000)
85 #define SD_OCR_WRITE_PROT_VIOLATION ((uint32_t)0x04000000)
86 #define SD_OCR_LOCK_UNLOCK_FAILED ((uint32_t)0x01000000)
87 #define SD_OCR_COM_CRC_FAILED ((uint32_t)0x00800000)
88 #define SD_OCR_ILLEGAL_CMD ((uint32_t)0x00400000)
89 #define SD_OCR_CARD_ECC_FAILED ((uint32_t)0x00200000)
90 #define SD_OCR_CC_ERROR ((uint32_t)0x00100000)
91 #define SD_OCR_GENERAL_UNKNOWN_ERROR ((uint32_t)0x00080000)
92 #define SD_OCR_STREAM_READ_UNDERRUN ((uint32_t)0x00040000)
93 #define SD_OCR_STREAM_WRITE_OVERRUN ((uint32_t)0x00020000)
94 #define SD_OCR_CID_CSD_OVERWRITE ((uint32_t)0x00010000)
95 #define SD_OCR_WP_ERASE_SKIP ((uint32_t)0x00008000)
96 #define SD_OCR_CARD_ECC_DISABLED ((uint32_t)0x00004000)
97 #define SD_OCR_ERASE_RESET ((uint32_t)0x00002000)
98 #define SD_OCR_AKE_SEQ_ERROR ((uint32_t)0x00000008)
99 #define SD_OCR_ERRORBITS ((uint32_t)0xFDFFE008)
101 #define SD_R6_GENERAL_UNKNOWN_ERROR ((uint32_t)0x00002000)
102 #define SD_R6_ILLEGAL_CMD ((uint32_t)0x00004000)
103 #define SD_R6_COM_CRC_FAILED ((uint32_t)0x00008000)
105 #define SD_VOLTAGE_WINDOW_SD ((uint32_t)0x80100000)
106 #define SD_RESP_HIGH_CAPACITY ((uint32_t)0x40000000)
107 #define SD_RESP_STD_CAPACITY ((uint32_t)0x00000000)
108 #define SD_CHECK_PATTERN ((uint32_t)0x000001AA)
110 #define SD_MAX_VOLT_TRIAL ((uint32_t)0x0000FFFF)
111 #define SD_ALLZERO ((uint32_t)0x00000000)
113 #define SD_WIDE_BUS_SUPPORT ((uint32_t)0x00040000)
114 #define SD_SINGLE_BUS_SUPPORT ((uint32_t)0x00010000)
115 #define SD_CARD_LOCKED ((uint32_t)0x02000000)
117 #define SD_0TO7BITS ((uint32_t)0x000000FF)
118 #define SD_8TO15BITS ((uint32_t)0x0000FF00)
119 #define SD_16TO23BITS ((uint32_t)0x00FF0000)
120 #define SD_24TO31BITS ((uint32_t)0xFF000000)
121 #define SD_MAX_DATA_LENGTH ((uint32_t)0x01FFFFFF)
123 #define SD_CCCC_ERASE ((uint32_t)0x00000020)
125 #define SD_SDIO_SEND_IF_COND ((uint32_t)SD_CMD_HS_SEND_EXT_CSD)
129 #define SD_BUS_WIDE_1B ((uint32_t)0x00000000)
130 #define SD_BUS_WIDE_4B SDIO_CLKCR_WIDBUS_0
131 #define SD_BUS_WIDE_8B SDIO_CLKCR_WIDBUS_1
133 #define SD_CMD_RESPONSE_SHORT SDIO_CMD_WAITRESP_0
134 #define SD_CMD_RESPONSE_LONG SDIO_CMD_WAITRESP
136 #define SD_DATABLOCK_SIZE_8B (SDIO_DCTRL_DBLOCKSIZE_0|SDIO_DCTRL_DBLOCKSIZE_1)
137 #define SD_DATABLOCK_SIZE_64B (SDIO_DCTRL_DBLOCKSIZE_1|SDIO_DCTRL_DBLOCKSIZE_2)
138 #define SD_DATABLOCK_SIZE_512B (SDIO_DCTRL_DBLOCKSIZE_0|SDIO_DCTRL_DBLOCKSIZE_3)
140 #define CLKCR_CLEAR_MASK ((uint32_t)(SDIO_CLKCR_CLKDIV | SDIO_CLKCR_PWRSAV |\
141 SDIO_CLKCR_BYPASS | SDIO_CLKCR_WIDBUS |\
142 SDIO_CLKCR_NEGEDGE | SDIO_CLKCR_HWFC_EN))
144 #define DCTRL_CLEAR_MASK ((uint32_t)(SDIO_DCTRL_DTEN | SDIO_DCTRL_DTDIR |\
145 SDIO_DCTRL_DTMODE | SDIO_DCTRL_DBLOCKSIZE))
147 #define CMD_CLEAR_MASK ((uint32_t)(SDIO_CMD_CMDINDEX | SDIO_CMD_WAITRESP |\
148 SDIO_CMD_WAITINT | SDIO_CMD_WAITPEND |\
149 SDIO_CMD_CPSMEN | SDIO_CMD_SDIOSUSPEND))
151 #define SDIO_INIT_CLK_DIV ((uint8_t)0x76)
152 #define SDIO_CLK_DIV ((uint8_t)0x00)
155 #define SD_CMD_GO_IDLE_STATE ((uint8_t)0) // Resets the SD memory card.
156 #define SD_CMD_SEND_OP_COND ((uint8_t)1) // Sends host capacity support information and activates the card's initialization process.
157 #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.
158 #define SD_CMD_SET_REL_ADDR ((uint8_t)3) // Asks the card to publish a new relative address (RCA).
159 #define SD_CMD_HS_SWITCH ((uint8_t)6) // Checks switchable function (mode 0) and switch card function (mode 1).
160 #define SD_CMD_SEL_DESEL_CARD ((uint8_t)7) // Selects the card by its own relative address and gets deselected by any other address
161 #define SD_CMD_HS_SEND_EXT_CSD ((uint8_t)8) // Sends SD Memory Card interface condition, which includes host supply voltage information
162 // and asks the card whether card supports voltage.
163 #define SD_CMD_SEND_CSD ((uint8_t)9) // Addressed card sends its card specific data (CSD) on the CMD line.
164 #define SD_CMD_SEND_CID ((uint8_t)10) // Addressed card sends its card identification (CID) on the CMD line.
165 #define SD_CMD_STOP_TRANSMISSION ((uint8_t)12) // Forces the card to stop transmission.
166 #define SD_CMD_SEND_STATUS ((uint8_t)13) // Addressed card sends its status register.
167 #define SD_CMD_SET_BLOCKLEN ((uint8_t)16) // Sets the block length (in bytes for SDSC) for all following block commands
168 // (read, write, lock). Default block length is fixed to 512 Bytes. Not effective
169 // for SDHS and SDXC.
170 #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
171 // fixed 512 bytes in case of SDHC and SDXC.
172 #define SD_CMD_READ_MULT_BLOCK ((uint8_t)18) // Continuously transfers data blocks from card to host until interrupted by
173 // STOP_TRANSMISSION command.
174 #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
175 // fixed 512 bytes in case of SDHC and SDXC.
176 #define SD_CMD_WRITE_MULT_BLOCK ((uint8_t)25) // Continuously writes blocks of data until a STOP_TRANSMISSION follows.
177 #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).
178 #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.
179 // system set by switch function command (CMD6).
180 #define SD_CMD_ERASE ((uint8_t)38) // Reserved for SD security applications.
181 #define SD_CMD_FAST_IO ((uint8_t)39) // SD card doesn't support it (Reserved).
182 #define SD_CMD_APP_CMD ((uint8_t)55) // Indicates to the card that the next command is an application specific command rather
183 // than a standard command.
185 /* Following commands are SD Card Specific commands.
186 SDIO_APP_CMD should be sent before sending these commands. */
187 #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
188 // widths are given in SCR register.
189 #define SD_CMD_SD_APP_STATUS ((uint8_t)13) // (ACMD13) Sends the SD status.
190 #define SD_CMD_SD_APP_OP_COND ((uint8_t)41) // (ACMD41) Sends host capacity support information (HCS) and asks the accessed card to
191 // send its operating condition register (OCR) content in the response on the CMD line.
192 #define SD_CMD_SD_APP_SEND_SCR ((uint8_t)51) // Reads the SD Configuration Register (SCR).
194 #define SDIO_DIR_TX 1
195 #define SDIO_DIR_RX 0
197 #define SDIO_DMA_ST3 1
200 /* Typedef(s) -------------------------------------------------------------------------------------------------------*/
204 SD_SINGLE_BLOCK
= 0, // Single block operation
205 SD_MULTIPLE_BLOCK
= 1, // Multiple blocks operation
211 uint32_t CSD
[4]; // SD card specific data table
212 uint32_t CID
[4]; // SD card identification number table
213 volatile uint32_t TransferComplete
; // SD transfer complete flag in non blocking mode
214 volatile uint32_t TransferError
; // SD transfer error flag in non blocking mode
215 volatile uint32_t RXCplt
; // SD RX Complete is equal 0 when no transfer
216 volatile uint32_t TXCplt
; // SD TX Complete is equal 0 when no transfer
217 volatile uint32_t Operation
; // SD transfer operation (read/write)
222 SD_CARD_READY
= ((uint32_t)0x00000001), // Card state is ready
223 SD_CARD_IDENTIFICATION
= ((uint32_t)0x00000002), // Card is in identification state
224 SD_CARD_STANDBY
= ((uint32_t)0x00000003), // Card is in standby state
225 SD_CARD_TRANSFER
= ((uint32_t)0x00000004), // Card is in transfer state
226 SD_CARD_SENDING
= ((uint32_t)0x00000005), // Card is sending an operation
227 SD_CARD_RECEIVING
= ((uint32_t)0x00000006), // Card is receiving operation information
228 SD_CARD_PROGRAMMING
= ((uint32_t)0x00000007), // Card is in programming state
229 SD_CARD_DISCONNECTED
= ((uint32_t)0x00000008), // Card is disconnected
230 SD_CARD_ERROR
= ((uint32_t)0x000000FF) // Card is in error state
233 /* Variable(s) ------------------------------------------------------------------------------------------------------*/
235 static SD_Handle_t SD_Handle
;
236 SD_CardInfo_t SD_CardInfo
;
237 static uint32_t SD_Status
;
238 static uint32_t SD_CardRCA
;
239 SD_CardType_t SD_CardType
;
240 static volatile uint32_t TimeOut
;
241 DMA_Stream_TypeDef
*dmaStream
;
244 /* Private function(s) ----------------------------------------------------------------------------------------------*/
246 static void SD_DataTransferInit (uint32_t Size
, uint32_t DataBlockSize
, bool IsItReadFromCard
);
247 static SD_Error_t
SD_TransmitCommand (uint32_t Command
, uint32_t Argument
, int8_t ResponseType
);
248 static SD_Error_t
SD_CmdResponse (uint8_t SD_CMD
, int8_t ResponseType
);
249 static void SD_GetResponse (uint32_t* pResponse
);
250 static SD_Error_t
CheckOCR_Response (uint32_t Response_R1
);
251 static void SD_DMA_Complete (DMA_Stream_TypeDef
* pDMA_Stream
);
252 static SD_Error_t
SD_InitializeCard (void);
254 static SD_Error_t
SD_PowerON (void);
255 static SD_Error_t
SD_WideBusOperationConfig (uint32_t WideMode
);
256 static SD_Error_t
SD_FindSCR (uint32_t *pSCR
);
258 void SDIO_DMA_ST3_IRQHandler(dmaChannelDescriptor_t
*dma
);
259 void SDIO_DMA_ST6_IRQHandler(dmaChannelDescriptor_t
*dma
);
261 //static void SD_PowerOFF (void);
263 /** -----------------------------------------------------------------------------------------------------------------*/
266 * @brief Prepare the state machine for transfer
267 * @param SD_TransferType_e TransfertDir
268 * @param SD_CARD_BlockSize_e Size
270 static void SD_DataTransferInit(uint32_t Size
, uint32_t DataBlockSize
, bool IsItReadFromCard
)
274 SDIO
->DTIMER
= SD_DATATIMEOUT
; // Set the SDIO Data TimeOut value
275 SDIO
->DLEN
= Size
; // Set the SDIO DataLength value
276 Direction
= (IsItReadFromCard
== true) ? SDIO_DCTRL_DTDIR
: 0;
277 SDIO
->DCTRL
|= (uint32_t)(DataBlockSize
| Direction
| SDIO_DCTRL_DTEN
| 0x01);
282 /** -----------------------------------------------------------------------------------------------------------------*/
283 /** SD_TransmitCommand
285 * @brief Send the command to SDIO
286 * @param uint32_t Command
287 * @param uint32_t Argument Must provide the response size
288 * @param uint8_t ResponseType
289 * @retval SD Card error state
291 static SD_Error_t
SD_TransmitCommand(uint32_t Command
, uint32_t Argument
, int8_t ResponseType
)
293 SD_Error_t ErrorState
;
295 WRITE_REG(SDIO
->ICR
, SDIO_ICR_STATIC_FLAGS
); // Clear the Command Flags
296 WRITE_REG(SDIO
->ARG
, (uint32_t)Argument
); // Set the SDIO Argument value
297 WRITE_REG(SDIO
->CMD
, (uint32_t)(Command
| SDIO_CMD_CPSMEN
)); // Set SDIO command parameters
298 if((Argument
== 0) && (ResponseType
== 0)) ResponseType
= -1; // Go idle command
299 ErrorState
= SD_CmdResponse(Command
& SDIO_CMD_CMDINDEX
, ResponseType
);
300 WRITE_REG(SDIO
->ICR
, SDIO_ICR_STATIC_FLAGS
); // Clear the Command Flags
306 /** -----------------------------------------------------------------------------------------------------------------*/
308 * @brief Checks for error conditions for any response.
309 * - R2 (CID or CSD) response.
310 * - R3 (OCR) response.
312 * @param SD_CMD: The sent command Index
313 * @retval SD Card error state
315 static SD_Error_t
SD_CmdResponse(uint8_t SD_CMD
, int8_t ResponseType
)
317 uint32_t Response_R1
;
321 if(ResponseType
== -1) {
322 Flag
= SDIO_STA_CMDSENT
;
324 Flag
= SDIO_STA_CCRCFAIL
| SDIO_STA_CMDREND
| SDIO_STA_CTIMEOUT
;
327 TimeOut
= SD_SOFTWARE_COMMAND_TIMEOUT
;
330 SD_Status
= SDIO
->STA
;
333 while(((SD_Status
& Flag
) == 0) && (TimeOut
> 0));
335 if(ResponseType
<= 0)
338 return SD_CMD_RSP_TIMEOUT
;
344 if((SDIO
->STA
& SDIO_STA_CTIMEOUT
) != 0) {
345 return SD_CMD_RSP_TIMEOUT
;
347 if(ResponseType
== 3)
350 return SD_CMD_RSP_TIMEOUT
; // Card is not V2.0 compliant or card does not support the set voltage range
352 return SD_OK
; // Card is SD V2.0 compliant
356 if((SDIO
->STA
& SDIO_STA_CCRCFAIL
) != 0) {
357 return SD_CMD_CRC_FAIL
;
359 if(ResponseType
== 2) {
362 if((uint8_t)SDIO
->RESPCMD
!= SD_CMD
) {
363 return SD_ILLEGAL_CMD
; // Check if response is of desired command
366 Response_R1
= SDIO
->RESP1
; // We have received response, retrieve it for analysis
368 if(ResponseType
== 1)
370 return CheckOCR_Response(Response_R1
);
372 else if(ResponseType
== 6)
374 if((Response_R1
& (SD_R6_GENERAL_UNKNOWN_ERROR
| SD_R6_ILLEGAL_CMD
| SD_R6_COM_CRC_FAILED
)) == SD_ALLZERO
)
376 SD_CardRCA
= Response_R1
;
378 if((Response_R1
& SD_R6_GENERAL_UNKNOWN_ERROR
) == SD_R6_GENERAL_UNKNOWN_ERROR
) {
379 return SD_GENERAL_UNKNOWN_ERROR
;
381 if((Response_R1
& SD_R6_ILLEGAL_CMD
) == SD_R6_ILLEGAL_CMD
) {
382 return SD_ILLEGAL_CMD
;
384 if((Response_R1
& SD_R6_COM_CRC_FAILED
) == SD_R6_COM_CRC_FAILED
) {
385 return SD_COM_CRC_FAILED
;
393 /** -----------------------------------------------------------------------------------------------------------------*/
395 * @brief Analyze the OCR response and return the appropriate error code
396 * @param Response_R1: OCR Response code
397 * @retval SD Card error state
399 static SD_Error_t
CheckOCR_Response(uint32_t Response_R1
)
401 if((Response_R1
& SD_OCR_ERRORBITS
) == SD_ALLZERO
) return SD_OK
;
402 if((Response_R1
& SD_OCR_ADDR_OUT_OF_RANGE
) == SD_OCR_ADDR_OUT_OF_RANGE
) return SD_ADDR_OUT_OF_RANGE
;
403 if((Response_R1
& SD_OCR_ADDR_MISALIGNED
) == SD_OCR_ADDR_MISALIGNED
) return SD_ADDR_MISALIGNED
;
404 if((Response_R1
& SD_OCR_BLOCK_LEN_ERR
) == SD_OCR_BLOCK_LEN_ERR
) return SD_BLOCK_LEN_ERR
;
405 if((Response_R1
& SD_OCR_ERASE_SEQ_ERR
) == SD_OCR_ERASE_SEQ_ERR
) return SD_ERASE_SEQ_ERR
;
406 if((Response_R1
& SD_OCR_BAD_ERASE_PARAM
) == SD_OCR_BAD_ERASE_PARAM
) return SD_BAD_ERASE_PARAM
;
407 if((Response_R1
& SD_OCR_WRITE_PROT_VIOLATION
) == SD_OCR_WRITE_PROT_VIOLATION
) return SD_WRITE_PROT_VIOLATION
;
408 if((Response_R1
& SD_OCR_LOCK_UNLOCK_FAILED
) == SD_OCR_LOCK_UNLOCK_FAILED
) return SD_LOCK_UNLOCK_FAILED
;
409 if((Response_R1
& SD_OCR_COM_CRC_FAILED
) == SD_OCR_COM_CRC_FAILED
) return SD_COM_CRC_FAILED
;
410 if((Response_R1
& SD_OCR_ILLEGAL_CMD
) == SD_OCR_ILLEGAL_CMD
) return SD_ILLEGAL_CMD
;
411 if((Response_R1
& SD_OCR_CARD_ECC_FAILED
) == SD_OCR_CARD_ECC_FAILED
) return SD_CARD_ECC_FAILED
;
412 if((Response_R1
& SD_OCR_CC_ERROR
) == SD_OCR_CC_ERROR
) return SD_CC_ERROR
;
413 if((Response_R1
& SD_OCR_GENERAL_UNKNOWN_ERROR
) == SD_OCR_GENERAL_UNKNOWN_ERROR
)return SD_GENERAL_UNKNOWN_ERROR
;
414 if((Response_R1
& SD_OCR_STREAM_READ_UNDERRUN
) == SD_OCR_STREAM_READ_UNDERRUN
) return SD_STREAM_READ_UNDERRUN
;
415 if((Response_R1
& SD_OCR_STREAM_WRITE_OVERRUN
) == SD_OCR_STREAM_WRITE_OVERRUN
) return SD_STREAM_WRITE_OVERRUN
;
416 if((Response_R1
& SD_OCR_CID_CSD_OVERWRITE
) == SD_OCR_CID_CSD_OVERWRITE
) return SD_CID_CSD_OVERWRITE
;
417 if((Response_R1
& SD_OCR_WP_ERASE_SKIP
) == SD_OCR_WP_ERASE_SKIP
) return SD_WP_ERASE_SKIP
;
418 if((Response_R1
& SD_OCR_CARD_ECC_DISABLED
) == SD_OCR_CARD_ECC_DISABLED
) return SD_CARD_ECC_DISABLED
;
419 if((Response_R1
& SD_OCR_ERASE_RESET
) == SD_OCR_ERASE_RESET
) return SD_ERASE_RESET
;
420 if((Response_R1
& SD_OCR_AKE_SEQ_ERROR
) == SD_OCR_AKE_SEQ_ERROR
) return SD_AKE_SEQ_ERROR
;
426 /** -----------------------------------------------------------------------------------------------------------------*/
429 * @brief Get response from SD device
430 * @param uint32_t* pResponse
432 static void SD_GetResponse(uint32_t* pResponse
)
434 pResponse
[0] = SDIO
->RESP1
;
435 pResponse
[1] = SDIO
->RESP2
;
436 pResponse
[2] = SDIO
->RESP3
;
437 pResponse
[3] = SDIO
->RESP4
;
441 /** -----------------------------------------------------------------------------------------------------------------*/
443 * @brief SD DMA transfer complete RX and TX callback.
444 * @param DMA_Stream_TypeDef* pDMA_Stream
446 static void SD_DMA_Complete(DMA_Stream_TypeDef
* pDMA_Stream
)
448 if (SD_Handle
.RXCplt
) {
449 if (SD_Handle
.Operation
== ((SDIO_DIR_RX
<< 1) | SD_MULTIPLE_BLOCK
)) {
450 /* Send stop command in multiblock write */
451 SD_TransmitCommand((SD_CMD_STOP_TRANSMISSION
| SD_CMD_RESPONSE_SHORT
), 0, 1);
454 /* Disable the DMA transfer for transmit request by setting the DMAEN bit
455 in the SD DCTRL register */
456 SDIO
->DCTRL
&= (uint32_t)~((uint32_t)SDIO_DCTRL_DMAEN
);
458 /* Clear all the static flags */
459 SDIO
->ICR
= SDIO_ICR_STATIC_FLAGS
;
462 SD_Handle
.RXCplt
= 0;
464 /* Disable the stream */
465 pDMA_Stream
->CR
&= ~DMA_SxCR_EN
;
467 /* Enable Dataend IE */
468 SDIO
->MASK
|= SDIO_MASK_DATAENDIE
;
473 /** -----------------------------------------------------------------------------------------------------------------*/
475 * @brief Initializes all cards or single card as the case may be Card(s) come
476 * into standby state.
477 * @retval SD Card error state
479 static SD_Error_t
SD_InitializeCard(void)
481 SD_Error_t ErrorState
= SD_OK
;
483 if((SDIO
->POWER
& SDIO_POWER_PWRCTRL
) != 0) // Power off
485 if(SD_CardType
!= SD_SECURE_DIGITAL_IO
)
487 // Send CMD2 ALL_SEND_CID
488 if((ErrorState
= SD_TransmitCommand((SD_CMD_ALL_SEND_CID
| SD_CMD_RESPONSE_LONG
), 0, 2)) != SD_OK
)
493 // Get Card identification number data
494 SD_GetResponse(SD_Handle
.CID
);
497 if((SD_CardType
== SD_STD_CAPACITY_V1_1
) || (SD_CardType
== SD_STD_CAPACITY_V2_0
) ||
498 (SD_CardType
== SD_SECURE_DIGITAL_IO_COMBO
) || (SD_CardType
== SD_HIGH_CAPACITY
))
500 // Send CMD3 SET_REL_ADDR with argument 0
501 // SD Card publishes its RCA.
502 if((ErrorState
= SD_TransmitCommand((SD_CMD_SET_REL_ADDR
| SD_CMD_RESPONSE_SHORT
), 0, 6)) != SD_OK
)
508 if(SD_CardType
!= SD_SECURE_DIGITAL_IO
)
510 // Send CMD9 SEND_CSD with argument as card's RCA
511 if((ErrorState
= SD_TransmitCommand((SD_CMD_SEND_CSD
| SD_CMD_RESPONSE_LONG
), SD_CardRCA
, 2)) == SD_OK
)
513 // Get Card Specific Data
514 SD_GetResponse(SD_Handle
.CSD
);
520 ErrorState
= SD_REQUEST_NOT_APPLICABLE
;
527 /** -----------------------------------------------------------------------------------------------------------------*/
529 * @brief Prepre the DMA transfer
530 * @param pDMA: DMA Stream to use for the DMA operation
531 * @param pBuffer: Pointer to the buffer that will contain the data to transmit
532 * @param BlockSize: The SD card Data block size
533 * @note BlockSize must be 512 bytes.
534 * @param NumberOfBlocks: Number of blocks to write
535 * @retval SD Card error state
537 static void SD_StartBlockTransfert(uint32_t* pBuffer
, uint32_t BlockSize
, uint32_t NumberOfBlocks
, uint8_t dir
)
539 DMA_Stream_TypeDef
*pDMA
= dmaStream
;
541 SDIO
->DCTRL
= 0; // Initialize data control register
542 SD_Handle
.TransferComplete
= 0; // Initialize handle flags
543 SD_Handle
.TransferError
= SD_OK
;
544 SD_Handle
.Operation
= (NumberOfBlocks
> 1) ? SD_MULTIPLE_BLOCK
: SD_SINGLE_BLOCK
; // Initialize SD Read operation
545 SD_Handle
.Operation
|= dir
<< 1;
547 if (dir
== SDIO_DIR_RX
) {
548 SDIO
->MASK
|= (SDIO_MASK_DCRCFAILIE
| SDIO_MASK_DTIMEOUTIE
| // Enable transfer interrupts
549 SDIO_MASK_DATAENDIE
| SDIO_MASK_RXOVERRIE
);
551 SDIO
->MASK
|= (SDIO_MASK_DCRCFAILIE
| SDIO_MASK_DTIMEOUTIE
| // Enable transfer interrupts
552 SDIO_MASK_TXUNDERRIE
);
554 if (dir
== SDIO_DIR_TX
) {
555 SDIO
->DCTRL
|= SDIO_DCTRL_DMAEN
; // Enable SDIO DMA transfer
557 pDMA
->CR
&= ~DMA_SxCR_EN
; // Disable the Peripheral
558 while (pDMA
->CR
& DMA_SxCR_EN
);
559 pDMA
->NDTR
= (uint32_t) (BlockSize
* NumberOfBlocks
) / 4; // Configure DMA Stream data length
560 pDMA
->M0AR
= (uint32_t) pBuffer
; // Configure DMA Stream memory address
561 if (dir
== SDIO_DIR_RX
) {
562 pDMA
->CR
&= ~(0x01U
<< 6U); // Sets peripheral to memory
564 pDMA
->CR
|= DMA_MEMORY_TO_PERIPH
; // Sets memory to peripheral
566 if (dmaStream
== DMA2_Stream3
) {
567 DMA2
->LIFCR
= DMA_LIFCR_CTEIF3
| DMA_LIFCR_CDMEIF3
|
568 DMA_LIFCR_CFEIF3
| DMA_LIFCR_CHTIF3
| DMA_LIFCR_CTCIF3
; // Clear the transfer error flag
570 DMA2
->HIFCR
= DMA_HIFCR_CTEIF6
| DMA_HIFCR_CDMEIF6
|
571 DMA_HIFCR_CFEIF6
| DMA_HIFCR_CHTIF6
| DMA_HIFCR_CTCIF6
; // Clear the transfer error flag
573 pDMA
->CR
|= DMA_SxCR_TCIE
| DMA_SxCR_HTIE
| DMA_SxCR_TEIE
| DMA_SxCR_DMEIE
; // Enable all interrupts
574 pDMA
->FCR
|= DMA_SxFCR_FEIE
;
575 pDMA
->CR
|= DMA_SxCR_EN
; // Enable the Peripheral
576 if (dir
== SDIO_DIR_RX
) {
577 SDIO
->DCTRL
|= SDIO_DCTRL_DMAEN
; // Enable SDIO DMA transfer
582 /** -----------------------------------------------------------------------------------------------------------------*/
584 * @brief Reads block(s) from a specified address in a card. The Data transfer
585 * is managed by DMA mode.
586 * @note This API should be followed by the function SD_CheckOperation()
587 * to check the completion of the read process
588 * @param pReadBuffer: Pointer to the buffer that will contain the received data
589 * @param ReadAddr: Address from where data is to be read
590 * @param BlockSize: SD card Data block size
591 * @note BlockSize must be 512 bytes.
592 * @param NumberOfBlocks: Number of blocks to read.
593 * @retval SD Card error state
595 SD_Error_t
SD_ReadBlocks_DMA(uint64_t ReadAddress
, uint32_t *buffer
, uint32_t BlockSize
, uint32_t NumberOfBlocks
)
597 SD_Error_t ErrorState
;
599 SD_Handle
.RXCplt
= 1;
601 //printf("Reading at %ld into %p %ld blocks\n", (uint32_t)ReadAddress, (void*)buffer, NumberOfBlocks);
603 if(SD_CardType
!= SD_HIGH_CAPACITY
)
608 SD_StartBlockTransfert(buffer
, BlockSize
, NumberOfBlocks
, SDIO_DIR_RX
);
610 // Configure the SD DPSM (Data Path State Machine)
611 SD_DataTransferInit(BlockSize
* NumberOfBlocks
, SD_DATABLOCK_SIZE_512B
, true);
613 // Set Block Size for Card
614 ErrorState
= SD_TransmitCommand((SD_CMD_SET_BLOCKLEN
| SD_CMD_RESPONSE_SHORT
), BlockSize
, 1);
616 // Send CMD18 READ_MULT_BLOCK with argument data address
617 // or send CMD17 READ_SINGLE_BLOCK depending on number of block
618 uint8_t retries
= 10;
619 CmdIndex
= (NumberOfBlocks
> 1) ? SD_CMD_READ_MULT_BLOCK
: SD_CMD_READ_SINGLE_BLOCK
;
621 ErrorState
= SD_TransmitCommand((CmdIndex
| SD_CMD_RESPONSE_SHORT
), (uint32_t)ReadAddress
, 1);
622 if (ErrorState
!= SD_OK
&& retries
--) {
623 ErrorState
= SD_TransmitCommand((SD_CMD_APP_CMD
| SD_CMD_RESPONSE_SHORT
), 0, 1);
625 } while (ErrorState
!= SD_OK
&& retries
);
627 if (ErrorState
!= SD_OK
) {
628 SD_Handle
.RXCplt
= 0;
631 // Update the SD transfer error in SD handle
632 SD_Handle
.TransferError
= ErrorState
;
638 /** -----------------------------------------------------------------------------------------------------------------*/
640 * @brief Writes block(s) to a specified address in a card. The Data transfer
641 * is managed by DMA mode.
642 * @note This API should be followed by the function SD_CheckOperation()
643 * to check the completion of the write process (by SD current status polling).
644 * @param pWriteBuffer: pointer to the buffer that will contain the data to transmit
645 * @param WriteAddress: Address from where data is to be read
646 * @param BlockSize: the SD card Data block size
647 * @note BlockSize must be 512 bytes.
648 * @param NumberOfBlocks: Number of blocks to write
649 * @retval SD Card error state
651 SD_Error_t
SD_WriteBlocks_DMA(uint64_t WriteAddress
, uint32_t *buffer
, uint32_t BlockSize
, uint32_t NumberOfBlocks
)
653 SD_Error_t ErrorState
;
655 SD_Handle
.TXCplt
= 1;
657 //printf("Reading at %ld into %p %ld blocks\n", (uint32_t)WriteAddress, (void*)buffer, NumberOfBlocks);
659 if(SD_CardType
!= SD_HIGH_CAPACITY
)
664 // Check number of blocks command
665 // Send CMD24 WRITE_SINGLE_BLOCK
666 // Send CMD25 WRITE_MULT_BLOCK with argument data address
667 CmdIndex
= (NumberOfBlocks
> 1) ? SD_CMD_WRITE_MULT_BLOCK
: SD_CMD_WRITE_SINGLE_BLOCK
;
669 // Set Block Size for Card
670 uint8_t retries
= 10;
672 ErrorState
= SD_TransmitCommand((CmdIndex
| SD_CMD_RESPONSE_SHORT
), (uint32_t)WriteAddress
, 1);
673 if (ErrorState
!= SD_OK
&& retries
--) {
674 ErrorState
= SD_TransmitCommand((SD_CMD_APP_CMD
| SD_CMD_RESPONSE_SHORT
), 0, 1);
676 } while(ErrorState
!= SD_OK
&& retries
);
678 if (ErrorState
!= SD_OK
) {
679 SD_Handle
.TXCplt
= 0;
683 SD_StartBlockTransfert(buffer
, BlockSize
, NumberOfBlocks
, SDIO_DIR_TX
);
685 // Configure the SD DPSM (Data Path State Machine)
686 SD_DataTransferInit(BlockSize
* NumberOfBlocks
, SD_DATABLOCK_SIZE_512B
, false);
688 SD_Handle
.TransferError
= ErrorState
;
693 SD_Error_t
SD_CheckWrite(void)
695 if (SD_Handle
.TXCplt
!= 0) return SD_BUSY
;
699 SD_Error_t
SD_CheckRead(void)
701 if (SD_Handle
.RXCplt
!= 0) return SD_BUSY
;
705 /** -----------------------------------------------------------------------------------------------------------------*/
707 * @brief This function waits until the SD DMA data wirte or read transfer is finished.
708 * This should be called after WriteBlocks_DMA or SD_ReadBlocks_DMA() function
709 * to insure that all data sent is already transferred by the DMA controller.
710 * @retval SD Card error state
713 SD_Error_t SD_CheckOperation(uint32_t Flag)
715 SD_Error_t ErrorState = SD_OK;
721 // Wait for DMA/SD transfer end or SD error variables to be in SD handle
722 Temp1 = SD_Handle.DMA_XferComplete;
723 Temp2 = SD_Handle.TransferComplete;
724 Temp3 = (SD_Error_t)SD_Handle.TransferError;
726 if (((Temp1 & Temp2) == 0) && (Temp3 == SD_OK) && (TimeOut > 0))
728 Temp1 = SD_Handle.DMA_XferComplete;
729 Temp2 = SD_Handle.TransferComplete;
730 Temp3 = (SD_Error_t)SD_Handle.TransferError;
735 // Wait until the Rx transfer is no longer active
736 if (((SDIO->STA & Flag) != 0) && (TimeOut > 0))
742 // Send stop command in multi block read
743 if(SD_Handle.Operation & 0x01 == SD_MULTIPLE_BLOCK)
745 ErrorState = SD_TransmitCommand((SD_CMD_STOP_TRANSMISSION | SD_CMD_RESPONSE_SHORT), 0, 1);
748 if((TimeOut == 0) && (ErrorState == SD_OK))
750 ErrorState = SD_DATA_TIMEOUT;
753 // Return error state
754 if(SD_Handle.TransferError != SD_OK)
756 return (SD_Error_t)(SD_Handle.TransferError);
763 /** -----------------------------------------------------------------------------------------------------------------*/
765 * @brief Erases the specified memory area of the given SD card.
766 * @param StartAddress: Start byte address
767 * @param EndAddress: End byte address
768 * @retval SD Card error state
771 SD_Error_t SD_Erase(uint64_t StartAddress, uint64_t EndAddress)
773 SD_Error_t ErrorState;
778 // Check if the card command class supports erase command
779 if(((SD_Handle.CSD[1] >> 20) & SD_CCCC_ERASE) == 0)
781 return SD_REQUEST_NOT_APPLICABLE;
784 // Get max delay value
785 MaxDelay = 120000 / (((SDIO->CLKCR) & 0xFF) + 2);
787 if((SDIO->RESP1 & SD_CARD_LOCKED) == SD_CARD_LOCKED)
789 return SD_LOCK_UNLOCK_FAILED;
792 // Get start and end block for high capacity cards
793 if(SD_CardType == SD_HIGH_CAPACITY)
799 // According to sd-card spec 1.0 ERASE_GROUP_START (CMD32) and erase_group_end(CMD33)
800 if ((SD_CardType == SD_STD_CAPACITY_V1_1) || (SD_CardType == SD_STD_CAPACITY_V2_0) ||
801 (SD_CardType == SD_HIGH_CAPACITY))
803 // Send CMD32 SD_ERASE_GRP_START with argument as addr
804 if((ErrorState = SD_TransmitCommand((SD_CMD_SD_ERASE_GRP_START | SDIO_CMD_RESPONSE_SHORT), (uint32_t)StartAddress, 1)) != SD_OK)
809 // Send CMD33 SD_ERASE_GRP_END with argument as addr
810 if((ErrorState = SD_TransmitCommand((SD_CMD_SD_ERASE_GRP_END | SDIO_CMD_RESPONSE_SHORT), (uint32_t)EndAddress, 1)) != SD_OK)
817 if((ErrorState = SD_TransmitCommand((SD_CMD_ERASE | SDIO_CMD_RESPONSE_SHORT), 0, 1)) != SD_OK)
822 for(Delay = 0; Delay < MaxDelay; Delay++);
824 // Wait until the card is in programming state
825 ErrorState = SD_IsCardProgramming(&CardState);
827 Delay = SD_DATATIMEOUT;
828 while((Delay > 0) && (ErrorState == SD_OK) && ((CardState == SD_CARD_PROGRAMMING) || (CardState == SD_CARD_RECEIVING)))
830 ErrorState = SD_IsCardProgramming( &CardState);
839 /** -----------------------------------------------------------------------------------------------------------------*/
841 * @brief Returns information about specific card.
842 * contains all SD cardinformation
843 * @retval SD Card error state
845 SD_Error_t
SD_GetCardInfo(void)
847 SD_Error_t ErrorState
= SD_OK
;
851 Temp
= (SD_Handle
.CSD
[0] & 0xFF000000) >> 24;
852 SD_CardInfo
.SD_csd
.CSDStruct
= (uint8_t)((Temp
& 0xC0) >> 6);
853 SD_CardInfo
.SD_csd
.SysSpecVersion
= (uint8_t)((Temp
& 0x3C) >> 2);
854 SD_CardInfo
.SD_csd
.Reserved1
= Temp
& 0x03;
857 Temp
= (SD_Handle
.CSD
[0] & 0x00FF0000) >> 16;
858 SD_CardInfo
.SD_csd
.TAAC
= (uint8_t)Temp
;
861 Temp
= (SD_Handle
.CSD
[0] & 0x0000FF00) >> 8;
862 SD_CardInfo
.SD_csd
.NSAC
= (uint8_t)Temp
;
865 Temp
= SD_Handle
.CSD
[0] & 0x000000FF;
866 SD_CardInfo
.SD_csd
.MaxBusClkFrec
= (uint8_t)Temp
;
869 Temp
= (SD_Handle
.CSD
[1] & 0xFF000000) >> 24;
870 SD_CardInfo
.SD_csd
.CardComdClasses
= (uint16_t)(Temp
<< 4);
873 Temp
= (SD_Handle
.CSD
[1] & 0x00FF0000) >> 16;
874 SD_CardInfo
.SD_csd
.CardComdClasses
|= (uint16_t)((Temp
& 0xF0) >> 4);
875 SD_CardInfo
.SD_csd
.RdBlockLen
= (uint8_t)(Temp
& 0x0F);
878 Temp
= (SD_Handle
.CSD
[1] & 0x0000FF00) >> 8;
879 SD_CardInfo
.SD_csd
.PartBlockRead
= (uint8_t)((Temp
& 0x80) >> 7);
880 SD_CardInfo
.SD_csd
.WrBlockMisalign
= (uint8_t)((Temp
& 0x40) >> 6);
881 SD_CardInfo
.SD_csd
.RdBlockMisalign
= (uint8_t)((Temp
& 0x20) >> 5);
882 SD_CardInfo
.SD_csd
.DSRImpl
= (uint8_t)((Temp
& 0x10) >> 4);
883 SD_CardInfo
.SD_csd
.Reserved2
= 0; /*!< Reserved */
885 if((SD_CardType
== SD_STD_CAPACITY_V1_1
) || (SD_CardType
== SD_STD_CAPACITY_V2_0
))
887 SD_CardInfo
.SD_csd
.DeviceSize
= (Temp
& 0x03) << 10;
890 Temp
= (uint8_t)(SD_Handle
.CSD
[1] & 0x000000FF);
891 SD_CardInfo
.SD_csd
.DeviceSize
|= (Temp
) << 2;
894 Temp
= (uint8_t)((SD_Handle
.CSD
[2] & 0xFF000000) >> 24);
895 SD_CardInfo
.SD_csd
.DeviceSize
|= (Temp
& 0xC0) >> 6;
897 SD_CardInfo
.SD_csd
.MaxRdCurrentVDDMin
= (Temp
& 0x38) >> 3;
898 SD_CardInfo
.SD_csd
.MaxRdCurrentVDDMax
= (Temp
& 0x07);
901 Temp
= (uint8_t)((SD_Handle
.CSD
[2] & 0x00FF0000) >> 16);
902 SD_CardInfo
.SD_csd
.MaxWrCurrentVDDMin
= (Temp
& 0xE0) >> 5;
903 SD_CardInfo
.SD_csd
.MaxWrCurrentVDDMax
= (Temp
& 0x1C) >> 2;
904 SD_CardInfo
.SD_csd
.DeviceSizeMul
= (Temp
& 0x03) << 1;
907 Temp
= (uint8_t)((SD_Handle
.CSD
[2] & 0x0000FF00) >> 8);
908 SD_CardInfo
.SD_csd
.DeviceSizeMul
|= (Temp
& 0x80) >> 7;
910 SD_CardInfo
.CardCapacity
= (SD_CardInfo
.SD_csd
.DeviceSize
+ 1) ;
911 SD_CardInfo
.CardCapacity
*= (1 << (SD_CardInfo
.SD_csd
.DeviceSizeMul
+ 2));
912 SD_CardInfo
.CardBlockSize
= 1 << (SD_CardInfo
.SD_csd
.RdBlockLen
);
913 SD_CardInfo
.CardCapacity
= SD_CardInfo
.CardCapacity
* SD_CardInfo
.CardBlockSize
/ 512; // In 512 byte blocks
915 else if(SD_CardType
== SD_HIGH_CAPACITY
)
918 Temp
= (uint8_t)(SD_Handle
.CSD
[1] & 0x000000FF);
919 SD_CardInfo
.SD_csd
.DeviceSize
= (Temp
& 0x3F) << 16;
922 Temp
= (uint8_t)((SD_Handle
.CSD
[2] & 0xFF000000) >> 24);
924 SD_CardInfo
.SD_csd
.DeviceSize
|= (Temp
<< 8);
927 Temp
= (uint8_t)((SD_Handle
.CSD
[2] & 0x00FF0000) >> 16);
929 SD_CardInfo
.SD_csd
.DeviceSize
|= (Temp
);
932 Temp
= (uint8_t)((SD_Handle
.CSD
[2] & 0x0000FF00) >> 8);
934 SD_CardInfo
.CardCapacity
= ((uint64_t)SD_CardInfo
.SD_csd
.DeviceSize
+ 1) * 1024;
935 SD_CardInfo
.CardBlockSize
= 512;
939 // Not supported card type
940 ErrorState
= SD_ERROR
;
943 SD_CardInfo
.SD_csd
.EraseGrSize
= (Temp
& 0x40) >> 6;
944 SD_CardInfo
.SD_csd
.EraseGrMul
= (Temp
& 0x3F) << 1;
947 Temp
= (uint8_t)(SD_Handle
.CSD
[2] & 0x000000FF);
948 SD_CardInfo
.SD_csd
.EraseGrMul
|= (Temp
& 0x80) >> 7;
949 SD_CardInfo
.SD_csd
.WrProtectGrSize
= (Temp
& 0x7F);
952 Temp
= (uint8_t)((SD_Handle
.CSD
[3] & 0xFF000000) >> 24);
953 SD_CardInfo
.SD_csd
.WrProtectGrEnable
= (Temp
& 0x80) >> 7;
954 SD_CardInfo
.SD_csd
.ManDeflECC
= (Temp
& 0x60) >> 5;
955 SD_CardInfo
.SD_csd
.WrSpeedFact
= (Temp
& 0x1C) >> 2;
956 SD_CardInfo
.SD_csd
.MaxWrBlockLen
= (Temp
& 0x03) << 2;
959 Temp
= (uint8_t)((SD_Handle
.CSD
[3] & 0x00FF0000) >> 16);
960 SD_CardInfo
.SD_csd
.MaxWrBlockLen
|= (Temp
& 0xC0) >> 6;
961 SD_CardInfo
.SD_csd
.WriteBlockPaPartial
= (Temp
& 0x20) >> 5;
962 SD_CardInfo
.SD_csd
.Reserved3
= 0;
963 SD_CardInfo
.SD_csd
.ContentProtectAppli
= (Temp
& 0x01);
966 Temp
= (uint8_t)((SD_Handle
.CSD
[3] & 0x0000FF00) >> 8);
967 SD_CardInfo
.SD_csd
.FileFormatGrouop
= (Temp
& 0x80) >> 7;
968 SD_CardInfo
.SD_csd
.CopyFlag
= (Temp
& 0x40) >> 6;
969 SD_CardInfo
.SD_csd
.PermWrProtect
= (Temp
& 0x20) >> 5;
970 SD_CardInfo
.SD_csd
.TempWrProtect
= (Temp
& 0x10) >> 4;
971 SD_CardInfo
.SD_csd
.FileFormat
= (Temp
& 0x0C) >> 2;
972 SD_CardInfo
.SD_csd
.ECC
= (Temp
& 0x03);
975 Temp
= (uint8_t)(SD_Handle
.CSD
[3] & 0x000000FF);
976 SD_CardInfo
.SD_csd
.CSD_CRC
= (Temp
& 0xFE) >> 1;
977 SD_CardInfo
.SD_csd
.Reserved4
= 1;
980 Temp
= (uint8_t)((SD_Handle
.CID
[0] & 0xFF000000) >> 24);
981 SD_CardInfo
.SD_cid
.ManufacturerID
= Temp
;
984 Temp
= (uint8_t)((SD_Handle
.CID
[0] & 0x00FF0000) >> 16);
985 SD_CardInfo
.SD_cid
.OEM_AppliID
= Temp
<< 8;
988 Temp
= (uint8_t)((SD_Handle
.CID
[0] & 0x000000FF00) >> 8);
989 SD_CardInfo
.SD_cid
.OEM_AppliID
|= Temp
;
992 Temp
= (uint8_t)(SD_Handle
.CID
[0] & 0x000000FF);
993 SD_CardInfo
.SD_cid
.ProdName1
= Temp
<< 24;
996 Temp
= (uint8_t)((SD_Handle
.CID
[1] & 0xFF000000) >> 24);
997 SD_CardInfo
.SD_cid
.ProdName1
|= Temp
<< 16;
1000 Temp
= (uint8_t)((SD_Handle
.CID
[1] & 0x00FF0000) >> 16);
1001 SD_CardInfo
.SD_cid
.ProdName1
|= Temp
<< 8;
1004 Temp
= (uint8_t)((SD_Handle
.CID
[1] & 0x0000FF00) >> 8);
1005 SD_CardInfo
.SD_cid
.ProdName1
|= Temp
;
1008 Temp
= (uint8_t)(SD_Handle
.CID
[1] & 0x000000FF);
1009 SD_CardInfo
.SD_cid
.ProdName2
= Temp
;
1012 Temp
= (uint8_t)((SD_Handle
.CID
[2] & 0xFF000000) >> 24);
1013 SD_CardInfo
.SD_cid
.ProdRev
= Temp
;
1016 Temp
= (uint8_t)((SD_Handle
.CID
[2] & 0x00FF0000) >> 16);
1017 SD_CardInfo
.SD_cid
.ProdSN
= Temp
<< 24;
1020 Temp
= (uint8_t)((SD_Handle
.CID
[2] & 0x0000FF00) >> 8);
1021 SD_CardInfo
.SD_cid
.ProdSN
|= Temp
<< 16;
1024 Temp
= (uint8_t)(SD_Handle
.CID
[2] & 0x000000FF);
1025 SD_CardInfo
.SD_cid
.ProdSN
|= Temp
<< 8;
1028 Temp
= (uint8_t)((SD_Handle
.CID
[3] & 0xFF000000) >> 24);
1029 SD_CardInfo
.SD_cid
.ProdSN
|= Temp
;
1032 Temp
= (uint8_t)((SD_Handle
.CID
[3] & 0x00FF0000) >> 16);
1033 SD_CardInfo
.SD_cid
.Reserved1
|= (Temp
& 0xF0) >> 4;
1034 SD_CardInfo
.SD_cid
.ManufactDate
= (Temp
& 0x0F) << 8;
1037 Temp
= (uint8_t)((SD_Handle
.CID
[3] & 0x0000FF00) >> 8);
1038 SD_CardInfo
.SD_cid
.ManufactDate
|= Temp
;
1041 Temp
= (uint8_t)(SD_Handle
.CID
[3] & 0x000000FF);
1042 SD_CardInfo
.SD_cid
.CID_CRC
= (Temp
& 0xFE) >> 1;
1043 SD_CardInfo
.SD_cid
.Reserved2
= 1;
1049 /** -----------------------------------------------------------------------------------------------------------------*/
1051 * @brief Enables wide bus operation for the requested card if supported by
1053 * @param WideMode: Specifies the SD card wide bus mode
1054 * This parameter can be one of the following values:
1055 * @arg SD_BUS_WIDE_8B: 8-bit data transfer (Only for MMC)
1056 * @arg SD_BUS_WIDE_4B: 4-bit data transfer
1057 * @arg SD_BUS_WIDE_1B: 1-bit data transfer
1058 * @retval SD Card error state
1060 static SD_Error_t
SD_WideBusOperationConfig(uint32_t WideMode
)
1062 SD_Error_t ErrorState
= SD_OK
;
1064 uint32_t SCR
[2] = {0, 0};
1066 if((SD_CardType
== SD_STD_CAPACITY_V1_1
) || (SD_CardType
== SD_STD_CAPACITY_V2_0
) ||\
1067 (SD_CardType
== SD_HIGH_CAPACITY
))
1069 if(WideMode
== SD_BUS_WIDE_8B
)
1071 ErrorState
= SD_UNSUPPORTED_FEATURE
;
1073 else if((WideMode
== SD_BUS_WIDE_4B
) ||
1074 (WideMode
== SD_BUS_WIDE_1B
))
1076 if((SDIO
->RESP1
& SD_CARD_LOCKED
) != SD_CARD_LOCKED
)
1079 ErrorState
= SD_FindSCR(SCR
);
1080 if(ErrorState
== SD_OK
)
1082 Temp
= (WideMode
== SD_BUS_WIDE_4B
) ? SD_WIDE_BUS_SUPPORT
: SD_SINGLE_BUS_SUPPORT
;
1084 // If requested card supports wide bus operation
1085 if((SCR
[1] & Temp
) != SD_ALLZERO
)
1087 // Send CMD55 APP_CMD with argument as card's RCA.
1088 ErrorState
= SD_TransmitCommand((SD_CMD_APP_CMD
| SD_CMD_RESPONSE_SHORT
), SD_CardRCA
, 1);
1089 if(ErrorState
== SD_OK
)
1091 Temp
= (WideMode
== SD_BUS_WIDE_4B
) ? 2 : 0;
1093 // Send ACMD6 APP_CMD with argument as 2 for wide bus mode
1094 ErrorState
= SD_TransmitCommand((SD_CMD_APP_SD_SET_BUSWIDTH
| SD_CMD_RESPONSE_SHORT
), Temp
, 1);
1099 ErrorState
= SD_REQUEST_NOT_APPLICABLE
;
1105 ErrorState
= SD_LOCK_UNLOCK_FAILED
;
1110 ErrorState
= SD_INVALID_PARAMETER
; // WideMode is not a valid argument
1113 if(ErrorState
== SD_OK
)
1115 // Configure the SDIO peripheral, we need this delay for some reason...
1116 while ((READ_REG(SDIO
->CLKCR
) & 0x800) != WideMode
) {
1117 MODIFY_REG(SDIO
->CLKCR
, CLKCR_CLEAR_MASK
, (uint32_t) WideMode
);
1122 ErrorState
= SD_UNSUPPORTED_FEATURE
;
1130 /** -----------------------------------------------------------------------------------------------------------------*/
1132 * @brief Switches the SD card to High Speed mode.
1133 * This API must be used after "Transfer State"
1134 * @retval SD Card error state
1136 SD_Error_t
SD_HighSpeed(void)
1138 SD_Error_t ErrorState
;
1139 uint8_t SD_hs
[64] = {0};
1140 uint32_t SD_scr
[2] = {0, 0};
1141 uint32_t SD_SPEC
= 0;
1143 uint32_t* Buffer
= (uint32_t *)SD_hs
;
1145 // Initialize the Data control register
1149 if((ErrorState
= SD_FindSCR(SD_scr
)) != SD_OK
)
1154 // Test the Version supported by the card
1155 SD_SPEC
= (SD_scr
[1] & 0x01000000) | (SD_scr
[1] & 0x02000000);
1157 if(SD_SPEC
!= SD_ALLZERO
)
1159 // Set Block Size for Card
1160 if((ErrorState
= SD_TransmitCommand((SD_CMD_SET_BLOCKLEN
| SD_CMD_RESPONSE_SHORT
), 64, 1)) != SD_OK
)
1165 // Configure the SD DPSM (Data Path State Machine)
1166 SD_DataTransferInit(64, SD_DATABLOCK_SIZE_64B
, true);
1168 // Send CMD6 switch mode
1169 if((ErrorState
=SD_TransmitCommand((SD_CMD_HS_SWITCH
| SD_CMD_RESPONSE_SHORT
), 0x80FFFF01, 1)) != SD_OK
)
1174 while((SDIO
->STA
& (SDIO_STA_RXOVERR
| SDIO_STA_DCRCFAIL
| SDIO_STA_DTIMEOUT
| SDIO_STA_DBCKEND
)) == 0)
1176 if((SDIO
->STA
& SDIO_STA_RXFIFOHF
) != 0)
1178 for(Count
= 0; Count
< 8; Count
++)
1180 *(Buffer
+ Count
) = SDIO
->FIFO
;
1187 if((SDIO
->STA
& SDIO_STA_DTIMEOUT
) != 0) return SD_DATA_TIMEOUT
;
1188 else if((SDIO
->STA
& SDIO_STA_DCRCFAIL
) != 0) return SD_DATA_CRC_FAIL
;
1189 else if((SDIO
->STA
& SDIO_STA_RXOVERR
) != 0) return SD_RX_OVERRUN
;
1191 Count
= SD_DATATIMEOUT
;
1193 while(((SDIO
->STA
& SDIO_STA_RXDAVL
) != 0) && (Count
> 0))
1195 *Buffer
= SDIO
->FIFO
;
1200 // Test if the switch mode HS is ok
1201 if((SD_hs
[13] & 2) != 2)
1203 ErrorState
= SD_UNSUPPORTED_FEATURE
;
1211 /** -----------------------------------------------------------------------------------------------------------------*/
1213 * @brief Gets the current card's data status.
1214 * @retval Data Transfer state
1216 SD_Error_t
SD_GetStatus(void)
1218 SD_Error_t ErrorState
;
1220 SD_CardState_t CardState
;
1223 // Send Status command
1224 if((ErrorState
= SD_TransmitCommand((SD_CMD_SEND_STATUS
| SD_CMD_RESPONSE_SHORT
), SD_CardRCA
, 1)) == SD_OK
)
1226 Response1
= SDIO
->RESP1
;
1227 CardState
= (SD_CardState_t
)((Response1
>> 9) & 0x0F);
1229 // Find SD status according to card state
1230 if (CardState
== SD_CARD_TRANSFER
) ErrorState
= SD_OK
;
1231 else if(CardState
== SD_CARD_ERROR
) ErrorState
= SD_ERROR
;
1232 else ErrorState
= SD_BUSY
;
1236 ErrorState
= SD_ERROR
;
1243 /** -----------------------------------------------------------------------------------------------------------------*/
1245 * @brief Gets the SD card status.
1246 * @retval SD Card error state
1248 SD_Error_t
SD_GetCardStatus(SD_CardStatus_t
* pCardStatus
)
1250 SD_Error_t ErrorState
;
1252 uint32_t Status
[16];
1255 // Check SD response
1256 if((SDIO
->RESP1
& SD_CARD_LOCKED
) == SD_CARD_LOCKED
)
1258 return SD_LOCK_UNLOCK_FAILED
;
1261 // Set block size for card if it is not equal to current block size for card
1262 if((ErrorState
= SD_TransmitCommand((SD_CMD_SET_BLOCKLEN
| SD_CMD_RESPONSE_SHORT
), 64, 1)) != SD_OK
)
1268 if((ErrorState
= SD_TransmitCommand((SD_CMD_APP_CMD
| SD_CMD_RESPONSE_SHORT
), SD_CardRCA
, 1)) != SD_OK
)
1273 // Configure the SD DPSM (Data Path State Machine)
1274 SD_DataTransferInit(64, SD_DATABLOCK_SIZE_64B
, true);
1276 // Send ACMD13 (SD_APP_STAUS) with argument as card's RCA
1277 if((ErrorState
= SD_TransmitCommand((SD_CMD_SD_APP_STATUS
| SD_CMD_RESPONSE_SHORT
), 0, 1)) != SD_OK
)
1283 while((SDIO
->STA
& (SDIO_STA_RXOVERR
| SDIO_STA_DCRCFAIL
| SDIO_STA_DTIMEOUT
| SDIO_STA_DBCKEND
)) == 0)
1285 if((SDIO
->STA
& SDIO_STA_RXFIFOHF
) != 0)
1287 for(Count
= 0; Count
< 8; Count
++)
1289 Status
[Count
] = SDIO
->FIFO
;
1294 if((SDIO
->STA
& SDIO_STA_DTIMEOUT
) != 0) return SD_DATA_TIMEOUT
;
1295 else if((SDIO
->STA
& SDIO_STA_DCRCFAIL
) != 0) return SD_DATA_CRC_FAIL
;
1296 else if((SDIO
->STA
& SDIO_STA_RXOVERR
) != 0) return SD_RX_OVERRUN
;
1300 this part from the HAL is very strange has it is possible to overflow the provide buffer... and this originate from ST HAL
1302 Count = SD_DATATIMEOUT;
1303 while(((SDIO->STA & SDIO_STA_RXDAVL) != 0) && (Count > 0))
1305 *pSDstatus = SDIO->FIFO;
1313 Temp
= (Status
[0] & 0xC0) >> 6;
1314 pCardStatus
->DAT_BUS_WIDTH
= (uint8_t)Temp
;
1317 Temp
= (Status
[0] & 0x20) >> 5;
1318 pCardStatus
->SECURED_MODE
= (uint8_t)Temp
;
1321 Temp
= (Status
[2] & 0xFF);
1322 pCardStatus
->SD_CARD_TYPE
= (uint8_t)(Temp
<< 8);
1325 Temp
= (Status
[3] & 0xFF);
1326 pCardStatus
->SD_CARD_TYPE
|= (uint8_t)Temp
;
1329 Temp
= (Status
[4] & 0xFF);
1330 pCardStatus
->SIZE_OF_PROTECTED_AREA
= (uint8_t)(Temp
<< 24);
1333 Temp
= (Status
[5] & 0xFF);
1334 pCardStatus
->SIZE_OF_PROTECTED_AREA
|= (uint8_t)(Temp
<< 16);
1337 Temp
= (Status
[6] & 0xFF);
1338 pCardStatus
->SIZE_OF_PROTECTED_AREA
|= (uint8_t)(Temp
<< 8);
1341 Temp
= (Status
[7] & 0xFF);
1342 pCardStatus
->SIZE_OF_PROTECTED_AREA
|= (uint8_t)Temp
;
1345 Temp
= (Status
[8] & 0xFF);
1346 pCardStatus
->SPEED_CLASS
= (uint8_t)Temp
;
1349 Temp
= (Status
[9] & 0xFF);
1350 pCardStatus
->PERFORMANCE_MOVE
= (uint8_t)Temp
;
1353 Temp
= (Status
[10] & 0xF0) >> 4;
1354 pCardStatus
->AU_SIZE
= (uint8_t)Temp
;
1357 Temp
= (Status
[11] & 0xFF);
1358 pCardStatus
->ERASE_SIZE
= (uint8_t)(Temp
<< 8);
1361 Temp
= (Status
[12] & 0xFF);
1362 pCardStatus
->ERASE_SIZE
|= (uint8_t)Temp
;
1365 Temp
= (Status
[13] & 0xFC) >> 2;
1366 pCardStatus
->ERASE_TIMEOUT
= (uint8_t)Temp
;
1369 Temp
= (Status
[13] & 0x3);
1370 pCardStatus
->ERASE_OFFSET
= (uint8_t)Temp
;
1376 /** -----------------------------------------------------------------------------------------------------------------*/
1378 * @brief Enquires cards about their operating voltage and configures clock
1379 * controls and stores SD information that will be needed in future
1381 * @retval SD Card error state
1383 static SD_Error_t
SD_PowerON(void)
1385 SD_Error_t ErrorState
;
1388 uint32_t ValidVoltage
;
1390 //uint32_t TickStart;
1394 SD_Type
= SD_RESP_STD_CAPACITY
;
1396 // Power ON Sequence -------------------------------------------------------
1397 SDIO
->CLKCR
&= ~SDIO_CLKCR_CLKEN
; // Disable SDIO Clock
1398 SDIO
->POWER
= SDIO_POWER_PWRCTRL
; // Set Power State to ON
1400 // 1ms: required power up waiting time before starting the SD initialization sequence (make it 2 to be safe)
1403 SDIO
->CLKCR
|= SDIO_CLKCR_CLKEN
; // Enable SDIO Clock
1405 // CMD0: GO_IDLE_STATE -----------------------------------------------------
1406 // No CMD response required
1407 if((ErrorState
= SD_TransmitCommand(SD_CMD_GO_IDLE_STATE
, 0, 0)) != SD_OK
)
1409 // CMD Response Timeout (wait for CMDSENT flag)
1413 // CMD8: SEND_IF_COND ------------------------------------------------------
1414 // Send CMD8 to verify SD card interface operating condition
1415 // Argument: - [31:12]: Reserved (shall be set to '0')
1416 //- [11:8]: Supply Voltage (VHS) 0x1 (Range: 2.7-3.6 V)
1417 //- [7:0]: Check Pattern (recommended 0xAA)
1418 // CMD Response: R7 */
1419 if((ErrorState
= SD_TransmitCommand((SD_SDIO_SEND_IF_COND
| SD_CMD_RESPONSE_SHORT
), SD_CHECK_PATTERN
, 7)) == SD_OK
)
1422 SD_CardType
= SD_STD_CAPACITY_V2_0
;
1423 SD_Type
= SD_RESP_HIGH_CAPACITY
;
1427 // If ErrorState is Command Timeout, it is a MMC card
1428 // If ErrorState is SD_OK it is a SD card: SD card 2.0 (voltage range mismatch) or SD card 1.x
1429 if((ErrorState
= SD_TransmitCommand((SD_CMD_APP_CMD
| SD_CMD_RESPONSE_SHORT
), 0, 1)) == SD_OK
)
1432 // Send ACMD41 SD_APP_OP_COND with Argument 0x80100000
1433 while((ValidVoltage
== 0) && (Count
< SD_MAX_VOLT_TRIAL
))
1435 // SEND CMD55 APP_CMD with RCA as 0
1436 if((ErrorState
= SD_TransmitCommand((SD_CMD_APP_CMD
| SD_CMD_RESPONSE_SHORT
), 0, 1)) != SD_OK
)
1442 if((ErrorState
= SD_TransmitCommand((SD_CMD_SD_APP_OP_COND
| SD_CMD_RESPONSE_SHORT
), SD_VOLTAGE_WINDOW_SD
| SD_Type
, 3)) != SD_OK
)
1447 Response
= SDIO
->RESP1
; // Get command response
1448 ValidVoltage
= (((Response
>> 31) == 1) ? 1 : 0); // Get operating voltage
1452 if(Count
>= SD_MAX_VOLT_TRIAL
)
1454 return SD_INVALID_VOLTRANGE
;
1457 if((Response
& SD_RESP_HIGH_CAPACITY
) == SD_RESP_HIGH_CAPACITY
)
1459 SD_CardType
= SD_HIGH_CAPACITY
;
1467 /** -----------------------------------------------------------------------------------------------------------------*/
1469 * @brief Turns the SDIO output signals off.
1470 * @retval SD Card error state
1473 static void SD_PowerOFF(void)
1475 // Set Power State to OFF
1476 SDIO
->POWER
= (uint32_t)0;
1481 /** -----------------------------------------------------------------------------------------------------------------*/
1483 * @brief Finds the SD card SCR register value.
1484 * @param pSCR: pointer to the buffer that will contain the SCR value
1485 * @retval SD Card error state
1487 static SD_Error_t
SD_FindSCR(uint32_t *pSCR
)
1489 SD_Error_t ErrorState
;
1491 uint32_t tempscr
[2] = {0, 0};
1493 // Set Block Size To 8 Bytes
1494 // Send CMD55 APP_CMD with argument as card's RCA
1495 if((ErrorState
= SD_TransmitCommand((SD_CMD_SET_BLOCKLEN
| SD_CMD_RESPONSE_SHORT
), 8, 1)) == SD_OK
)
1497 // Send CMD55 APP_CMD with argument as card's RCA
1498 if((ErrorState
= SD_TransmitCommand((SD_CMD_APP_CMD
| SD_CMD_RESPONSE_SHORT
), SD_CardRCA
, 1)) == SD_OK
)
1500 SD_DataTransferInit(8, SD_DATABLOCK_SIZE_8B
, true);
1502 // Send ACMD51 SD_APP_SEND_SCR with argument as 0
1503 if((ErrorState
= SD_TransmitCommand((SD_CMD_SD_APP_SEND_SCR
| SD_CMD_RESPONSE_SHORT
), 0, 1)) == SD_OK
)
1505 while((SDIO
->STA
& (SDIO_STA_RXOVERR
| SDIO_STA_DCRCFAIL
| SDIO_STA_DTIMEOUT
| SDIO_STA_DBCKEND
)) == 0)
1507 if((SDIO
->STA
& SDIO_STA_RXDAVL
) != 0)
1509 *(tempscr
+ Index
) = SDIO
->FIFO
;
1514 if ((SDIO
->STA
& SDIO_STA_DTIMEOUT
) != 0) ErrorState
= SD_DATA_TIMEOUT
;
1515 else if((SDIO
->STA
& SDIO_STA_DCRCFAIL
) != 0) ErrorState
= SD_DATA_CRC_FAIL
;
1516 else if((SDIO
->STA
& SDIO_STA_RXOVERR
) != 0) ErrorState
= SD_RX_OVERRUN
;
1517 else if((SDIO
->STA
& SDIO_STA_RXDAVL
) != 0) ErrorState
= SD_OUT_OF_BOUND
;
1520 *(pSCR
+ 1) = ((tempscr
[0] & SD_0TO7BITS
) << 24) | ((tempscr
[0] & SD_8TO15BITS
) << 8) |
1521 ((tempscr
[0] & SD_16TO23BITS
) >> 8) | ((tempscr
[0] & SD_24TO31BITS
) >> 24);
1523 *(pSCR
) = ((tempscr
[1] & SD_0TO7BITS
) << 24) | ((tempscr
[1] & SD_8TO15BITS
) << 8) |
1524 ((tempscr
[1] & SD_16TO23BITS
) >> 8) | ((tempscr
[1] & SD_24TO31BITS
) >> 24);
1535 /** -----------------------------------------------------------------------------------------------------------------*/
1537 * @brief Checks if the SD card is in programming state.
1538 * @param pStatus: pointer to the variable that will contain the SD card state
1539 * @retval SD Card error state
1542 static SD_Error_t SD_IsCardProgramming(uint8_t *pStatus)
1544 uint32_t Response_R1;
1546 SD_TransmitCommand((SD_CMD_SEND_STATUS | SDIO_CMD_RESPONSE_SHORT), SD_CardRCA, 0);
1547 if((SDIO->STA & SDIO_STA_CTIMEOUT) != 0) return SD_CMD_RSP_TIMEOUT;
1548 else if((SDIO->STA & SDIO_STA_CCRCFAIL) != 0) return SD_CMD_CRC_FAIL;
1549 if((uint32_t)SDIO->RESPCMD != SD_CMD_SEND_STATUS) return SD_ILLEGAL_CMD; // Check if is of desired command
1550 Response_R1 = SDIO->RESP1; // We have received response, retrieve it for analysis
1551 *pStatus = (uint8_t)((Response_R1 >> 9) & 0x0000000F); // Find out card status
1553 return CheckOCR_Response(Response_R1);
1557 /** -----------------------------------------------------------------------------------------------------------------*/
1559 * @brief Initialize the SDIO module, DMA, and IO
1561 bool SD_Initialize_LL(DMA_Stream_TypeDef
*dma
)
1563 const dmaIdentifier_e dmaIdentifier
= dmaGetIdentifier((dmaResource_t
*)dmaStream
);
1564 if (!(dma
== DMA2_Stream3
|| dma
== DMA2_Stream6
) || !dmaAllocate(dmaIdentifier
, OWNER_SDCARD
, 0)) {
1568 // Reset SDIO Module
1569 RCC
->APB2RSTR
|= RCC_APB2RSTR_SDIORST
;
1571 RCC
->APB2RSTR
&= ~RCC_APB2RSTR_SDIORST
;
1574 // Enable SDIO clock
1575 RCC
->APB2ENR
|= RCC_APB2ENR_SDIOEN
;
1577 // Enable DMA2 clocks
1578 RCC
->AHB1ENR
|= RCC_AHB1ENR_DMA2EN
;
1581 RCC
->AHB1ENR
|= RCC_AHB1ENR_GPIOCEN
| RCC_AHB1ENR_GPIODEN
;
1583 uint8_t is4BitWidth
= sdioConfig()->use4BitWidth
;
1585 const IO_t d0
= IOGetByTag(IO_TAG(PC8
));
1586 const IO_t d1
= IOGetByTag(IO_TAG(PC9
));
1587 const IO_t d2
= IOGetByTag(IO_TAG(PC10
));
1588 const IO_t d3
= IOGetByTag(IO_TAG(PC11
));
1589 const IO_t clk
= IOGetByTag(IO_TAG(PC12
));
1590 const IO_t cmd
= IOGetByTag(IO_TAG(PD2
));
1592 IOInit(d0
, OWNER_SDCARD
, 0);
1594 IOInit(d1
, OWNER_SDCARD
, 0);
1595 IOInit(d2
, OWNER_SDCARD
, 0);
1596 IOInit(d3
, OWNER_SDCARD
, 0);
1598 IOInit(clk
, OWNER_SDCARD
, 0);
1599 IOInit(cmd
, OWNER_SDCARD
, 0);
1601 #define SDIO_DATA IO_CONFIG(GPIO_Mode_AF, GPIO_Speed_100MHz, GPIO_OType_PP, GPIO_PuPd_NOPULL)
1602 #define SDIO_CMD IO_CONFIG(GPIO_Mode_AF, GPIO_Speed_100MHz, GPIO_OType_PP, GPIO_PuPd_NOPULL)
1603 #define SDIO_CLK IO_CONFIG(GPIO_Mode_AF, GPIO_Speed_100MHz, GPIO_OType_PP, GPIO_PuPd_NOPULL)
1605 IOConfigGPIOAF(d0
, SDIO_DATA
, GPIO_AF_SDIO
);
1607 IOConfigGPIOAF(d1
, SDIO_DATA
, GPIO_AF_SDIO
);
1608 IOConfigGPIOAF(d2
, SDIO_DATA
, GPIO_AF_SDIO
);
1609 IOConfigGPIOAF(d3
, SDIO_DATA
, GPIO_AF_SDIO
);
1611 IOConfigGPIOAF(clk
, SDIO_CLK
, GPIO_AF_SDIO
);
1612 IOConfigGPIOAF(cmd
, SDIO_CMD
, GPIO_AF_SDIO
);
1614 // NVIC configuration for SDIO interrupts
1615 NVIC_InitTypeDef NVIC_InitStructure
;
1616 NVIC_InitStructure
.NVIC_IRQChannel
= SDIO_IRQn
;
1617 NVIC_InitStructure
.NVIC_IRQChannelPreemptionPriority
= NVIC_PRIORITY_BASE(1);
1618 NVIC_InitStructure
.NVIC_IRQChannelSubPriority
= NVIC_PRIORITY_SUB(0);
1619 NVIC_InitStructure
.NVIC_IRQChannelCmd
= ENABLE
;
1620 NVIC_Init(&NVIC_InitStructure
);
1623 RCC
->AHB1ENR
|= RCC_AHB1ENR_DMA2EN
;
1625 dmaStream
->CR
= 0; // Reset DMA Stream control register
1626 dmaStream
->PAR
= (uint32_t)&SDIO
->FIFO
;
1627 if (dmaStream
== DMA2_Stream3
) {
1628 DMA2
->LIFCR
= IFCR_CLEAR_MASK_STREAM3
; // Clear all interrupt flags
1630 DMA2
->HIFCR
= IFCR_CLEAR_MASK_STREAM6
; // Clear all interrupt flags
1632 dmaStream
->CR
= (DMA_CHANNEL_4
| DMA_SxCR_PFCTRL
| // Prepare the DMA Stream configuration
1633 DMA_MINC_ENABLE
| DMA_PDATAALIGN_WORD
| // And write to DMA Stream CR register
1634 DMA_MDATAALIGN_WORD
| DMA_PRIORITY_VERY_HIGH
|
1635 DMA_MBURST_INC4
| DMA_PBURST_INC4
|
1636 DMA_MEMORY_TO_PERIPH
);
1637 dmaStream
->FCR
= (DMA_SxFCR_DMDIS
| DMA_SxFCR_FTH
); // Configuration FIFO control register
1638 dmaEnable(dmaIdentifier
);
1639 if (dmaStream
== DMA2_Stream3
) {
1640 dmaSetHandler(dmaIdentifier
, SDIO_DMA_ST3_IRQHandler
, 1, 0);
1642 dmaSetHandler(dmaIdentifier
, SDIO_DMA_ST6_IRQHandler
, 1, 0);
1649 /** -----------------------------------------------------------------------------------------------------------------*/
1650 bool SD_GetState(void)
1652 // Check SDCARD status
1653 if(SD_GetStatus() == SD_OK
) return true;
1658 /** -----------------------------------------------------------------------------------------------------------------*/
1659 static SD_Error_t
SD_DoInit(void)
1661 SD_Error_t errorState
;
1663 // Initialize SDIO peripheral interface with default configuration for SD card initialization.
1664 MODIFY_REG(SDIO
->CLKCR
, CLKCR_CLEAR_MASK
, (uint32_t)SDIO_INIT_CLK_DIV
);
1666 // Identify card operating voltage.
1667 errorState
= SD_PowerON();
1668 if (errorState
!= SD_OK
) {
1672 // Initialize the present card and put them in idle state.
1673 errorState
= SD_InitializeCard();
1674 if (errorState
!= SD_OK
) {
1678 // Read CSD/CID MSD registers.
1679 errorState
= SD_GetCardInfo();
1680 if (errorState
!= SD_OK
) {
1684 // Select the Card - Send CMD7 SDIO_SEL_DESEL_CARD.
1685 errorState
= SD_TransmitCommand((SD_CMD_SEL_DESEL_CARD
| SD_CMD_RESPONSE_SHORT
), SD_CardRCA
, 1);
1686 // Configure SDIO peripheral interface.
1687 MODIFY_REG(SDIO
->CLKCR
, CLKCR_CLEAR_MASK
, (uint32_t) SDIO_CLK_DIV
);
1689 // Configure SD Bus width.
1690 if (errorState
== SD_OK
)
1692 // Enable wide operation.
1693 if (sdioConfig()->use4BitWidth
) {
1694 errorState
= SD_WideBusOperationConfig(SD_BUS_WIDE_4B
);
1696 errorState
= SD_WideBusOperationConfig(SD_BUS_WIDE_1B
);
1698 if (errorState
== SD_OK
&& sdioConfig()->clockBypass
) {
1699 if (SD_HighSpeed()) {
1700 SDIO
->CLKCR
|= SDIO_CLKCR_BYPASS
;
1701 SDIO
->CLKCR
|= SDIO_CLKCR_NEGEDGE
;
1709 SD_Error_t
SD_Init(void)
1711 static bool sdInitAttempted
= false;
1712 static SD_Error_t result
= SD_ERROR
;
1714 if (sdInitAttempted
) {
1718 sdInitAttempted
= true;
1720 result
= SD_DoInit();
1725 /** -----------------------------------------------------------------------------------------------------------------*/
1727 * @brief This function handles SD card interrupt request.
1729 void SDIO_IRQHandler(void)
1731 // Check for SDIO interrupt flags
1732 if ((SDIO
->STA
& SDIO_STA_DATAEND
) != 0) {
1733 SDIO
->ICR
= SDIO_ICR_DATAENDC
;
1734 SDIO
->ICR
= SDIO_ICR_STATIC_FLAGS
;
1735 SDIO
->MASK
&= ~(SDIO_MASK_DATAENDIE
| SDIO_MASK_DCRCFAILIE
| SDIO_MASK_DTIMEOUTIE
| \
1736 SDIO_MASK_TXUNDERRIE
| SDIO_MASK_RXOVERRIE
| SDIO_MASK_TXFIFOHEIE
| SDIO_MASK_RXFIFOHFIE
);
1738 /* Currently doesn't implement multiple block write handling */
1739 if ((SD_Handle
.Operation
& 0x02) == (SDIO_DIR_TX
<< 1)) {
1740 /* Disable the stream */
1741 dmaStream
->CR
&= ~DMA_SxCR_EN
;
1742 SDIO
->DCTRL
&= ~(SDIO_DCTRL_DMAEN
);
1743 /* Transfer is complete */
1744 SD_Handle
.TXCplt
= 0;
1745 if ((SD_Handle
.Operation
& 0x01) == SD_MULTIPLE_BLOCK
) {
1746 /* Send stop command in multiblock write */
1747 SD_TransmitCommand((SD_CMD_STOP_TRANSMISSION
| SD_CMD_RESPONSE_SHORT
), 0, 1);
1750 SD_Handle
.TransferComplete
= 1;
1751 SD_Handle
.TransferError
= SD_OK
; // No transfer error
1753 else if ((SDIO
->STA
& SDIO_STA_DCRCFAIL
) != 0)
1754 SD_Handle
.TransferError
= SD_DATA_CRC_FAIL
;
1755 else if ((SDIO
->STA
& SDIO_STA_DTIMEOUT
) != 0)
1756 SD_Handle
.TransferError
= SD_DATA_TIMEOUT
;
1757 else if ((SDIO
->STA
& SDIO_STA_RXOVERR
) != 0)
1758 SD_Handle
.TransferError
= SD_RX_OVERRUN
;
1759 else if ((SDIO
->STA
& SDIO_STA_TXUNDERR
) != 0)
1760 SD_Handle
.TransferError
= SD_TX_UNDERRUN
;
1762 SDIO
->ICR
= SDIO_ICR_STATIC_FLAGS
;
1764 // Disable all SDIO peripheral interrupt sources
1765 SDIO
->MASK
&= ~(SDIO_MASK_DCRCFAILIE
| SDIO_MASK_DTIMEOUTIE
1766 | SDIO_MASK_DATAENDIE
|
1767 SDIO_MASK_TXFIFOHEIE
| SDIO_MASK_RXFIFOHFIE
| SDIO_MASK_TXUNDERRIE
|
1768 SDIO_MASK_RXOVERRIE
);
1771 /** -----------------------------------------------------------------------------------------------------------------*/
1773 * @brief This function handles DMA2 Stream 3 interrupt request.
1775 void SDIO_DMA_ST3_IRQHandler(dmaChannelDescriptor_t
*dma
)
1778 // Transfer Error Interrupt management
1779 if((DMA2
->LISR
& DMA_LISR_TEIF3
) != 0)
1781 if((DMA2_Stream3
->CR
& DMA_SxCR_TEIE
) != 0)
1783 DMA2_Stream3
->CR
&= ~DMA_SxCR_TEIE
; // Disable the transfer error interrupt
1784 DMA2
->LIFCR
= DMA_LIFCR_CTEIF3
; // Clear the transfer error flag
1788 // FIFO Error Interrupt management
1789 if((DMA2
->LISR
& DMA_LISR_FEIF3
) != 0)
1791 if((DMA2_Stream3
->FCR
& DMA_SxFCR_FEIE
) != 0)
1793 DMA2_Stream3
->FCR
&= ~DMA_SxFCR_FEIE
; // Disable the FIFO Error interrupt
1794 DMA2
->LIFCR
= DMA_LIFCR_CFEIF3
; // Clear the FIFO error flag
1798 // Direct Mode Error Interrupt management
1799 if((DMA2
->LISR
& DMA_LISR_DMEIF3
) != 0)
1801 if((DMA2_Stream3
->CR
& DMA_SxCR_DMEIE
) != 0)
1803 DMA2_Stream3
->CR
&= ~DMA_SxCR_DMEIE
; // Disable the direct mode Error interrupt
1804 DMA2
->LIFCR
= DMA_LIFCR_CDMEIF3
; // Clear the FIFO error flag
1808 // Half Transfer Complete Interrupt management
1809 if((DMA2
->LISR
& DMA_LISR_HTIF3
) != 0)
1811 if((DMA2_Stream3
->CR
& DMA_SxCR_HTIE
) != 0)
1813 if(((DMA2_Stream3
->CR
) & (uint32_t)(DMA_SxCR_DBM
)) != 0) // Multi_Buffering mode enabled
1815 DMA2
->LIFCR
= DMA_LIFCR_CHTIF3
; // Clear the half transfer complete flag
1819 if((DMA2_Stream3
->CR
& DMA_SxCR_CIRC
) == 0) // Disable the half transfer interrupt if the DMA mode is not CIRCULAR
1821 DMA2_Stream3
->CR
&= ~DMA_SxCR_HTIE
; // Disable the half transfer interrupt
1824 DMA2
->LIFCR
= DMA_LIFCR_CHTIF3
; // Clear the half transfer complete flag
1829 // Transfer Complete Interrupt management
1830 if((DMA2
->LISR
& DMA_LISR_TCIF3
) != 0)
1832 if((DMA2_Stream3
->CR
& DMA_SxCR_TCIE
) != 0)
1834 if((DMA2_Stream3
->CR
& (uint32_t)(DMA_SxCR_DBM
)) != 0)
1836 DMA2
->LIFCR
= DMA_LIFCR_CTCIF3
; // Clear the transfer complete flag
1838 else //Disable the transfer complete interrupt if the DMA mode is not CIRCULAR
1840 if((DMA2_Stream3
->CR
& DMA_SxCR_CIRC
) == 0)
1842 DMA2_Stream3
->CR
&= ~DMA_SxCR_TCIE
; // Disable the transfer complete interrupt
1845 DMA2
->LIFCR
= DMA_LIFCR_CTCIF3
; // Clear the transfer complete flag
1846 SD_DMA_Complete(DMA2_Stream3
);
1853 /** -----------------------------------------------------------------------------------------------------------------*/
1855 * @brief This function handles DMA2 Stream 6 interrupt request.
1857 void SDIO_DMA_ST6_IRQHandler(dmaChannelDescriptor_t
*dma
)
1860 // Transfer Error Interrupt management
1861 if((DMA2
->HISR
& DMA_HISR_TEIF6
) != 0)
1863 if((DMA2_Stream6
->CR
& DMA_SxCR_TEIE
) != 0)
1865 DMA2_Stream6
->CR
&= ~DMA_SxCR_TEIE
; // Disable the transfer error interrupt
1866 DMA2
->HIFCR
= DMA_HIFCR_CTEIF6
; // Clear the transfer error flag
1870 // FIFO Error Interrupt management
1871 if((DMA2
->HISR
& DMA_HISR_FEIF6
) != 0)
1873 if((DMA2_Stream6
->FCR
& DMA_SxFCR_FEIE
) != 0)
1875 DMA2_Stream6
->FCR
&= ~DMA_SxFCR_FEIE
; // Disable the FIFO Error interrupt
1876 DMA2
->HIFCR
= DMA_HIFCR_CFEIF6
; // Clear the FIFO error flag
1880 // Direct Mode Error Interrupt management
1881 if((DMA2
->HISR
& DMA_HISR_DMEIF6
) != 0)
1883 if((DMA2_Stream6
->CR
& DMA_SxCR_DMEIE
) != 0)
1885 DMA2_Stream6
->CR
&= ~DMA_SxCR_DMEIE
; // Disable the direct mode Error interrupt
1886 DMA2
->HIFCR
= DMA_HIFCR_CDMEIF6
; // Clear the FIFO error flag
1890 // Half Transfer Complete Interrupt management
1891 if((DMA2
->HISR
& DMA_HISR_HTIF6
) != 0)
1893 if((DMA2_Stream6
->CR
& DMA_SxCR_HTIE
) != 0)
1895 if(((DMA2_Stream6
->CR
) & (uint32_t)(DMA_SxCR_DBM
)) != 0) // Multi_Buffering mode enabled
1897 DMA2
->HIFCR
= DMA_HIFCR_CHTIF6
; // Clear the half transfer complete flag
1901 if((DMA2_Stream6
->CR
& DMA_SxCR_CIRC
) == 0) // Disable the half transfer interrupt if the DMA mode is not CIRCULAR
1903 DMA2_Stream6
->CR
&= ~DMA_SxCR_HTIE
; // Disable the half transfer interrupt
1906 DMA2
->HIFCR
= DMA_HIFCR_CHTIF6
; // Clear the half transfer complete flag
1911 // Transfer Complete Interrupt management
1912 if((DMA2
->HISR
& DMA_HISR_TCIF6
) != 0)
1914 if((DMA2_Stream6
->CR
& DMA_SxCR_TCIE
) != 0)
1916 if((DMA2_Stream6
->CR
& (uint32_t)(DMA_SxCR_DBM
)) != 0)
1918 DMA2
->HIFCR
= DMA_HIFCR_CTCIF6
; // Clear the transfer complete flag
1920 else //Disable the transfer complete interrupt if the DMA mode is not CIRCULAR
1922 if((DMA2_Stream6
->CR
& DMA_SxCR_CIRC
) == 0)
1924 DMA2_Stream6
->CR
&= ~DMA_SxCR_TCIE
; // Disable the transfer complete interrupt
1927 DMA2
->HIFCR
= DMA_HIFCR_CTCIF6
; // Clear the transfer complete flag
1928 SD_DMA_Complete(DMA2_Stream6
);
1934 /* ------------------------------------------------------------------------------------------------------------------*/