sdcard.c 9.71 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/*
 * This file is part of the Micro Python project, http://micropython.org/
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2013, 2014 Damien P. George
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

Damien George's avatar
Damien George committed
27
28
29
30
31
// TODO make it work with DMA

#include <stm32f4xx_hal.h>

#include "mpconfig.h"
32
#include "nlr.h"
33
#include "misc.h"
Damien George's avatar
Damien George committed
34
35
36
37
#include "qstr.h"
#include "obj.h"
#include "runtime.h"
#include "sdcard.h"
38
#include "pin.h"
39
#include "genhdr/pins.h"
40
#include "bufhelper.h"
Damien George's avatar
Damien George committed
41

42
#if MICROPY_HW_HAS_SDCARD
Damien George's avatar
Damien George committed
43

44
static SD_HandleTypeDef sd_handle;
Damien George's avatar
Damien George committed
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66

void sdcard_init(void) {
    GPIO_InitTypeDef GPIO_Init_Structure;

    // invalidate the sd_handle
    sd_handle.Instance = NULL;

    // configure SD GPIO
    // we do this here an not in HAL_SD_MspInit because it apparently
    // makes it more robust to have the pins always pulled high
    GPIO_Init_Structure.Mode = GPIO_MODE_AF_PP;
    GPIO_Init_Structure.Pull = GPIO_PULLUP;
    GPIO_Init_Structure.Speed = GPIO_SPEED_HIGH;
    GPIO_Init_Structure.Alternate = GPIO_AF12_SDIO;
    GPIO_Init_Structure.Pin = GPIO_PIN_8 | GPIO_PIN_9 | GPIO_PIN_10 | GPIO_PIN_11 | GPIO_PIN_12;
    HAL_GPIO_Init(GPIOC, &GPIO_Init_Structure);
    GPIO_Init_Structure.Pin = GPIO_PIN_2;
    HAL_GPIO_Init(GPIOD, &GPIO_Init_Structure);

    // configure the SD card detect pin
    // we do this here so we can detect if the SD card is inserted before powering it on
    GPIO_Init_Structure.Mode = GPIO_MODE_INPUT;
67
    GPIO_Init_Structure.Pull = MICROPY_HW_SDCARD_DETECT_PULL;
Damien George's avatar
Damien George committed
68
    GPIO_Init_Structure.Speed = GPIO_SPEED_HIGH;
69
70
    GPIO_Init_Structure.Pin = MICROPY_HW_SDCARD_DETECT_PIN.pin_mask;
    HAL_GPIO_Init(MICROPY_HW_SDCARD_DETECT_PIN.gpio, &GPIO_Init_Structure);
Damien George's avatar
Damien George committed
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
}

void HAL_SD_MspInit(SD_HandleTypeDef *hsd) {
    // enable SDIO clock
    __SDIO_CLK_ENABLE();

    // GPIO have already been initialised by sdcard_init

    // interrupts are not used at the moment
    // they are needed only for DMA transfer (I think...)
}

void HAL_SD_MspDeInit(SD_HandleTypeDef *hsd) {
    __SDIO_CLK_DISABLE();
}

bool sdcard_is_present(void) {
88
    return HAL_GPIO_ReadPin(MICROPY_HW_SDCARD_DETECT_PIN.gpio, MICROPY_HW_SDCARD_DETECT_PIN.pin_mask) == MICROPY_HW_SDCARD_DETECT_PRESENT;
Damien George's avatar
Damien George committed
89
90
91
92
93
94
}

bool sdcard_power_on(void) {
    if (!sdcard_is_present()) {
        return false;
    }
95
96
97
    if (sd_handle.Instance) {
        return true;
    }
Damien George's avatar
Damien George committed
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127

    // SD device interface configuration
    sd_handle.Instance = SDIO;
    sd_handle.Init.ClockEdge           = SDIO_CLOCK_EDGE_RISING;
    sd_handle.Init.ClockBypass         = SDIO_CLOCK_BYPASS_DISABLE;
    sd_handle.Init.ClockPowerSave      = SDIO_CLOCK_POWER_SAVE_DISABLE;
    sd_handle.Init.BusWide             = SDIO_BUS_WIDE_1B;
    sd_handle.Init.HardwareFlowControl = SDIO_HARDWARE_FLOW_CONTROL_DISABLE;
    sd_handle.Init.ClockDiv            = SDIO_TRANSFER_CLK_DIV;

    // init the SD interface
    HAL_SD_CardInfoTypedef cardinfo;
    if (HAL_SD_Init(&sd_handle, &cardinfo) != SD_OK) {
        goto error;
    }

    // configure the SD bus width for wide operation
    if (HAL_SD_WideBusOperation_Config(&sd_handle, SDIO_BUS_WIDE_4B) != SD_OK) {
        HAL_SD_DeInit(&sd_handle);
        goto error;
    }

    return true;

error:
    sd_handle.Instance = NULL;
    return false;
}

void sdcard_power_off(void) {
128
129
130
131
    if (!sd_handle.Instance) {
        return;
    }
    HAL_SD_DeInit(&sd_handle); 
Damien George's avatar
Damien George committed
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
    sd_handle.Instance = NULL;
}

uint64_t sdcard_get_capacity_in_bytes(void) {
    if (sd_handle.Instance == NULL) {
        return 0;
    }
    HAL_SD_CardInfoTypedef cardinfo;
    HAL_SD_Get_CardInfo(&sd_handle, &cardinfo);
    return cardinfo.CardCapacity;
}

bool sdcard_read_blocks(uint8_t *dest, uint32_t block_num, uint32_t num_blocks) {
    // check that dest pointer is aligned on a 4-byte boundary
    if (((uint32_t)dest & 3) != 0) {
        return false;
    }

    // check that SD card is initialised
    if (sd_handle.Instance == NULL) {
        return false;
    }

155
156
157
    // We must disable IRQs because the SDIO peripheral has a small FIFO
    // buffer and we can't let it fill up in the middle of a read.
    // This will not be needed when SD uses DMA for transfer.
158
    __disable_irq();
159
    HAL_SD_ErrorTypedef err = HAL_SD_ReadBlocks(&sd_handle, (uint32_t*)dest, (uint64_t)block_num * SDCARD_BLOCK_SIZE, SDCARD_BLOCK_SIZE, num_blocks);
160
161
162
    __enable_irq();

    if (err != SD_OK) {
Damien George's avatar
Damien George committed
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
        return false;
    }

    return true;
}

bool sdcard_write_blocks(const uint8_t *src, uint32_t block_num, uint32_t num_blocks) {
    // check that src pointer is aligned on a 4-byte boundary
    if (((uint32_t)src & 3) != 0) {
        return false;
    }

    // check that SD card is initialised
    if (sd_handle.Instance == NULL) {
        return false;
    }

180
181
182
183
    // We must disable IRQs because the SDIO peripheral has a small FIFO
    // buffer and we can't let it drain to empty in the middle of a write.
    // This will not be needed when SD uses DMA for transfer.
    __disable_irq();
184
    HAL_SD_ErrorTypedef err = HAL_SD_WriteBlocks(&sd_handle, (uint32_t*)src, (uint64_t)block_num * SDCARD_BLOCK_SIZE, SDCARD_BLOCK_SIZE, num_blocks);
185
186
187
    __enable_irq();

    if (err != SD_OK) {
Damien George's avatar
Damien George committed
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
        return false;
    }

    return true;
}

#if 0
DMA not implemented
bool sdcard_read_blocks_dma(uint8_t *dest, uint32_t block_num, uint32_t num_blocks) {
    // check that dest pointer is aligned on a 4-byte boundary
    if (((uint32_t)dest & 3) != 0) {
        return false;
    }

    // check that SD card is initialised
    if (sd_handle.Instance == NULL) {
        return false;
    }

    // do the read
208
    if (HAL_SD_ReadBlocks_DMA(&sd_handle, (uint32_t*)dest, (uint64_t)block_num * SDCARD_BLOCK_SIZE, SDCARD_BLOCK_SIZE) != SD_OK) {
Damien George's avatar
Damien George committed
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
        return false;
    }

    // wait for DMA transfer to finish, with a large timeout
    if (HAL_SD_CheckReadOperation(&sd_handle, 100000000) != SD_OK) {
        return false;
    }

    return true;
}

bool sdcard_write_blocks_dma(const uint8_t *src, uint32_t block_num, uint32_t num_blocks) {
    // check that src pointer is aligned on a 4-byte boundary
    if (((uint32_t)src & 3) != 0) {
        return false;
    }

    // check that SD card is initialised
    if (sd_handle.Instance == NULL) {
        return false;
    }

    SD_Error status;

233
    status = HAL_SD_WriteBlock_DMA(&sd_handle, (uint32_t*)src, (uint64_t)block_num * SDCARD_BLOCK_SIZE, SDCARD_BLOCK_SIZE, num_blocks);
Damien George's avatar
Damien George committed
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
    if (status != SD_OK) {
        return false;
    }

    // wait for DMA transfer to finish, with a large timeout
    status = HAL_SD_CheckWriteOperation(&sd_handle, 100000000);
    if (status != SD_OK) {
        return false;
    }

    return true;
}
#endif

/******************************************************************************/
// Micro Python bindings

static mp_obj_t sd_present(mp_obj_t self) {
    return MP_BOOL(sdcard_is_present());
}

static MP_DEFINE_CONST_FUN_OBJ_1(sd_present_obj, sd_present);

static mp_obj_t sd_power(mp_obj_t self, mp_obj_t state) {
    bool result;
Damien George's avatar
Damien George committed
259
    if (mp_obj_is_true(state)) {
Damien George's avatar
Damien George committed
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
        result = sdcard_power_on();
    } else {
        sdcard_power_off();
        result = true;
    }
    return MP_BOOL(result);
}

static MP_DEFINE_CONST_FUN_OBJ_2(sd_power_obj, sd_power);

static mp_obj_t sd_read(mp_obj_t self, mp_obj_t block_num) {
    uint8_t *dest = m_new(uint8_t, SDCARD_BLOCK_SIZE);
    if (!sdcard_read_blocks(dest, mp_obj_get_int(block_num), 1)) {
        m_free(dest, SDCARD_BLOCK_SIZE);
        return mp_const_none;
    }
    return mp_obj_new_bytearray_by_ref(SDCARD_BLOCK_SIZE, dest);
}

static MP_DEFINE_CONST_FUN_OBJ_2(sd_read_obj, sd_read);

281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
static mp_obj_t sd_write(mp_obj_t self, mp_obj_t block_num, mp_obj_t source) {
    mp_buffer_info_t bufinfo;
    uint8_t tmp[1];

    pyb_buf_get_for_send(source, &bufinfo, tmp);
    if (bufinfo.len % SDCARD_BLOCK_SIZE != 0) {
        nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "writes must be aligned to SDCARD_BLOCK_SIZE (%d) bytes", SDCARD_BLOCK_SIZE));
    }

    if (!sdcard_write_blocks(bufinfo.buf, mp_obj_get_int(block_num), bufinfo.len / SDCARD_BLOCK_SIZE)) {
        nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_Exception, "sdcard_write_blocks failed"));
    }
    return mp_const_none;
}

static MP_DEFINE_CONST_FUN_OBJ_3(sd_write_obj, sd_write);

298
299
300
301
STATIC const mp_map_elem_t sdcard_locals_dict_table[] = {
    { MP_OBJ_NEW_QSTR(MP_QSTR_present), (mp_obj_t)&sd_present_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_power), (mp_obj_t)&sd_power_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_read), (mp_obj_t)&sd_read_obj },
302
    { MP_OBJ_NEW_QSTR(MP_QSTR_write), (mp_obj_t)&sd_write_obj },
Damien George's avatar
Damien George committed
303
304
};

305
306
STATIC MP_DEFINE_CONST_DICT(sdcard_locals_dict, sdcard_locals_dict_table);

Damien George's avatar
Damien George committed
307
308
309
static const mp_obj_type_t sdcard_type = {
    { &mp_type_type },
    .name = MP_QSTR_SDcard,
310
    .locals_dict = (mp_obj_t)&sdcard_locals_dict,
Damien George's avatar
Damien George committed
311
312
313
};

const mp_obj_base_t pyb_sdcard_obj = {&sdcard_type};
314
315

#endif // MICROPY_HW_HAS_SDCARD