Merge pull request #11297 from SteveCEvans/baro_state
[betaflight.git] / src / main / drivers / sdio_f4xx.c
blob1a6bf8ed955050a912cd02f345eae7c3a7bcc139
1 /*
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)
8 * any later version.
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) -------------------------------------------------------------------------------------------------------*/
31 #include "stdbool.h"
32 #include <string.h>
34 #include "platform.h"
36 #ifdef USE_SDCARD_SDIO
38 #include "sdmmc_sdio.h"
39 #include "stm32f4xx_gpio.h"
41 #include "pg/sdio.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 |\
76 SDIO_ICR_DBCKENDC))
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) -------------------------------------------------------------------------------------------------------*/
202 typedef enum
204 SD_SINGLE_BLOCK = 0, // Single block operation
205 SD_MULTIPLE_BLOCK = 1, // Multiple blocks operation
206 } SD_Operation_t;
209 typedef struct
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)
218 } SD_Handle_t;
220 typedef enum
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
231 } SD_CardState_t;
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 /** -----------------------------------------------------------------------------------------------------------------*/
264 /** DataTransferInit
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)
272 uint32_t Direction;
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);
278 return;
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
302 return ErrorState;
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;
318 uint32_t TimeOut;
319 uint32_t Flag;
321 if(ResponseType == -1) {
322 Flag = SDIO_STA_CMDSENT;
323 } else {
324 Flag = SDIO_STA_CCRCFAIL | SDIO_STA_CMDREND | SDIO_STA_CTIMEOUT;
327 TimeOut = SD_SOFTWARE_COMMAND_TIMEOUT;
330 SD_Status = SDIO->STA;
331 TimeOut--;
333 while(((SD_Status & Flag) == 0) && (TimeOut > 0));
335 if(ResponseType <= 0)
337 if(TimeOut == 0) {
338 return SD_CMD_RSP_TIMEOUT;
339 } else {
340 return SD_OK;
344 if((SDIO->STA & SDIO_STA_CTIMEOUT) != 0) {
345 return SD_CMD_RSP_TIMEOUT;
347 if(ResponseType == 3)
349 if(TimeOut == 0) {
350 return SD_CMD_RSP_TIMEOUT; // Card is not V2.0 compliant or card does not support the set voltage range
351 } else {
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) {
360 return SD_OK;
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;
389 return SD_OK;
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;
422 return SD_OK;
426 /** -----------------------------------------------------------------------------------------------------------------*/
427 /** GetResponse
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;
461 /* Clear flag */
462 SD_Handle.RXCplt = 0;
464 /* Disable the stream */
465 pDMA_Stream->CR &= ~DMA_SxCR_EN;
466 } else {
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)
490 return ErrorState;
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)
504 return ErrorState;
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);
518 else
520 ErrorState = SD_REQUEST_NOT_APPLICABLE;
523 return ErrorState;
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;
546 SDIO->MASK = 0;
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);
550 } else {
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
563 } else {
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
569 } else {
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;
598 uint32_t CmdIndex;
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)
605 ReadAddress *= 512;
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;
620 do {
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;
634 return 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;
654 uint32_t CmdIndex;
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)
661 WriteAddress *= 512;
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;
671 do {
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;
680 return ErrorState;
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;
690 return ErrorState;
693 SD_Error_t SD_CheckWrite(void) {
694 if (SD_Handle.TXCplt != 0) return SD_BUSY;
695 return SD_OK;
698 SD_Error_t SD_CheckRead(void) {
699 if (SD_Handle.RXCplt != 0) return SD_BUSY;
700 return SD_OK;
703 /** -----------------------------------------------------------------------------------------------------------------*/
705 * @brief This function waits until the SD DMA data wirte or read transfer is finished.
706 * This should be called after WriteBlocks_DMA or SD_ReadBlocks_DMA() function
707 * to insure that all data sent is already transferred by the DMA controller.
708 * @retval SD Card error state
711 SD_Error_t SD_CheckOperation(uint32_t Flag)
713 SD_Error_t ErrorState = SD_OK;
714 uint32_t TimeOut;
715 uint32_t Temp1;
716 uint32_t Temp2;
717 SD_Error_t Temp3;
719 // Wait for DMA/SD transfer end or SD error variables to be in SD handle
720 Temp1 = SD_Handle.DMA_XferComplete;
721 Temp2 = SD_Handle.TransferComplete;
722 Temp3 = (SD_Error_t)SD_Handle.TransferError;
724 if (((Temp1 & Temp2) == 0) && (Temp3 == SD_OK) && (TimeOut > 0))
726 Temp1 = SD_Handle.DMA_XferComplete;
727 Temp2 = SD_Handle.TransferComplete;
728 Temp3 = (SD_Error_t)SD_Handle.TransferError;
729 TimeOut--;
730 return SD_BUSY;
733 // Wait until the Rx transfer is no longer active
734 if (((SDIO->STA & Flag) != 0) && (TimeOut > 0))
736 TimeOut--;
737 return SD_BUSY;
740 // Send stop command in multi block read
741 if(SD_Handle.Operation & 0x01 == SD_MULTIPLE_BLOCK)
743 ErrorState = SD_TransmitCommand((SD_CMD_STOP_TRANSMISSION | SD_CMD_RESPONSE_SHORT), 0, 1);
746 if((TimeOut == 0) && (ErrorState == SD_OK))
748 ErrorState = SD_DATA_TIMEOUT;
751 // Return error state
752 if(SD_Handle.TransferError != SD_OK)
754 return (SD_Error_t)(SD_Handle.TransferError);
757 return ErrorState;
761 /** -----------------------------------------------------------------------------------------------------------------*/
763 * @brief Erases the specified memory area of the given SD card.
764 * @param StartAddress: Start byte address
765 * @param EndAddress: End byte address
766 * @retval SD Card error state
769 SD_Error_t SD_Erase(uint64_t StartAddress, uint64_t EndAddress)
771 SD_Error_t ErrorState;
772 uint32_t Delay;
773 uint32_t MaxDelay;
774 uint8_t CardState;
776 // Check if the card command class supports erase command
777 if(((SD_Handle.CSD[1] >> 20) & SD_CCCC_ERASE) == 0)
779 return SD_REQUEST_NOT_APPLICABLE;
782 // Get max delay value
783 MaxDelay = 120000 / (((SDIO->CLKCR) & 0xFF) + 2);
785 if((SDIO->RESP1 & SD_CARD_LOCKED) == SD_CARD_LOCKED)
787 return SD_LOCK_UNLOCK_FAILED;
790 // Get start and end block for high capacity cards
791 if(SD_CardType == SD_HIGH_CAPACITY)
793 StartAddress /= 512;
794 EndAddress /= 512;
797 // According to sd-card spec 1.0 ERASE_GROUP_START (CMD32) and erase_group_end(CMD33)
798 if ((SD_CardType == SD_STD_CAPACITY_V1_1) || (SD_CardType == SD_STD_CAPACITY_V2_0) ||
799 (SD_CardType == SD_HIGH_CAPACITY))
801 // Send CMD32 SD_ERASE_GRP_START with argument as addr
802 if((ErrorState = SD_TransmitCommand((SD_CMD_SD_ERASE_GRP_START | SDIO_CMD_RESPONSE_SHORT), (uint32_t)StartAddress, 1)) != SD_OK)
804 return ErrorState;
807 // Send CMD33 SD_ERASE_GRP_END with argument as addr
808 if((ErrorState = SD_TransmitCommand((SD_CMD_SD_ERASE_GRP_END | SDIO_CMD_RESPONSE_SHORT), (uint32_t)EndAddress, 1)) != SD_OK)
810 return ErrorState;
814 // Send CMD38 ERASE
815 if((ErrorState = SD_TransmitCommand((SD_CMD_ERASE | SDIO_CMD_RESPONSE_SHORT), 0, 1)) != SD_OK)
817 return ErrorState;
820 for(Delay = 0; Delay < MaxDelay; Delay++);
822 // Wait until the card is in programming state
823 ErrorState = SD_IsCardProgramming(&CardState);
825 Delay = SD_DATATIMEOUT;
826 while((Delay > 0) && (ErrorState == SD_OK) && ((CardState == SD_CARD_PROGRAMMING) || (CardState == SD_CARD_RECEIVING)))
828 ErrorState = SD_IsCardProgramming( &CardState);
829 Delay--;
832 return ErrorState;
837 /** -----------------------------------------------------------------------------------------------------------------*/
839 * @brief Returns information about specific card.
840 * contains all SD cardinformation
841 * @retval SD Card error state
843 SD_Error_t SD_GetCardInfo(void)
845 SD_Error_t ErrorState = SD_OK;
846 uint32_t Temp = 0;
848 // Byte 0
849 Temp = (SD_Handle.CSD[0] & 0xFF000000) >> 24;
850 SD_CardInfo.SD_csd.CSDStruct = (uint8_t)((Temp & 0xC0) >> 6);
851 SD_CardInfo.SD_csd.SysSpecVersion = (uint8_t)((Temp & 0x3C) >> 2);
852 SD_CardInfo.SD_csd.Reserved1 = Temp & 0x03;
854 // Byte 1
855 Temp = (SD_Handle.CSD[0] & 0x00FF0000) >> 16;
856 SD_CardInfo.SD_csd.TAAC = (uint8_t)Temp;
858 // Byte 2
859 Temp = (SD_Handle.CSD[0] & 0x0000FF00) >> 8;
860 SD_CardInfo.SD_csd.NSAC = (uint8_t)Temp;
862 // Byte 3
863 Temp = SD_Handle.CSD[0] & 0x000000FF;
864 SD_CardInfo.SD_csd.MaxBusClkFrec = (uint8_t)Temp;
866 // Byte 4
867 Temp = (SD_Handle.CSD[1] & 0xFF000000) >> 24;
868 SD_CardInfo.SD_csd.CardComdClasses = (uint16_t)(Temp << 4);
870 // Byte 5
871 Temp = (SD_Handle.CSD[1] & 0x00FF0000) >> 16;
872 SD_CardInfo.SD_csd.CardComdClasses |= (uint16_t)((Temp & 0xF0) >> 4);
873 SD_CardInfo.SD_csd.RdBlockLen = (uint8_t)(Temp & 0x0F);
875 // Byte 6
876 Temp = (SD_Handle.CSD[1] & 0x0000FF00) >> 8;
877 SD_CardInfo.SD_csd.PartBlockRead = (uint8_t)((Temp & 0x80) >> 7);
878 SD_CardInfo.SD_csd.WrBlockMisalign = (uint8_t)((Temp & 0x40) >> 6);
879 SD_CardInfo.SD_csd.RdBlockMisalign = (uint8_t)((Temp & 0x20) >> 5);
880 SD_CardInfo.SD_csd.DSRImpl = (uint8_t)((Temp & 0x10) >> 4);
881 SD_CardInfo.SD_csd.Reserved2 = 0; /*!< Reserved */
883 if((SD_CardType == SD_STD_CAPACITY_V1_1) || (SD_CardType == SD_STD_CAPACITY_V2_0))
885 SD_CardInfo.SD_csd.DeviceSize = (Temp & 0x03) << 10;
887 // Byte 7
888 Temp = (uint8_t)(SD_Handle.CSD[1] & 0x000000FF);
889 SD_CardInfo.SD_csd.DeviceSize |= (Temp) << 2;
891 // Byte 8
892 Temp = (uint8_t)((SD_Handle.CSD[2] & 0xFF000000) >> 24);
893 SD_CardInfo.SD_csd.DeviceSize |= (Temp & 0xC0) >> 6;
895 SD_CardInfo.SD_csd.MaxRdCurrentVDDMin = (Temp & 0x38) >> 3;
896 SD_CardInfo.SD_csd.MaxRdCurrentVDDMax = (Temp & 0x07);
898 // Byte 9
899 Temp = (uint8_t)((SD_Handle.CSD[2] & 0x00FF0000) >> 16);
900 SD_CardInfo.SD_csd.MaxWrCurrentVDDMin = (Temp & 0xE0) >> 5;
901 SD_CardInfo.SD_csd.MaxWrCurrentVDDMax = (Temp & 0x1C) >> 2;
902 SD_CardInfo.SD_csd.DeviceSizeMul = (Temp & 0x03) << 1;
904 // Byte 10
905 Temp = (uint8_t)((SD_Handle.CSD[2] & 0x0000FF00) >> 8);
906 SD_CardInfo.SD_csd.DeviceSizeMul |= (Temp & 0x80) >> 7;
908 SD_CardInfo.CardCapacity = (SD_CardInfo.SD_csd.DeviceSize + 1) ;
909 SD_CardInfo.CardCapacity *= (1 << (SD_CardInfo.SD_csd.DeviceSizeMul + 2));
910 SD_CardInfo.CardBlockSize = 1 << (SD_CardInfo.SD_csd.RdBlockLen);
911 SD_CardInfo.CardCapacity = SD_CardInfo.CardCapacity * SD_CardInfo.CardBlockSize / 512; // In 512 byte blocks
913 else if(SD_CardType == SD_HIGH_CAPACITY)
915 // Byte 7
916 Temp = (uint8_t)(SD_Handle.CSD[1] & 0x000000FF);
917 SD_CardInfo.SD_csd.DeviceSize = (Temp & 0x3F) << 16;
919 // Byte 8
920 Temp = (uint8_t)((SD_Handle.CSD[2] & 0xFF000000) >> 24);
922 SD_CardInfo.SD_csd.DeviceSize |= (Temp << 8);
924 // Byte 9
925 Temp = (uint8_t)((SD_Handle.CSD[2] & 0x00FF0000) >> 16);
927 SD_CardInfo.SD_csd.DeviceSize |= (Temp);
929 // Byte 10
930 Temp = (uint8_t)((SD_Handle.CSD[2] & 0x0000FF00) >> 8);
932 SD_CardInfo.CardCapacity = ((uint64_t)SD_CardInfo.SD_csd.DeviceSize + 1) * 1024;
933 SD_CardInfo.CardBlockSize = 512;
935 else
937 // Not supported card type
938 ErrorState = SD_ERROR;
941 SD_CardInfo.SD_csd.EraseGrSize = (Temp & 0x40) >> 6;
942 SD_CardInfo.SD_csd.EraseGrMul = (Temp & 0x3F) << 1;
944 // Byte 11
945 Temp = (uint8_t)(SD_Handle.CSD[2] & 0x000000FF);
946 SD_CardInfo.SD_csd.EraseGrMul |= (Temp & 0x80) >> 7;
947 SD_CardInfo.SD_csd.WrProtectGrSize = (Temp & 0x7F);
949 // Byte 12
950 Temp = (uint8_t)((SD_Handle.CSD[3] & 0xFF000000) >> 24);
951 SD_CardInfo.SD_csd.WrProtectGrEnable = (Temp & 0x80) >> 7;
952 SD_CardInfo.SD_csd.ManDeflECC = (Temp & 0x60) >> 5;
953 SD_CardInfo.SD_csd.WrSpeedFact = (Temp & 0x1C) >> 2;
954 SD_CardInfo.SD_csd.MaxWrBlockLen = (Temp & 0x03) << 2;
956 // Byte 13
957 Temp = (uint8_t)((SD_Handle.CSD[3] & 0x00FF0000) >> 16);
958 SD_CardInfo.SD_csd.MaxWrBlockLen |= (Temp & 0xC0) >> 6;
959 SD_CardInfo.SD_csd.WriteBlockPaPartial = (Temp & 0x20) >> 5;
960 SD_CardInfo.SD_csd.Reserved3 = 0;
961 SD_CardInfo.SD_csd.ContentProtectAppli = (Temp & 0x01);
963 // Byte 14
964 Temp = (uint8_t)((SD_Handle.CSD[3] & 0x0000FF00) >> 8);
965 SD_CardInfo.SD_csd.FileFormatGrouop = (Temp & 0x80) >> 7;
966 SD_CardInfo.SD_csd.CopyFlag = (Temp & 0x40) >> 6;
967 SD_CardInfo.SD_csd.PermWrProtect = (Temp & 0x20) >> 5;
968 SD_CardInfo.SD_csd.TempWrProtect = (Temp & 0x10) >> 4;
969 SD_CardInfo.SD_csd.FileFormat = (Temp & 0x0C) >> 2;
970 SD_CardInfo.SD_csd.ECC = (Temp & 0x03);
972 // Byte 15
973 Temp = (uint8_t)(SD_Handle.CSD[3] & 0x000000FF);
974 SD_CardInfo.SD_csd.CSD_CRC = (Temp & 0xFE) >> 1;
975 SD_CardInfo.SD_csd.Reserved4 = 1;
977 // Byte 0
978 Temp = (uint8_t)((SD_Handle.CID[0] & 0xFF000000) >> 24);
979 SD_CardInfo.SD_cid.ManufacturerID = Temp;
981 // Byte 1
982 Temp = (uint8_t)((SD_Handle.CID[0] & 0x00FF0000) >> 16);
983 SD_CardInfo.SD_cid.OEM_AppliID = Temp << 8;
985 // Byte 2
986 Temp = (uint8_t)((SD_Handle.CID[0] & 0x000000FF00) >> 8);
987 SD_CardInfo.SD_cid.OEM_AppliID |= Temp;
989 // Byte 3
990 Temp = (uint8_t)(SD_Handle.CID[0] & 0x000000FF);
991 SD_CardInfo.SD_cid.ProdName1 = Temp << 24;
993 // Byte 4
994 Temp = (uint8_t)((SD_Handle.CID[1] & 0xFF000000) >> 24);
995 SD_CardInfo.SD_cid.ProdName1 |= Temp << 16;
997 // Byte 5
998 Temp = (uint8_t)((SD_Handle.CID[1] & 0x00FF0000) >> 16);
999 SD_CardInfo.SD_cid.ProdName1 |= Temp << 8;
1001 // Byte 6
1002 Temp = (uint8_t)((SD_Handle.CID[1] & 0x0000FF00) >> 8);
1003 SD_CardInfo.SD_cid.ProdName1 |= Temp;
1005 // Byte 7
1006 Temp = (uint8_t)(SD_Handle.CID[1] & 0x000000FF);
1007 SD_CardInfo.SD_cid.ProdName2 = Temp;
1009 // Byte 8
1010 Temp = (uint8_t)((SD_Handle.CID[2] & 0xFF000000) >> 24);
1011 SD_CardInfo.SD_cid.ProdRev = Temp;
1013 // Byte 9
1014 Temp = (uint8_t)((SD_Handle.CID[2] & 0x00FF0000) >> 16);
1015 SD_CardInfo.SD_cid.ProdSN = Temp << 24;
1017 // Byte 10
1018 Temp = (uint8_t)((SD_Handle.CID[2] & 0x0000FF00) >> 8);
1019 SD_CardInfo.SD_cid.ProdSN |= Temp << 16;
1021 // Byte 11
1022 Temp = (uint8_t)(SD_Handle.CID[2] & 0x000000FF);
1023 SD_CardInfo.SD_cid.ProdSN |= Temp << 8;
1025 // Byte 12
1026 Temp = (uint8_t)((SD_Handle.CID[3] & 0xFF000000) >> 24);
1027 SD_CardInfo.SD_cid.ProdSN |= Temp;
1029 // Byte 13
1030 Temp = (uint8_t)((SD_Handle.CID[3] & 0x00FF0000) >> 16);
1031 SD_CardInfo.SD_cid.Reserved1 |= (Temp & 0xF0) >> 4;
1032 SD_CardInfo.SD_cid.ManufactDate = (Temp & 0x0F) << 8;
1034 // Byte 14
1035 Temp = (uint8_t)((SD_Handle.CID[3] & 0x0000FF00) >> 8);
1036 SD_CardInfo.SD_cid.ManufactDate |= Temp;
1038 // Byte 15
1039 Temp = (uint8_t)(SD_Handle.CID[3] & 0x000000FF);
1040 SD_CardInfo.SD_cid.CID_CRC = (Temp & 0xFE) >> 1;
1041 SD_CardInfo.SD_cid.Reserved2 = 1;
1043 return ErrorState;
1047 /** -----------------------------------------------------------------------------------------------------------------*/
1049 * @brief Enables wide bus operation for the requested card if supported by
1050 * card.
1051 * @param WideMode: Specifies the SD card wide bus mode
1052 * This parameter can be one of the following values:
1053 * @arg SD_BUS_WIDE_8B: 8-bit data transfer (Only for MMC)
1054 * @arg SD_BUS_WIDE_4B: 4-bit data transfer
1055 * @arg SD_BUS_WIDE_1B: 1-bit data transfer
1056 * @retval SD Card error state
1058 static SD_Error_t SD_WideBusOperationConfig(uint32_t WideMode)
1060 SD_Error_t ErrorState = SD_OK;
1061 uint32_t Temp;
1062 uint32_t SCR[2] = {0, 0};
1064 if((SD_CardType == SD_STD_CAPACITY_V1_1) || (SD_CardType == SD_STD_CAPACITY_V2_0) ||\
1065 (SD_CardType == SD_HIGH_CAPACITY))
1067 if(WideMode == SD_BUS_WIDE_8B)
1069 ErrorState = SD_UNSUPPORTED_FEATURE;
1071 else if((WideMode == SD_BUS_WIDE_4B) ||
1072 (WideMode == SD_BUS_WIDE_1B))
1074 if((SDIO->RESP1 & SD_CARD_LOCKED) != SD_CARD_LOCKED)
1076 // Get SCR Register
1077 ErrorState = SD_FindSCR(SCR);
1078 if(ErrorState == SD_OK)
1080 Temp = (WideMode == SD_BUS_WIDE_4B) ? SD_WIDE_BUS_SUPPORT : SD_SINGLE_BUS_SUPPORT;
1082 // If requested card supports wide bus operation
1083 if((SCR[1] & Temp) != SD_ALLZERO)
1085 // Send CMD55 APP_CMD with argument as card's RCA.
1086 ErrorState = SD_TransmitCommand((SD_CMD_APP_CMD | SD_CMD_RESPONSE_SHORT), SD_CardRCA, 1);
1087 if(ErrorState == SD_OK)
1089 Temp = (WideMode == SD_BUS_WIDE_4B) ? 2 : 0;
1091 // Send ACMD6 APP_CMD with argument as 2 for wide bus mode
1092 ErrorState = SD_TransmitCommand((SD_CMD_APP_SD_SET_BUSWIDTH | SD_CMD_RESPONSE_SHORT), Temp, 1);
1095 else
1097 ErrorState = SD_REQUEST_NOT_APPLICABLE;
1101 else
1103 ErrorState = SD_LOCK_UNLOCK_FAILED;
1106 else
1108 ErrorState = SD_INVALID_PARAMETER; // WideMode is not a valid argument
1111 if(ErrorState == SD_OK)
1113 // Configure the SDIO peripheral, we need this delay for some reason...
1114 while ((READ_REG(SDIO->CLKCR) & 0x800) != WideMode) {
1115 MODIFY_REG(SDIO->CLKCR, CLKCR_CLEAR_MASK, (uint32_t) WideMode);
1119 else {
1120 ErrorState = SD_UNSUPPORTED_FEATURE;
1124 return ErrorState;
1128 /** -----------------------------------------------------------------------------------------------------------------*/
1130 * @brief Switches the SD card to High Speed mode.
1131 * This API must be used after "Transfer State"
1132 * @retval SD Card error state
1134 SD_Error_t SD_HighSpeed(void)
1136 SD_Error_t ErrorState;
1137 uint8_t SD_hs[64] = {0};
1138 uint32_t SD_scr[2] = {0, 0};
1139 uint32_t SD_SPEC = 0;
1140 uint32_t Count = 0;
1141 uint32_t* Buffer = (uint32_t *)SD_hs;
1143 // Initialize the Data control register
1144 SDIO->DCTRL = 0;
1146 // Get SCR Register
1147 if((ErrorState = SD_FindSCR(SD_scr)) != SD_OK)
1149 return ErrorState;
1152 // Test the Version supported by the card
1153 SD_SPEC = (SD_scr[1] & 0x01000000) | (SD_scr[1] & 0x02000000);
1155 if(SD_SPEC != SD_ALLZERO)
1157 // Set Block Size for Card
1158 if((ErrorState = SD_TransmitCommand((SD_CMD_SET_BLOCKLEN | SD_CMD_RESPONSE_SHORT), 64, 1)) != SD_OK)
1160 return ErrorState;
1163 // Configure the SD DPSM (Data Path State Machine)
1164 SD_DataTransferInit(64, SD_DATABLOCK_SIZE_64B, true);
1166 // Send CMD6 switch mode
1167 if((ErrorState =SD_TransmitCommand((SD_CMD_HS_SWITCH | SD_CMD_RESPONSE_SHORT), 0x80FFFF01, 1)) != SD_OK)
1169 return ErrorState;
1172 while((SDIO->STA & (SDIO_STA_RXOVERR | SDIO_STA_DCRCFAIL | SDIO_STA_DTIMEOUT | SDIO_STA_DBCKEND)) == 0)
1174 if((SDIO->STA & SDIO_STA_RXFIFOHF) != 0)
1176 for(Count = 0; Count < 8; Count++)
1178 *(Buffer + Count) = SDIO->FIFO;
1181 Buffer += 8;
1185 if((SDIO->STA & SDIO_STA_DTIMEOUT) != 0) return SD_DATA_TIMEOUT;
1186 else if((SDIO->STA & SDIO_STA_DCRCFAIL) != 0) return SD_DATA_CRC_FAIL;
1187 else if((SDIO->STA & SDIO_STA_RXOVERR) != 0) return SD_RX_OVERRUN;
1189 Count = SD_DATATIMEOUT;
1191 while(((SDIO->STA & SDIO_STA_RXDAVL) != 0) && (Count > 0))
1193 *Buffer = SDIO->FIFO;
1194 Buffer++;
1195 Count--;
1198 // Test if the switch mode HS is ok
1199 if((SD_hs[13] & 2) != 2)
1201 ErrorState = SD_UNSUPPORTED_FEATURE;
1205 return ErrorState;
1209 /** -----------------------------------------------------------------------------------------------------------------*/
1211 * @brief Gets the current card's data status.
1212 * @retval Data Transfer state
1214 SD_Error_t SD_GetStatus(void)
1216 SD_Error_t ErrorState;
1217 uint32_t Response1;
1218 SD_CardState_t CardState;
1221 // Send Status command
1222 if((ErrorState = SD_TransmitCommand((SD_CMD_SEND_STATUS | SD_CMD_RESPONSE_SHORT), SD_CardRCA, 1)) == SD_OK)
1224 Response1 = SDIO->RESP1;
1225 CardState = (SD_CardState_t)((Response1 >> 9) & 0x0F);
1227 // Find SD status according to card state
1228 if (CardState == SD_CARD_TRANSFER) ErrorState = SD_OK;
1229 else if(CardState == SD_CARD_ERROR) ErrorState = SD_ERROR;
1230 else ErrorState = SD_BUSY;
1232 else
1234 ErrorState = SD_CARD_ERROR;
1237 return ErrorState;
1241 /** -----------------------------------------------------------------------------------------------------------------*/
1243 * @brief Gets the SD card status.
1244 * @retval SD Card error state
1246 SD_Error_t SD_GetCardStatus(SD_CardStatus_t* pCardStatus)
1248 SD_Error_t ErrorState;
1249 uint32_t Temp = 0;
1250 uint32_t Status[16];
1251 uint32_t Count;
1253 // Check SD response
1254 if((SDIO->RESP1 & SD_CARD_LOCKED) == SD_CARD_LOCKED)
1256 return SD_LOCK_UNLOCK_FAILED;
1259 // Set block size for card if it is not equal to current block size for card
1260 if((ErrorState = SD_TransmitCommand((SD_CMD_SET_BLOCKLEN | SD_CMD_RESPONSE_SHORT), 64, 1)) != SD_OK)
1262 return ErrorState;
1265 // Send CMD55
1266 if((ErrorState = SD_TransmitCommand((SD_CMD_APP_CMD | SD_CMD_RESPONSE_SHORT), SD_CardRCA, 1)) != SD_OK)
1268 return ErrorState;
1271 // Configure the SD DPSM (Data Path State Machine)
1272 SD_DataTransferInit(64, SD_DATABLOCK_SIZE_64B, true);
1274 // Send ACMD13 (SD_APP_STAUS) with argument as card's RCA
1275 if((ErrorState = SD_TransmitCommand((SD_CMD_SD_APP_STATUS | SD_CMD_RESPONSE_SHORT), 0, 1)) != SD_OK)
1277 return ErrorState;
1280 // Get status data
1281 while((SDIO->STA & (SDIO_STA_RXOVERR | SDIO_STA_DCRCFAIL | SDIO_STA_DTIMEOUT | SDIO_STA_DBCKEND)) == 0)
1283 if((SDIO->STA & SDIO_STA_RXFIFOHF) != 0)
1285 for(Count = 0; Count < 8; Count++)
1287 Status[Count] = SDIO->FIFO;
1292 if((SDIO->STA & SDIO_STA_DTIMEOUT) != 0) return SD_DATA_TIMEOUT;
1293 else if((SDIO->STA & SDIO_STA_DCRCFAIL) != 0) return SD_DATA_CRC_FAIL;
1294 else if((SDIO->STA & SDIO_STA_RXOVERR) != 0) return SD_RX_OVERRUN;
1295 else
1298 this part from the HAL is very strange has it is possible to overflow the provide buffer... and this originate from ST HAL
1300 Count = SD_DATATIMEOUT;
1301 while(((SDIO->STA & SDIO_STA_RXDAVL) != 0) && (Count > 0))
1303 *pSDstatus = SDIO->FIFO;
1304 pSDstatus++;
1305 Count--;
1310 // Byte 0
1311 Temp = (Status[0] & 0xC0) >> 6;
1312 pCardStatus->DAT_BUS_WIDTH = (uint8_t)Temp;
1314 // Byte 0
1315 Temp = (Status[0] & 0x20) >> 5;
1316 pCardStatus->SECURED_MODE = (uint8_t)Temp;
1318 // Byte 2
1319 Temp = (Status[2] & 0xFF);
1320 pCardStatus->SD_CARD_TYPE = (uint8_t)(Temp << 8);
1322 // Byte 3
1323 Temp = (Status[3] & 0xFF);
1324 pCardStatus->SD_CARD_TYPE |= (uint8_t)Temp;
1326 // Byte 4
1327 Temp = (Status[4] & 0xFF);
1328 pCardStatus->SIZE_OF_PROTECTED_AREA = (uint8_t)(Temp << 24);
1330 // Byte 5
1331 Temp = (Status[5] & 0xFF);
1332 pCardStatus->SIZE_OF_PROTECTED_AREA |= (uint8_t)(Temp << 16);
1334 // Byte 6
1335 Temp = (Status[6] & 0xFF);
1336 pCardStatus->SIZE_OF_PROTECTED_AREA |= (uint8_t)(Temp << 8);
1338 // Byte 7
1339 Temp = (Status[7] & 0xFF);
1340 pCardStatus->SIZE_OF_PROTECTED_AREA |= (uint8_t)Temp;
1342 // Byte 8
1343 Temp = (Status[8] & 0xFF);
1344 pCardStatus->SPEED_CLASS = (uint8_t)Temp;
1346 // Byte 9
1347 Temp = (Status[9] & 0xFF);
1348 pCardStatus->PERFORMANCE_MOVE = (uint8_t)Temp;
1350 // Byte 10
1351 Temp = (Status[10] & 0xF0) >> 4;
1352 pCardStatus->AU_SIZE = (uint8_t)Temp;
1354 // Byte 11
1355 Temp = (Status[11] & 0xFF);
1356 pCardStatus->ERASE_SIZE = (uint8_t)(Temp << 8);
1358 // Byte 12
1359 Temp = (Status[12] & 0xFF);
1360 pCardStatus->ERASE_SIZE |= (uint8_t)Temp;
1362 // Byte 13
1363 Temp = (Status[13] & 0xFC) >> 2;
1364 pCardStatus->ERASE_TIMEOUT = (uint8_t)Temp;
1366 // Byte 13
1367 Temp = (Status[13] & 0x3);
1368 pCardStatus->ERASE_OFFSET = (uint8_t)Temp;
1370 return SD_OK;
1374 /** -----------------------------------------------------------------------------------------------------------------*/
1376 * @brief Enquires cards about their operating voltage and configures clock
1377 * controls and stores SD information that will be needed in future
1378 * in the SD handle.
1379 * @retval SD Card error state
1381 static SD_Error_t SD_PowerON(void)
1383 SD_Error_t ErrorState;
1384 uint32_t Response;
1385 uint32_t Count;
1386 uint32_t ValidVoltage;
1387 uint32_t SD_Type;
1388 //uint32_t TickStart;
1390 Count = 0;
1391 ValidVoltage = 0;
1392 SD_Type = SD_RESP_STD_CAPACITY;
1394 // Power ON Sequence -------------------------------------------------------
1395 SDIO->CLKCR &= ~SDIO_CLKCR_CLKEN; // Disable SDIO Clock
1396 SDIO->POWER = SDIO_POWER_PWRCTRL; // Set Power State to ON
1398 // 1ms: required power up waiting time before starting the SD initialization sequence (make it 2 to be safe)
1399 delay(2);
1401 SDIO->CLKCR |= SDIO_CLKCR_CLKEN; // Enable SDIO Clock
1403 // CMD0: GO_IDLE_STATE -----------------------------------------------------
1404 // No CMD response required
1405 if((ErrorState = SD_TransmitCommand(SD_CMD_GO_IDLE_STATE, 0, 0)) != SD_OK)
1407 // CMD Response Timeout (wait for CMDSENT flag)
1408 return ErrorState;
1411 // CMD8: SEND_IF_COND ------------------------------------------------------
1412 // Send CMD8 to verify SD card interface operating condition
1413 // Argument: - [31:12]: Reserved (shall be set to '0')
1414 //- [11:8]: Supply Voltage (VHS) 0x1 (Range: 2.7-3.6 V)
1415 //- [7:0]: Check Pattern (recommended 0xAA)
1416 // CMD Response: R7 */
1417 if((ErrorState = SD_TransmitCommand((SD_SDIO_SEND_IF_COND | SD_CMD_RESPONSE_SHORT), SD_CHECK_PATTERN, 7)) == SD_OK)
1419 // SD Card 2.0
1420 SD_CardType = SD_STD_CAPACITY_V2_0;
1421 SD_Type = SD_RESP_HIGH_CAPACITY;
1424 // Send CMD55
1425 // If ErrorState is Command Timeout, it is a MMC card
1426 // If ErrorState is SD_OK it is a SD card: SD card 2.0 (voltage range mismatch) or SD card 1.x
1427 if((ErrorState = SD_TransmitCommand((SD_CMD_APP_CMD | SD_CMD_RESPONSE_SHORT), 0, 1)) == SD_OK)
1429 // SD CARD
1430 // Send ACMD41 SD_APP_OP_COND with Argument 0x80100000
1431 while((ValidVoltage == 0) && (Count < SD_MAX_VOLT_TRIAL))
1433 // SEND CMD55 APP_CMD with RCA as 0
1434 if((ErrorState = SD_TransmitCommand((SD_CMD_APP_CMD | SD_CMD_RESPONSE_SHORT), 0, 1)) != SD_OK)
1436 return ErrorState;
1439 // Send CMD41
1440 if((ErrorState = SD_TransmitCommand((SD_CMD_SD_APP_OP_COND | SD_CMD_RESPONSE_SHORT), SD_VOLTAGE_WINDOW_SD | SD_Type, 3)) != SD_OK)
1442 return ErrorState;
1445 Response = SDIO->RESP1; // Get command response
1446 ValidVoltage = (((Response >> 31) == 1) ? 1 : 0); // Get operating voltage
1447 Count++;
1450 if(Count >= SD_MAX_VOLT_TRIAL)
1452 return SD_INVALID_VOLTRANGE;
1455 if((Response & SD_RESP_HIGH_CAPACITY) == SD_RESP_HIGH_CAPACITY)
1457 SD_CardType = SD_HIGH_CAPACITY;
1459 } // else MMC Card
1461 return ErrorState;
1465 /** -----------------------------------------------------------------------------------------------------------------*/
1467 * @brief Turns the SDIO output signals off.
1468 * @retval SD Card error state
1470 #if 0
1471 static void SD_PowerOFF(void)
1473 // Set Power State to OFF
1474 SDIO->POWER = (uint32_t)0;
1476 #endif
1479 /** -----------------------------------------------------------------------------------------------------------------*/
1481 * @brief Finds the SD card SCR register value.
1482 * @param pSCR: pointer to the buffer that will contain the SCR value
1483 * @retval SD Card error state
1485 static SD_Error_t SD_FindSCR(uint32_t *pSCR)
1487 SD_Error_t ErrorState;
1488 uint32_t Index = 0;
1489 uint32_t tempscr[2] = {0, 0};
1491 // Set Block Size To 8 Bytes
1492 // Send CMD55 APP_CMD with argument as card's RCA
1493 if((ErrorState = SD_TransmitCommand((SD_CMD_SET_BLOCKLEN | SD_CMD_RESPONSE_SHORT), 8, 1)) == SD_OK)
1495 // Send CMD55 APP_CMD with argument as card's RCA
1496 if((ErrorState = SD_TransmitCommand((SD_CMD_APP_CMD | SD_CMD_RESPONSE_SHORT), SD_CardRCA, 1)) == SD_OK)
1498 SD_DataTransferInit(8, SD_DATABLOCK_SIZE_8B, true);
1500 // Send ACMD51 SD_APP_SEND_SCR with argument as 0
1501 if((ErrorState = SD_TransmitCommand((SD_CMD_SD_APP_SEND_SCR | SD_CMD_RESPONSE_SHORT), 0, 1)) == SD_OK)
1503 while((SDIO->STA & (SDIO_STA_RXOVERR | SDIO_STA_DCRCFAIL | SDIO_STA_DTIMEOUT | SDIO_STA_DBCKEND)) == 0)
1505 if((SDIO->STA & SDIO_STA_RXDAVL) != 0)
1507 *(tempscr + Index) = SDIO->FIFO;
1508 Index++;
1512 if ((SDIO->STA & SDIO_STA_DTIMEOUT) != 0) ErrorState = SD_DATA_TIMEOUT;
1513 else if((SDIO->STA & SDIO_STA_DCRCFAIL) != 0) ErrorState = SD_DATA_CRC_FAIL;
1514 else if((SDIO->STA & SDIO_STA_RXOVERR) != 0) ErrorState = SD_RX_OVERRUN;
1515 else if((SDIO->STA & SDIO_STA_RXDAVL) != 0) ErrorState = SD_OUT_OF_BOUND;
1516 else
1518 *(pSCR + 1) = ((tempscr[0] & SD_0TO7BITS) << 24) | ((tempscr[0] & SD_8TO15BITS) << 8) |
1519 ((tempscr[0] & SD_16TO23BITS) >> 8) | ((tempscr[0] & SD_24TO31BITS) >> 24);
1521 *(pSCR) = ((tempscr[1] & SD_0TO7BITS) << 24) | ((tempscr[1] & SD_8TO15BITS) << 8) |
1522 ((tempscr[1] & SD_16TO23BITS) >> 8) | ((tempscr[1] & SD_24TO31BITS) >> 24);
1529 return ErrorState;
1533 /** -----------------------------------------------------------------------------------------------------------------*/
1535 * @brief Checks if the SD card is in programming state.
1536 * @param pStatus: pointer to the variable that will contain the SD card state
1537 * @retval SD Card error state
1540 static SD_Error_t SD_IsCardProgramming(uint8_t *pStatus)
1542 uint32_t Response_R1;
1544 SD_TransmitCommand((SD_CMD_SEND_STATUS | SDIO_CMD_RESPONSE_SHORT), SD_CardRCA, 0);
1545 if((SDIO->STA & SDIO_STA_CTIMEOUT) != 0) return SD_CMD_RSP_TIMEOUT;
1546 else if((SDIO->STA & SDIO_STA_CCRCFAIL) != 0) return SD_CMD_CRC_FAIL;
1547 if((uint32_t)SDIO->RESPCMD != SD_CMD_SEND_STATUS) return SD_ILLEGAL_CMD; // Check if is of desired command
1548 Response_R1 = SDIO->RESP1; // We have received response, retrieve it for analysis
1549 *pStatus = (uint8_t)((Response_R1 >> 9) & 0x0000000F); // Find out card status
1551 return CheckOCR_Response(Response_R1);
1555 /** -----------------------------------------------------------------------------------------------------------------*/
1557 * @brief Initialize the SDIO module, DMA, and IO
1559 bool SD_Initialize_LL(DMA_Stream_TypeDef *dma)
1561 const dmaIdentifier_e dmaIdentifier = dmaGetIdentifier((dmaResource_t *)dmaStream);
1562 if (!(dma == DMA2_Stream3 || dma == DMA2_Stream6) || !dmaAllocate(dmaIdentifier, OWNER_SDCARD, 0)) {
1563 return false;
1566 // Reset SDIO Module
1567 RCC->APB2RSTR |= RCC_APB2RSTR_SDIORST;
1568 delay(1);
1569 RCC->APB2RSTR &= ~RCC_APB2RSTR_SDIORST;
1570 delay(1);
1572 // Enable SDIO clock
1573 RCC->APB2ENR |= RCC_APB2ENR_SDIOEN;
1575 // Enable DMA2 clocks
1576 RCC->AHB1ENR |= RCC_AHB1ENR_DMA2EN;
1578 //Configure Pins
1579 RCC->AHB1ENR |= RCC_AHB1ENR_GPIOCEN | RCC_AHB1ENR_GPIODEN;
1581 uint8_t is4BitWidth = sdioConfig()->use4BitWidth;
1583 const IO_t d0 = IOGetByTag(IO_TAG(PC8));
1584 const IO_t d1 = IOGetByTag(IO_TAG(PC9));
1585 const IO_t d2 = IOGetByTag(IO_TAG(PC10));
1586 const IO_t d3 = IOGetByTag(IO_TAG(PC11));
1587 const IO_t clk = IOGetByTag(IO_TAG(PC12));
1588 const IO_t cmd = IOGetByTag(IO_TAG(PD2));
1590 IOInit(d0, OWNER_SDCARD, 0);
1591 if (is4BitWidth) {
1592 IOInit(d1, OWNER_SDCARD, 0);
1593 IOInit(d2, OWNER_SDCARD, 0);
1594 IOInit(d3, OWNER_SDCARD, 0);
1596 IOInit(clk, OWNER_SDCARD, 0);
1597 IOInit(cmd, OWNER_SDCARD, 0);
1599 #define SDIO_DATA IO_CONFIG(GPIO_Mode_AF, GPIO_Speed_100MHz, GPIO_OType_PP, GPIO_PuPd_NOPULL)
1600 #define SDIO_CMD IO_CONFIG(GPIO_Mode_AF, GPIO_Speed_100MHz, GPIO_OType_PP, GPIO_PuPd_NOPULL)
1601 #define SDIO_CLK IO_CONFIG(GPIO_Mode_AF, GPIO_Speed_100MHz, GPIO_OType_PP, GPIO_PuPd_NOPULL)
1603 IOConfigGPIOAF(d0, SDIO_DATA, GPIO_AF_SDIO);
1604 if (is4BitWidth) {
1605 IOConfigGPIOAF(d1, SDIO_DATA, GPIO_AF_SDIO);
1606 IOConfigGPIOAF(d2, SDIO_DATA, GPIO_AF_SDIO);
1607 IOConfigGPIOAF(d3, SDIO_DATA, GPIO_AF_SDIO);
1609 IOConfigGPIOAF(clk, SDIO_CLK, GPIO_AF_SDIO);
1610 IOConfigGPIOAF(cmd, SDIO_CMD, GPIO_AF_SDIO);
1612 // NVIC configuration for SDIO interrupts
1613 NVIC_InitTypeDef NVIC_InitStructure;
1614 NVIC_InitStructure.NVIC_IRQChannel = SDIO_IRQn;
1615 NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = NVIC_PRIORITY_BASE(1);
1616 NVIC_InitStructure.NVIC_IRQChannelSubPriority = NVIC_PRIORITY_SUB(0);
1617 NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
1618 NVIC_Init(&NVIC_InitStructure);
1620 dmaStream = dma;
1621 RCC->AHB1ENR |= RCC_AHB1ENR_DMA2EN;
1622 // Initialize DMA
1623 dmaStream->CR = 0; // Reset DMA Stream control register
1624 dmaStream->PAR = (uint32_t)&SDIO->FIFO;
1625 if (dmaStream == DMA2_Stream3) {
1626 DMA2->LIFCR = IFCR_CLEAR_MASK_STREAM3; // Clear all interrupt flags
1627 } else {
1628 DMA2->HIFCR = IFCR_CLEAR_MASK_STREAM6; // Clear all interrupt flags
1630 dmaStream->CR = (DMA_CHANNEL_4 | DMA_SxCR_PFCTRL | // Prepare the DMA Stream configuration
1631 DMA_MINC_ENABLE | DMA_PDATAALIGN_WORD | // And write to DMA Stream CR register
1632 DMA_MDATAALIGN_WORD | DMA_PRIORITY_VERY_HIGH |
1633 DMA_MBURST_INC4 | DMA_PBURST_INC4 |
1634 DMA_MEMORY_TO_PERIPH);
1635 dmaStream->FCR = (DMA_SxFCR_DMDIS | DMA_SxFCR_FTH); // Configuration FIFO control register
1636 dmaEnable(dmaIdentifier);
1637 if (dmaStream == DMA2_Stream3) {
1638 dmaSetHandler(dmaIdentifier, SDIO_DMA_ST3_IRQHandler, 1, 0);
1639 } else {
1640 dmaSetHandler(dmaIdentifier, SDIO_DMA_ST6_IRQHandler, 1, 0);
1643 return true;
1647 /** -----------------------------------------------------------------------------------------------------------------*/
1648 bool SD_GetState(void)
1650 // Check SDCARD status
1651 if(SD_GetStatus() == SD_OK) return true;
1652 return false;
1656 /** -----------------------------------------------------------------------------------------------------------------*/
1657 static SD_Error_t SD_DoInit(void)
1659 SD_Error_t errorState;
1661 // Initialize SDIO peripheral interface with default configuration for SD card initialization.
1662 MODIFY_REG(SDIO->CLKCR, CLKCR_CLEAR_MASK, (uint32_t)SDIO_INIT_CLK_DIV);
1664 // Identify card operating voltage.
1665 errorState = SD_PowerON();
1666 if (errorState != SD_OK) {
1667 return errorState;
1670 // Initialize the present card and put them in idle state.
1671 errorState = SD_InitializeCard();
1672 if (errorState != SD_OK) {
1673 return errorState;
1676 // Read CSD/CID MSD registers.
1677 errorState = SD_GetCardInfo();
1678 if (errorState != SD_OK) {
1679 return errorState;
1682 // Select the Card - Send CMD7 SDIO_SEL_DESEL_CARD.
1683 errorState = SD_TransmitCommand((SD_CMD_SEL_DESEL_CARD | SD_CMD_RESPONSE_SHORT), SD_CardRCA, 1);
1684 // Configure SDIO peripheral interface.
1685 MODIFY_REG(SDIO->CLKCR, CLKCR_CLEAR_MASK, (uint32_t) SDIO_CLK_DIV);
1687 // Configure SD Bus width.
1688 if (errorState == SD_OK)
1690 // Enable wide operation.
1691 if (sdioConfig()->use4BitWidth) {
1692 errorState = SD_WideBusOperationConfig(SD_BUS_WIDE_4B);
1693 } else {
1694 errorState = SD_WideBusOperationConfig(SD_BUS_WIDE_1B);
1696 if (errorState == SD_OK && sdioConfig()->clockBypass) {
1697 if (SD_HighSpeed()) {
1698 SDIO->CLKCR |= SDIO_CLKCR_BYPASS;
1699 SDIO->CLKCR |= SDIO_CLKCR_NEGEDGE;
1704 return errorState;
1707 SD_Error_t SD_Init(void)
1709 static bool sdInitAttempted = false;
1710 static SD_Error_t result = SD_ERROR;
1712 if (sdInitAttempted) {
1713 return result;
1716 sdInitAttempted = true;
1718 result = SD_DoInit();
1720 return result;
1723 /** -----------------------------------------------------------------------------------------------------------------*/
1725 * @brief This function handles SD card interrupt request.
1727 void SDIO_IRQHandler(void) {
1728 // Check for SDIO interrupt flags
1729 if ((SDIO->STA & SDIO_STA_DATAEND) != 0) {
1730 SDIO->ICR = SDIO_ICR_DATAENDC;
1731 SDIO->ICR = SDIO_ICR_STATIC_FLAGS;
1732 SDIO->MASK &= ~(SDIO_MASK_DATAENDIE | SDIO_MASK_DCRCFAILIE | SDIO_MASK_DTIMEOUTIE | \
1733 SDIO_MASK_TXUNDERRIE | SDIO_MASK_RXOVERRIE | SDIO_MASK_TXFIFOHEIE | SDIO_MASK_RXFIFOHFIE);
1735 /* Currently doesn't implement multiple block write handling */
1736 if ((SD_Handle.Operation & 0x02) == (SDIO_DIR_TX << 1)) {
1737 /* Disable the stream */
1738 dmaStream->CR &= ~DMA_SxCR_EN;
1739 SDIO->DCTRL &= ~(SDIO_DCTRL_DMAEN);
1740 /* Transfer is complete */
1741 SD_Handle.TXCplt = 0;
1742 if ((SD_Handle.Operation & 0x01) == SD_MULTIPLE_BLOCK) {
1743 /* Send stop command in multiblock write */
1744 SD_TransmitCommand((SD_CMD_STOP_TRANSMISSION | SD_CMD_RESPONSE_SHORT), 0, 1);
1747 SD_Handle.TransferComplete = 1;
1748 SD_Handle.TransferError = SD_OK; // No transfer error
1750 else if ((SDIO->STA & SDIO_STA_DCRCFAIL) != 0)
1751 SD_Handle.TransferError = SD_DATA_CRC_FAIL;
1752 else if ((SDIO->STA & SDIO_STA_DTIMEOUT) != 0)
1753 SD_Handle.TransferError = SD_DATA_TIMEOUT;
1754 else if ((SDIO->STA & SDIO_STA_RXOVERR) != 0)
1755 SD_Handle.TransferError = SD_RX_OVERRUN;
1756 else if ((SDIO->STA & SDIO_STA_TXUNDERR) != 0)
1757 SD_Handle.TransferError = SD_TX_UNDERRUN;
1759 SDIO->ICR = SDIO_ICR_STATIC_FLAGS;
1761 // Disable all SDIO peripheral interrupt sources
1762 SDIO->MASK &= ~(SDIO_MASK_DCRCFAILIE | SDIO_MASK_DTIMEOUTIE
1763 | SDIO_MASK_DATAENDIE |
1764 SDIO_MASK_TXFIFOHEIE | SDIO_MASK_RXFIFOHFIE | SDIO_MASK_TXUNDERRIE |
1765 SDIO_MASK_RXOVERRIE);
1768 /** -----------------------------------------------------------------------------------------------------------------*/
1770 * @brief This function handles DMA2 Stream 3 interrupt request.
1772 void SDIO_DMA_ST3_IRQHandler(dmaChannelDescriptor_t *dma)
1774 UNUSED(dma);
1775 // Transfer Error Interrupt management
1776 if((DMA2->LISR & DMA_LISR_TEIF3) != 0)
1778 if((DMA2_Stream3->CR & DMA_SxCR_TEIE) != 0)
1780 DMA2_Stream3->CR &= ~DMA_SxCR_TEIE; // Disable the transfer error interrupt
1781 DMA2->LIFCR = DMA_LIFCR_CTEIF3; // Clear the transfer error flag
1785 // FIFO Error Interrupt management
1786 if((DMA2->LISR & DMA_LISR_FEIF3) != 0)
1788 if((DMA2_Stream3->FCR & DMA_SxFCR_FEIE) != 0)
1790 DMA2_Stream3->FCR &= ~DMA_SxFCR_FEIE; // Disable the FIFO Error interrupt
1791 DMA2->LIFCR = DMA_LIFCR_CFEIF3; // Clear the FIFO error flag
1795 // Direct Mode Error Interrupt management
1796 if((DMA2->LISR & DMA_LISR_DMEIF3) != 0)
1798 if((DMA2_Stream3->CR & DMA_SxCR_DMEIE) != 0)
1800 DMA2_Stream3->CR &= ~DMA_SxCR_DMEIE; // Disable the direct mode Error interrupt
1801 DMA2->LIFCR = DMA_LIFCR_CDMEIF3; // Clear the FIFO error flag
1805 // Half Transfer Complete Interrupt management
1806 if((DMA2->LISR & DMA_LISR_HTIF3) != 0)
1808 if((DMA2_Stream3->CR & DMA_SxCR_HTIE) != 0)
1810 if(((DMA2_Stream3->CR) & (uint32_t)(DMA_SxCR_DBM)) != 0) // Multi_Buffering mode enabled
1812 DMA2->LIFCR = DMA_LIFCR_CHTIF3; // Clear the half transfer complete flag
1814 else
1816 if((DMA2_Stream3->CR & DMA_SxCR_CIRC) == 0) // Disable the half transfer interrupt if the DMA mode is not CIRCULAR
1818 DMA2_Stream3->CR &= ~DMA_SxCR_HTIE; // Disable the half transfer interrupt
1821 DMA2->LIFCR = DMA_LIFCR_CHTIF3; // Clear the half transfer complete flag
1826 // Transfer Complete Interrupt management
1827 if((DMA2->LISR & DMA_LISR_TCIF3) != 0)
1829 if((DMA2_Stream3->CR & DMA_SxCR_TCIE) != 0)
1831 if((DMA2_Stream3->CR & (uint32_t)(DMA_SxCR_DBM)) != 0)
1833 DMA2->LIFCR = DMA_LIFCR_CTCIF3; // Clear the transfer complete flag
1835 else //Disable the transfer complete interrupt if the DMA mode is not CIRCULAR
1837 if((DMA2_Stream3->CR & DMA_SxCR_CIRC) == 0)
1839 DMA2_Stream3->CR &= ~DMA_SxCR_TCIE; // Disable the transfer complete interrupt
1842 DMA2->LIFCR = DMA_LIFCR_CTCIF3; // Clear the transfer complete flag
1843 SD_DMA_Complete(DMA2_Stream3);
1850 /** -----------------------------------------------------------------------------------------------------------------*/
1852 * @brief This function handles DMA2 Stream 6 interrupt request.
1854 void SDIO_DMA_ST6_IRQHandler(dmaChannelDescriptor_t *dma)
1856 UNUSED(dma);
1857 // Transfer Error Interrupt management
1858 if((DMA2->HISR & DMA_HISR_TEIF6) != 0)
1860 if((DMA2_Stream6->CR & DMA_SxCR_TEIE) != 0)
1862 DMA2_Stream6->CR &= ~DMA_SxCR_TEIE; // Disable the transfer error interrupt
1863 DMA2->HIFCR = DMA_HIFCR_CTEIF6; // Clear the transfer error flag
1867 // FIFO Error Interrupt management
1868 if((DMA2->HISR & DMA_HISR_FEIF6) != 0)
1870 if((DMA2_Stream6->FCR & DMA_SxFCR_FEIE) != 0)
1872 DMA2_Stream6->FCR &= ~DMA_SxFCR_FEIE; // Disable the FIFO Error interrupt
1873 DMA2->HIFCR = DMA_HIFCR_CFEIF6; // Clear the FIFO error flag
1877 // Direct Mode Error Interrupt management
1878 if((DMA2->HISR & DMA_HISR_DMEIF6) != 0)
1880 if((DMA2_Stream6->CR & DMA_SxCR_DMEIE) != 0)
1882 DMA2_Stream6->CR &= ~DMA_SxCR_DMEIE; // Disable the direct mode Error interrupt
1883 DMA2->HIFCR = DMA_HIFCR_CDMEIF6; // Clear the FIFO error flag
1887 // Half Transfer Complete Interrupt management
1888 if((DMA2->HISR & DMA_HISR_HTIF6) != 0)
1890 if((DMA2_Stream6->CR & DMA_SxCR_HTIE) != 0)
1892 if(((DMA2_Stream6->CR) & (uint32_t)(DMA_SxCR_DBM)) != 0) // Multi_Buffering mode enabled
1894 DMA2->HIFCR = DMA_HIFCR_CHTIF6; // Clear the half transfer complete flag
1896 else
1898 if((DMA2_Stream6->CR & DMA_SxCR_CIRC) == 0) // Disable the half transfer interrupt if the DMA mode is not CIRCULAR
1900 DMA2_Stream6->CR &= ~DMA_SxCR_HTIE; // Disable the half transfer interrupt
1903 DMA2->HIFCR = DMA_HIFCR_CHTIF6; // Clear the half transfer complete flag
1908 // Transfer Complete Interrupt management
1909 if((DMA2->HISR & DMA_HISR_TCIF6) != 0)
1911 if((DMA2_Stream6->CR & DMA_SxCR_TCIE) != 0)
1913 if((DMA2_Stream6->CR & (uint32_t)(DMA_SxCR_DBM)) != 0)
1915 DMA2->HIFCR = DMA_HIFCR_CTCIF6; // Clear the transfer complete flag
1917 else //Disable the transfer complete interrupt if the DMA mode is not CIRCULAR
1919 if((DMA2_Stream6->CR & DMA_SxCR_CIRC) == 0)
1921 DMA2_Stream6->CR &= ~DMA_SxCR_TCIE; // Disable the transfer complete interrupt
1924 DMA2->HIFCR = DMA_HIFCR_CTCIF6; // Clear the transfer complete flag
1925 SD_DMA_Complete(DMA2_Stream6);
1931 /* ------------------------------------------------------------------------------------------------------------------*/
1932 #endif