spi.c 29.1 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
#include <stdio.h>
#include <string.h>

30
31
#include "py/nlr.h"
#include "py/runtime.h"
32
#include "py/mphal.h"
33
#include "irq.h"
Damien George's avatar
Damien George committed
34
35
#include "pin.h"
#include "genhdr/pins.h"
36
#include "bufhelper.h"
37
#include "dma.h"
Damien George's avatar
Damien George committed
38
39
#include "spi.h"

40
41
42
43
44
45
46
47
48
49
/// \moduleref pyb
/// \class SPI - a master-driven serial protocol
///
/// SPI is a serial protocol that is driven by a master.  At the physical level
/// there are 3 lines: SCK, MOSI, MISO.
///
/// See usage model of I2C; SPI is very similar.  Main difference is
/// parameters to init the SPI bus:
///
///     from pyb import SPI
50
///     spi = SPI(1, SPI.MASTER, baudrate=600000, polarity=1, phase=0, crc=0x7)
51
52
///
/// Only required parameter is mode, SPI.MASTER or SPI.SLAVE.  Polarity can be
53
54
55
/// 0 or 1, and is the level the idle clock line sits at.  Phase can be 0 or 1
/// to sample data on the first or second clock edge respectively.  Crc can be
/// None for no CRC, or a polynomial specifier.
56
57
58
59
60
61
62
///
/// Additional method for SPI:
///
///     data = spi.send_recv(b'1234')        # send 4 bytes and receive 4 bytes
///     buf = bytearray(4)
///     spi.send_recv(b'1234', buf)          # send 4 bytes and receive 4 into buf
///     spi.send_recv(buf, buf)              # send/recv 4 bytes from/to buf
63

64
65
66
67
68
69
70
// Possible DMA configurations for SPI busses:
// SPI1_TX: DMA2_Stream3.CHANNEL_3 or DMA2_Stream5.CHANNEL_3
// SPI1_RX: DMA2_Stream0.CHANNEL_3 or DMA2_Stream2.CHANNEL_3
// SPI2_TX: DMA1_Stream4.CHANNEL_0
// SPI2_RX: DMA1_Stream3.CHANNEL_0
// SPI3_TX: DMA1_Stream5.CHANNEL_0 or DMA1_Stream7.CHANNEL_0
// SPI3_RX: DMA1_Stream0.CHANNEL_0 or DMA1_Stream2.CHANNEL_0
71
72
73
74
75
76
// SPI4_TX: DMA2_Stream4.CHANNEL_5 or DMA2_Stream1.CHANNEL_4
// SPI4_RX: DMA2_Stream3.CHANNEL_5 or DMA2_Stream0.CHANNEL_4
// SPI5_TX: DMA2_Stream4.CHANNEL_2 or DMA2_Stream6.CHANNEL_7
// SPI5_RX: DMA2_Stream3.CHANNEL_2 or DMA2_Stream5.CHANNEL_7
// SPI6_TX: DMA2_Stream5.CHANNEL_1
// SPI6_RX: DMA2_Stream6.CHANNEL_1
77
78
79
80

typedef struct _pyb_spi_obj_t {
    mp_obj_base_t base;
    SPI_HandleTypeDef *spi;
81
82
    const dma_descr_t *tx_dma_descr;
    const dma_descr_t *rx_dma_descr;
83
84
} pyb_spi_obj_t;

85
#if defined(MICROPY_HW_SPI1_SCK)
Damien George's avatar
Damien George committed
86
SPI_HandleTypeDef SPIHandle1 = {.Instance = NULL};
87
#endif
88
#if defined(MICROPY_HW_SPI2_SCK)
Damien George's avatar
Damien George committed
89
SPI_HandleTypeDef SPIHandle2 = {.Instance = NULL};
90
#endif
91
#if defined(MICROPY_HW_SPI3_SCK)
Damien George's avatar
Damien George committed
92
SPI_HandleTypeDef SPIHandle3 = {.Instance = NULL};
93
#endif
94
95
96
97
98
99
100
101
102
#if defined(MICROPY_HW_SPI4_SCK)
SPI_HandleTypeDef SPIHandle4 = {.Instance = NULL};
#endif
#if defined(MICROPY_HW_SPI5_SCK)
SPI_HandleTypeDef SPIHandle5 = {.Instance = NULL};
#endif
#if defined(MICROPY_HW_SPI6_SCK)
SPI_HandleTypeDef SPIHandle6 = {.Instance = NULL};
#endif
Damien George's avatar
Damien George committed
103

104
STATIC const pyb_spi_obj_t pyb_spi_obj[] = {
105
    #if defined(MICROPY_HW_SPI1_SCK)
106
    {{&pyb_spi_type}, &SPIHandle1, &dma_SPI_1_TX, &dma_SPI_1_RX},
107
    #else
108
    {{&pyb_spi_type}, NULL, NULL, NULL},
109
110
    #endif
    #if defined(MICROPY_HW_SPI2_SCK)
111
    {{&pyb_spi_type}, &SPIHandle2, &dma_SPI_2_TX, &dma_SPI_2_RX},
112
    #else
113
    {{&pyb_spi_type}, NULL, NULL, NULL},
114
115
    #endif
    #if defined(MICROPY_HW_SPI3_SCK)
116
    {{&pyb_spi_type}, &SPIHandle3, &dma_SPI_3_TX, &dma_SPI_3_RX},
117
    #else
118
    {{&pyb_spi_type}, NULL, NULL, NULL},
119
    #endif
120
    #if defined(MICROPY_HW_SPI4_SCK)
121
    {{&pyb_spi_type}, &SPIHandle4, &dma_SPI_4_TX, &dma_SPI_4_RX},
122
    #else
123
    {{&pyb_spi_type}, NULL, NULL, NULL},
124
125
    #endif
    #if defined(MICROPY_HW_SPI5_SCK)
126
    {{&pyb_spi_type}, &SPIHandle5, &dma_SPI_5_TX, &dma_SPI_5_RX},
127
    #else
128
    {{&pyb_spi_type}, NULL, NULL, NULL},
129
130
    #endif
    #if defined(MICROPY_HW_SPI6_SCK)
131
    {{&pyb_spi_type}, &SPIHandle6, &dma_SPI_6_TX, &dma_SPI_6_RX},
132
    #else
133
    {{&pyb_spi_type}, NULL, NULL, NULL},
134
    #endif
135
};
136

Damien George's avatar
Damien George committed
137
138
void spi_init0(void) {
    // reset the SPI handles
139
    #if defined(MICROPY_HW_SPI1_SCK)
Damien George's avatar
Damien George committed
140
141
    memset(&SPIHandle1, 0, sizeof(SPI_HandleTypeDef));
    SPIHandle1.Instance = SPI1;
142
143
    #endif
    #if defined(MICROPY_HW_SPI2_SCK)
Damien George's avatar
Damien George committed
144
145
    memset(&SPIHandle2, 0, sizeof(SPI_HandleTypeDef));
    SPIHandle2.Instance = SPI2;
146
147
    #endif
    #if defined(MICROPY_HW_SPI3_SCK)
Damien George's avatar
Damien George committed
148
149
    memset(&SPIHandle3, 0, sizeof(SPI_HandleTypeDef));
    SPIHandle3.Instance = SPI3;
150
    #endif
151
152
153
154
155
156
157
158
159
160
161
162
    #if defined(MICROPY_HW_SPI4_SCK)
    memset(&SPIHandle4, 0, sizeof(SPI_HandleTypeDef));
    SPIHandle4.Instance = SPI4;
    #endif
    #if defined(MICROPY_HW_SPI5_SCK)
    memset(&SPIHandle5, 0, sizeof(SPI_HandleTypeDef));
    SPIHandle5.Instance = SPI5;
    #endif
    #if defined(MICROPY_HW_SPI6_SCK)
    memset(&SPIHandle6, 0, sizeof(SPI_HandleTypeDef));
    SPIHandle6.Instance = SPI6;
    #endif
Damien George's avatar
Damien George committed
163
164
165
}

// TODO allow to take a list of pins to use
166
void spi_init(SPI_HandleTypeDef *spi, bool enable_nss_pin) {
167
168
169
170
    // init the GPIO lines
    GPIO_InitTypeDef GPIO_InitStructure;
    GPIO_InitStructure.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStructure.Speed = GPIO_SPEED_FAST;
171
    GPIO_InitStructure.Pull = spi->Init.CLKPolarity == SPI_POLARITY_LOW ? GPIO_PULLDOWN : GPIO_PULLUP;
172

173
    const pyb_spi_obj_t *self;
Damien George's avatar
Damien George committed
174
    const pin_obj_t *pins[4];
175
    pins[0] = NULL;
176

177
    if (0) {
178
    #if defined(MICROPY_HW_SPI1_SCK)
179
    } else if (spi->Instance == SPI1) {
180
        self = &pyb_spi_obj[0];
181
        #if defined(MICROPY_HW_SPI1_NSS)
182
        pins[0] = &MICROPY_HW_SPI1_NSS;
183
        #endif
184
185
186
        pins[1] = &MICROPY_HW_SPI1_SCK;
        pins[2] = &MICROPY_HW_SPI1_MISO;
        pins[3] = &MICROPY_HW_SPI1_MOSI;
187
188
        // enable the SPI clock
        __SPI1_CLK_ENABLE();
189
190
    #endif
    #if defined(MICROPY_HW_SPI2_SCK)
191
    } else if (spi->Instance == SPI2) {
192
        self = &pyb_spi_obj[1];
193
        #if defined(MICROPY_HW_SPI2_NSS)
194
        pins[0] = &MICROPY_HW_SPI2_NSS;
195
        #endif
196
197
198
        pins[1] = &MICROPY_HW_SPI2_SCK;
        pins[2] = &MICROPY_HW_SPI2_MISO;
        pins[3] = &MICROPY_HW_SPI2_MOSI;
199
200
        // enable the SPI clock
        __SPI2_CLK_ENABLE();
201
202
    #endif
    #if defined(MICROPY_HW_SPI3_SCK)
203
    } else if (spi->Instance == SPI3) {
204
        self = &pyb_spi_obj[2];
205
        #if defined(MICROPY_HW_SPI3_NSS)
206
        pins[0] = &MICROPY_HW_SPI3_NSS;
207
        #endif
208
209
210
        pins[1] = &MICROPY_HW_SPI3_SCK;
        pins[2] = &MICROPY_HW_SPI3_MISO;
        pins[3] = &MICROPY_HW_SPI3_MOSI;
211
212
        // enable the SPI clock
        __SPI3_CLK_ENABLE();
213
    #endif
214
215
216
    #if defined(MICROPY_HW_SPI4_SCK)
    } else if (spi->Instance == SPI4) {
        self = &pyb_spi_obj[3];
217
        #if defined(MICROPY_HW_SPI4_NSS)
218
        pins[0] = &MICROPY_HW_SPI4_NSS;
219
        #endif
220
221
222
223
224
225
226
227
228
        pins[1] = &MICROPY_HW_SPI4_SCK;
        pins[2] = &MICROPY_HW_SPI4_MISO;
        pins[3] = &MICROPY_HW_SPI4_MOSI;
        // enable the SPI clock
        __SPI4_CLK_ENABLE();
    #endif
    #if defined(MICROPY_HW_SPI5_SCK)
    } else if (spi->Instance == SPI5) {
        self = &pyb_spi_obj[4];
229
        #if defined(MICROPY_HW_SPI5_NSS)
230
        pins[0] = &MICROPY_HW_SPI5_NSS;
231
        #endif
232
233
234
235
236
237
238
239
240
        pins[1] = &MICROPY_HW_SPI5_SCK;
        pins[2] = &MICROPY_HW_SPI5_MISO;
        pins[3] = &MICROPY_HW_SPI5_MOSI;
        // enable the SPI clock
        __SPI5_CLK_ENABLE();
    #endif
    #if defined(MICROPY_HW_SPI6_SCK)
    } else if (spi->Instance == SPI6) {
        self = &pyb_spi_obj[5];
241
        #if defined(MICROPY_HW_SPI6_NSS)
242
        pins[0] = &MICROPY_HW_SPI6_NSS;
243
        #endif
244
245
246
247
248
249
        pins[1] = &MICROPY_HW_SPI6_SCK;
        pins[2] = &MICROPY_HW_SPI6_MISO;
        pins[3] = &MICROPY_HW_SPI6_MOSI;
        // enable the SPI clock
        __SPI6_CLK_ENABLE();
    #endif
250
251
252
    } else {
        // SPI does not exist for this board (shouldn't get here, should be checked by caller)
        return;
Damien George's avatar
Damien George committed
253
254
    }

255
    for (uint i = (enable_nss_pin && pins[0] ? 0 : 1); i < 4; i++) {
256
        mp_hal_gpio_set_af(pins[i], &GPIO_InitStructure, AF_FN_SPI, (self - &pyb_spi_obj[0]) + 1);
Damien George's avatar
Damien George committed
257
258
    }

259
    // init the SPI device
Damien George's avatar
Damien George committed
260
261
262
263
    if (HAL_SPI_Init(spi) != HAL_OK) {
        // init error
        // TODO should raise an exception, but this function is not necessarily going to be
        // called via Python, so may not be properly wrapped in an NLR handler
264
        printf("OSError: HAL_SPI_Init failed\n");
Damien George's avatar
Damien George committed
265
266
        return;
    }
267

268
269
270
    // After calling HAL_SPI_Init() it seems that the DMA gets disconnected if
    // it was previously configured.  So we invalidate the DMA channel to force
    // an initialisation the next time we use it.
271
272
    dma_invalidate_channel(self->tx_dma_descr);
    dma_invalidate_channel(self->rx_dma_descr);
Damien George's avatar
Damien George committed
273
274
275
276
}

void spi_deinit(SPI_HandleTypeDef *spi) {
    HAL_SPI_DeInit(spi);
277
    if (0) {
278
    #if defined(MICROPY_HW_SPI1_SCK)
279
    } else if (spi->Instance == SPI1) {
280
281
        __SPI1_FORCE_RESET();
        __SPI1_RELEASE_RESET();
Damien George's avatar
Damien George committed
282
        __SPI1_CLK_DISABLE();
283
284
    #endif
    #if defined(MICROPY_HW_SPI2_SCK)
Damien George's avatar
Damien George committed
285
    } else if (spi->Instance == SPI2) {
286
287
        __SPI2_FORCE_RESET();
        __SPI2_RELEASE_RESET();
Damien George's avatar
Damien George committed
288
        __SPI2_CLK_DISABLE();
289
290
    #endif
    #if defined(MICROPY_HW_SPI3_SCK)
291
    } else if (spi->Instance == SPI3) {
292
293
        __SPI3_FORCE_RESET();
        __SPI3_RELEASE_RESET();
Damien George's avatar
Damien George committed
294
        __SPI3_CLK_DISABLE();
295
    #endif
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
    #if defined(MICROPY_HW_SPI4_SCK)
    } else if (spi->Instance == SPI4) {
        __SPI4_FORCE_RESET();
        __SPI4_RELEASE_RESET();
        __SPI4_CLK_DISABLE();
    #endif
    #if defined(MICROPY_HW_SPI5_SCK)
    } else if (spi->Instance == SPI5) {
        __SPI5_FORCE_RESET();
        __SPI5_RELEASE_RESET();
        __SPI5_CLK_DISABLE();
    #endif
    #if defined(MICROPY_HW_SPI6_SCK)
    } else if (spi->Instance == SPI6) {
        __SPI6_FORCE_RESET();
        __SPI6_RELEASE_RESET();
        __SPI6_CLK_DISABLE();
    #endif
Damien George's avatar
Damien George committed
314
315
316
    }
}

317
STATIC HAL_StatusTypeDef spi_wait_dma_finished(SPI_HandleTypeDef *spi, uint32_t timeout) {
318
319
320
    // Note: we can't use WFI to idle in this loop because the DMA completion
    // interrupt may occur before the WFI.  Hence we miss it and have to wait
    // until the next sys-tick (up to 1ms).
321
322
323
324
325
326
327
328
329
    uint32_t start = HAL_GetTick();
    while (HAL_SPI_GetState(spi) != HAL_SPI_STATE_READY) {
        if (HAL_GetTick() - start >= timeout) {
            return HAL_TIMEOUT;
        }
    }
    return HAL_OK;
}

Damien George's avatar
Damien George committed
330
331
332
/******************************************************************************/
/* Micro Python bindings                                                      */

333
334
335
336
337
338
339
340
SPI_HandleTypeDef *spi_get_handle(mp_obj_t o) {
    if (!MP_OBJ_IS_TYPE(o, &pyb_spi_type)) {
        nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "expecting an SPI object"));
    }
    pyb_spi_obj_t *self = o;
    return self->spi;
}

341
STATIC void pyb_spi_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
Damien George's avatar
Damien George committed
342
343
    pyb_spi_obj_t *self = self_in;

344
345
346
347
348
349
350
351
352
353
354
355
    uint spi_num = 1; // default to SPI1
    if (self->spi->Instance == SPI2) { spi_num = 2; }
    else if (self->spi->Instance == SPI3) { spi_num = 3; }
    #if defined(SPI4)
    else if (self->spi->Instance == SPI4) { spi_num = 4; }
    #endif
    #if defined(SPI5)
    else if (self->spi->Instance == SPI5) { spi_num = 5; }
    #endif
    #if defined(SPI6)
    else if (self->spi->Instance == SPI6) { spi_num = 6; }
    #endif
Damien George's avatar
Damien George committed
356
357

    if (self->spi->State == HAL_SPI_STATE_RESET) {
358
        mp_printf(print, "SPI(%u)", spi_num);
Damien George's avatar
Damien George committed
359
360
361
362
    } else {
        if (self->spi->Init.Mode == SPI_MODE_MASTER) {
            // compute baudrate
            uint spi_clock;
363
            if (self->spi->Instance == SPI2 || self->spi->Instance == SPI3) {
Damien George's avatar
Damien George committed
364
365
                // SPI2 and SPI3 are on APB1
                spi_clock = HAL_RCC_GetPCLK1Freq();
366
367
368
            } else {
                // SPI1, SPI4, SPI5 and SPI6 are on APB2
                spi_clock = HAL_RCC_GetPCLK2Freq();
Damien George's avatar
Damien George committed
369
            }
370
371
            uint log_prescaler = (self->spi->Init.BaudRatePrescaler >> 3) + 1;
            uint baudrate = spi_clock >> log_prescaler;
372
            mp_printf(print, "SPI(%u, SPI.MASTER, baudrate=%u, prescaler=%u", spi_num, baudrate, 1 << log_prescaler);
Damien George's avatar
Damien George committed
373
        } else {
374
            mp_printf(print, "SPI(%u, SPI.SLAVE", spi_num);
Damien George's avatar
Damien George committed
375
        }
376
        mp_printf(print, ", polarity=%u, phase=%u, bits=%u", self->spi->Init.CLKPolarity == SPI_POLARITY_LOW ? 0 : 1, self->spi->Init.CLKPhase == SPI_PHASE_1EDGE ? 0 : 1, self->spi->Init.DataSize == SPI_DATASIZE_8BIT ? 8 : 16);
377
        if (self->spi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) {
378
            mp_printf(print, ", crc=0x%x", self->spi->Init.CRCPolynomial);
379
        }
380
        mp_print_str(print, ")");
Damien George's avatar
Damien George committed
381
382
383
    }
}

384
/// \method init(mode, baudrate=328125, *, polarity=1, phase=0, bits=8, firstbit=SPI.MSB, ti=False, crc=None)
385
386
387
388
389
///
/// Initialise the SPI bus with the given parameters:
///
///   - `mode` must be either `SPI.MASTER` or `SPI.SLAVE`.
///   - `baudrate` is the SCK clock rate (only sensible for a master).
390
391
392
393
STATIC mp_obj_t pyb_spi_init_helper(const pyb_spi_obj_t *self, mp_uint_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
    static const mp_arg_t allowed_args[] = {
        { MP_QSTR_mode,     MP_ARG_REQUIRED | MP_ARG_INT, {.u_int = 0} },
        { MP_QSTR_baudrate, MP_ARG_INT, {.u_int = 328125} },
394
        { MP_QSTR_prescaler, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0xffffffff} },
395
396
397
398
399
400
401
402
403
        { MP_QSTR_polarity, MP_ARG_KW_ONLY | MP_ARG_INT,  {.u_int = 1} },
        { MP_QSTR_phase,    MP_ARG_KW_ONLY | MP_ARG_INT,  {.u_int = 0} },
        { MP_QSTR_dir,      MP_ARG_KW_ONLY | MP_ARG_INT,  {.u_int = SPI_DIRECTION_2LINES} },
        { MP_QSTR_bits,     MP_ARG_KW_ONLY | MP_ARG_INT,  {.u_int = 8} },
        { MP_QSTR_nss,      MP_ARG_KW_ONLY | MP_ARG_INT,  {.u_int = SPI_NSS_SOFT} },
        { MP_QSTR_firstbit, MP_ARG_KW_ONLY | MP_ARG_INT,  {.u_int = SPI_FIRSTBIT_MSB} },
        { MP_QSTR_ti,       MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} },
        { MP_QSTR_crc,      MP_ARG_KW_ONLY | MP_ARG_OBJ,  {.u_obj = mp_const_none} },
    };
Damien George's avatar
Damien George committed
404

405
    // parse args
406
407
    mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
    mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
Damien George's avatar
Damien George committed
408
409
410

    // set the SPI configuration values
    SPI_InitTypeDef *init = &self->spi->Init;
411
    init->Mode = args[0].u_int;
Damien George's avatar
Damien George committed
412

413
414
415
416
417
    // configure the prescaler
    mp_uint_t br_prescale = args[2].u_int;
    if (br_prescale == 0xffffffff) {
        // prescaler not given, so select one that yields at most the requested baudrate
        mp_uint_t spi_clock;
418
        if (self->spi->Instance == SPI2 || self->spi->Instance == SPI3) {
419
420
            // SPI2 and SPI3 are on APB1
            spi_clock = HAL_RCC_GetPCLK1Freq();
421
422
423
        } else {
            // SPI1, SPI4, SPI5 and SPI6 are on APB2
            spi_clock = HAL_RCC_GetPCLK2Freq();
424
425
        }
        br_prescale = spi_clock / args[1].u_int;
Damien George's avatar
Damien George committed
426
427
428
429
430
431
432
433
    }
    if (br_prescale <= 2) { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_2; }
    else if (br_prescale <= 4) { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_4; }
    else if (br_prescale <= 8) { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_8; }
    else if (br_prescale <= 16) { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_16; }
    else if (br_prescale <= 32) { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_32; }
    else if (br_prescale <= 64) { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_64; }
    else if (br_prescale <= 128) { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_128; }
434
    else { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_256; }
Damien George's avatar
Damien George committed
435

436
437
438
439
440
441
442
443
    init->CLKPolarity = args[3].u_int == 0 ? SPI_POLARITY_LOW : SPI_POLARITY_HIGH;
    init->CLKPhase = args[4].u_int == 0 ? SPI_PHASE_1EDGE : SPI_PHASE_2EDGE;
    init->Direction = args[5].u_int;
    init->DataSize = (args[6].u_int == 16) ? SPI_DATASIZE_16BIT : SPI_DATASIZE_8BIT;
    init->NSS = args[7].u_int;
    init->FirstBit = args[8].u_int;
    init->TIMode = args[9].u_bool ? SPI_TIMODE_ENABLED : SPI_TIMODE_DISABLED;
    if (args[10].u_obj == mp_const_none) {
Damien George's avatar
Damien George committed
444
445
446
447
        init->CRCCalculation = SPI_CRCCALCULATION_DISABLED;
        init->CRCPolynomial = 0;
    } else {
        init->CRCCalculation = SPI_CRCCALCULATION_ENABLED;
448
        init->CRCPolynomial = mp_obj_get_int(args[10].u_obj);
Damien George's avatar
Damien George committed
449
450
451
    }

    // init the SPI bus
452
    spi_init(self->spi, init->NSS != SPI_NSS_SOFT);
Damien George's avatar
Damien George committed
453
454
455
456

    return mp_const_none;
}

457
458
459
460
461
462
463
/// \classmethod \constructor(bus, ...)
///
/// Construct an SPI object on the given bus.  `bus` can be 1 or 2.
/// With no additional parameters, the SPI object is created but not
/// initialised (it has the settings from the last initialisation of
/// the bus, if any).  If extra arguments are given, the bus is initialised.
/// See `init` for parameters of initialisation.
464
465
466
467
468
469
470
471
///
/// The physical pins of the SPI busses are:
///
///   - `SPI(1)` is on the X position: `(NSS, SCK, MISO, MOSI) = (X5, X6, X7, X8) = (PA4, PA5, PA6, PA7)`
///   - `SPI(2)` is on the Y position: `(NSS, SCK, MISO, MOSI) = (Y5, Y6, Y7, Y8) = (PB12, PB13, PB14, PB15)`
///
/// At the moment, the NSS pin is not used by the SPI driver and is free
/// for other use.
472
STATIC mp_obj_t pyb_spi_make_new(const mp_obj_type_t *type, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *args) {
Damien George's avatar
Damien George committed
473
474
475
    // check arguments
    mp_arg_check_num(n_args, n_kw, 1, MP_OBJ_FUN_ARGS_MAX, true);

476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
    // work out SPI bus
    int spi_id = 0;
    if (MP_OBJ_IS_STR(args[0])) {
        const char *port = mp_obj_str_get_str(args[0]);
        if (0) {
        #ifdef MICROPY_HW_SPI1_NAME
        } else if (strcmp(port, MICROPY_HW_SPI1_NAME) == 0) {
            spi_id = 1;
        #endif
        #ifdef MICROPY_HW_SPI2_NAME
        } else if (strcmp(port, MICROPY_HW_SPI2_NAME) == 0) {
            spi_id = 2;
        #endif
        #ifdef MICROPY_HW_SPI3_NAME
        } else if (strcmp(port, MICROPY_HW_SPI3_NAME) == 0) {
            spi_id = 3;
        #endif
        } else {
            nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
                "SPI(%s) does not exist", port));
        }
    } else {
        spi_id = mp_obj_get_int(args[0]);
        if (spi_id < 1 || spi_id > MP_ARRAY_SIZE(pyb_spi_obj)
500
            || pyb_spi_obj[spi_id - 1].spi == NULL) {
501
502
503
            nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
                "SPI(%d) does not exist", spi_id));
        }
Damien George's avatar
Damien George committed
504
505
506
    }

    // get SPI object
507
    const pyb_spi_obj_t *spi_obj = &pyb_spi_obj[spi_id - 1];
Damien George's avatar
Damien George committed
508
509
510
511
512
513
514
515
516
517
518

    if (n_args > 1 || n_kw > 0) {
        // start the peripheral
        mp_map_t kw_args;
        mp_map_init_fixed_table(&kw_args, n_kw, args + n_args);
        pyb_spi_init_helper(spi_obj, n_args - 1, args + 1, &kw_args);
    }

    return (mp_obj_t)spi_obj;
}

519
STATIC mp_obj_t pyb_spi_init(mp_uint_t n_args, const mp_obj_t *args, mp_map_t *kw_args) {
Damien George's avatar
Damien George committed
520
521
522
523
    return pyb_spi_init_helper(args[0], n_args - 1, args + 1, kw_args);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_spi_init_obj, 1, pyb_spi_init);

524
525
/// \method deinit()
/// Turn off the SPI bus.
Damien George's avatar
Damien George committed
526
527
528
529
530
531
532
STATIC mp_obj_t pyb_spi_deinit(mp_obj_t self_in) {
    pyb_spi_obj_t *self = self_in;
    spi_deinit(self->spi);
    return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_spi_deinit_obj, pyb_spi_deinit);

533
534
535
536
537
538
539
/// \method send(send, *, timeout=5000)
/// Send data on the bus:
///
///   - `send` is the data to send (an integer to send, or a buffer object).
///   - `timeout` is the timeout in milliseconds to wait for the send.
///
/// Return value: `None`.
540
STATIC mp_obj_t pyb_spi_send(mp_uint_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
Damien George's avatar
Damien George committed
541
542
    // TODO assumes transmission size is 8-bits wide

543
544
545
546
    static const mp_arg_t allowed_args[] = {
        { MP_QSTR_send,    MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
        { MP_QSTR_timeout, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 5000} },
    };
Damien George's avatar
Damien George committed
547

548
    // parse args
549
550
551
    pyb_spi_obj_t *self = pos_args[0];
    mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
    mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
552
553

    // get the buffer to send from
Damien George's avatar
Damien George committed
554
    mp_buffer_info_t bufinfo;
555
    uint8_t data[1];
556
    pyb_buf_get_for_send(args[0].u_obj, &bufinfo, data);
Damien George's avatar
Damien George committed
557

558
    // send the data
559
560
561
    // Note: there seems to be a problem sending 1 byte using DMA the first
    // time directly after the SPI/DMA is initialised.  The cause of this is
    // unknown but we sidestep the issue by using polling for 1 byte transfer.
562
    HAL_StatusTypeDef status;
563
    if (bufinfo.len == 1 || query_irq() == IRQ_STATE_DISABLED) {
564
565
        status = HAL_SPI_Transmit(self->spi, bufinfo.buf, bufinfo.len, args[1].u_int);
    } else {
566
        DMA_HandleTypeDef tx_dma;
567
        dma_init(&tx_dma, self->tx_dma_descr, self->spi);
568
569
        self->spi->hdmatx = &tx_dma;
        self->spi->hdmarx = NULL;
570
571
572
573
        status = HAL_SPI_Transmit_DMA(self->spi, bufinfo.buf, bufinfo.len);
        if (status == HAL_OK) {
            status = spi_wait_dma_finished(self->spi, args[1].u_int);
        }
574
        dma_deinit(self->tx_dma_descr);
575
    }
Damien George's avatar
Damien George committed
576
577

    if (status != HAL_OK) {
578
        mp_hal_raise(status);
Damien George's avatar
Damien George committed
579
580
581
582
    }

    return mp_const_none;
}
583
584
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_spi_send_obj, 1, pyb_spi_send);

585
586
587
588
589
590
591
592
593
594
/// \method recv(recv, *, timeout=5000)
///
/// Receive data on the bus:
///
///   - `recv` can be an integer, which is the number of bytes to receive,
///     or a mutable buffer, which will be filled with received bytes.
///   - `timeout` is the timeout in milliseconds to wait for the receive.
///
/// Return value: if `recv` is an integer then a new buffer of the bytes received,
/// otherwise the same buffer that was passed in to `recv`.
595
STATIC mp_obj_t pyb_spi_recv(mp_uint_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
Damien George's avatar
Damien George committed
596
597
    // TODO assumes transmission size is 8-bits wide

598
599
600
601
    static const mp_arg_t allowed_args[] = {
        { MP_QSTR_recv,    MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
        { MP_QSTR_timeout, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 5000} },
    };
602
603

    // parse args
604
605
606
    pyb_spi_obj_t *self = pos_args[0];
    mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
    mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
Damien George's avatar
Damien George committed
607

608
    // get the buffer to receive into
609
610
    vstr_t vstr;
    mp_obj_t o_ret = pyb_buf_get_for_recv(args[0].u_obj, &vstr);
611
612

    // receive the data
613
    HAL_StatusTypeDef status;
614
    if (vstr.len == 1 || query_irq() == IRQ_STATE_DISABLED) {
615
        status = HAL_SPI_Receive(self->spi, (uint8_t*)vstr.buf, vstr.len, args[1].u_int);
616
    } else {
617
618
619
        DMA_HandleTypeDef tx_dma, rx_dma;
        if (self->spi->Init.Mode == SPI_MODE_MASTER) {
            // in master mode the HAL actually does a TransmitReceive call
620
            dma_init(&tx_dma, self->tx_dma_descr, self->spi);
621
622
623
624
            self->spi->hdmatx = &tx_dma;
        } else {
            self->spi->hdmatx = NULL;
        }
625
        dma_init(&rx_dma, self->rx_dma_descr, self->spi);
626
627
        self->spi->hdmarx = &rx_dma;

628
        status = HAL_SPI_Receive_DMA(self->spi, (uint8_t*)vstr.buf, vstr.len);
629
630
631
        if (status == HAL_OK) {
            status = spi_wait_dma_finished(self->spi, args[1].u_int);
        }
632
        if (self->spi->hdmatx != NULL) {
633
            dma_deinit(self->tx_dma_descr);
634
        }
635
        dma_deinit(self->rx_dma_descr);
636
    }
Damien George's avatar
Damien George committed
637
638

    if (status != HAL_OK) {
639
        mp_hal_raise(status);
Damien George's avatar
Damien George committed
640
641
    }

642
    // return the received data
643
644
    if (o_ret != MP_OBJ_NULL) {
        return o_ret;
645
    } else {
646
        return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
647
    }
Damien George's avatar
Damien George committed
648
}
649
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_spi_recv_obj, 1, pyb_spi_recv);
Damien George's avatar
Damien George committed
650

651
652
653
654
655
656
657
658
659
660
661
/// \method send_recv(send, recv=None, *, timeout=5000)
///
/// Send and receive data on the bus at the same time:
///
///   - `send` is the data to send (an integer to send, or a buffer object).
///   - `recv` is a mutable buffer which will be filled with received bytes.
///   It can be the same as `send`, or omitted.  If omitted, a new buffer will
///   be created.
///   - `timeout` is the timeout in milliseconds to wait for the receive.
///
/// Return value: the buffer with the received bytes.
662
STATIC mp_obj_t pyb_spi_send_recv(mp_uint_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
Damien George's avatar
Damien George committed
663
664
    // TODO assumes transmission size is 8-bits wide

665
666
667
668
669
    static const mp_arg_t allowed_args[] = {
        { MP_QSTR_send,    MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
        { MP_QSTR_recv,    MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
        { MP_QSTR_timeout, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 5000} },
    };
Damien George's avatar
Damien George committed
670

671
    // parse args
672
673
674
    pyb_spi_obj_t *self = pos_args[0];
    mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
    mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
675
676
677

    // get buffers to send from/receive to
    mp_buffer_info_t bufinfo_send;
Damien George's avatar
Damien George committed
678
    uint8_t data_send[1];
679
    mp_buffer_info_t bufinfo_recv;
680
    vstr_t vstr_recv;
681
682
    mp_obj_t o_ret;

683
    if (args[0].u_obj == args[1].u_obj) {
684
        // same object for send and receive, it must be a r/w buffer
685
        mp_get_buffer_raise(args[0].u_obj, &bufinfo_send, MP_BUFFER_RW);
686
        bufinfo_recv = bufinfo_send;
687
        o_ret = args[0].u_obj;
Damien George's avatar
Damien George committed
688
    } else {
689
        // get the buffer to send from
690
        pyb_buf_get_for_send(args[0].u_obj, &bufinfo_send, data_send);
691
692

        // get the buffer to receive into
693
        if (args[1].u_obj == MP_OBJ_NULL) {
694
            // only send argument given, so create a fresh buffer of the send length
695
696
697
698
            vstr_init_len(&vstr_recv, bufinfo_send.len);
            bufinfo_recv.len = vstr_recv.len;
            bufinfo_recv.buf = vstr_recv.buf;
            o_ret = MP_OBJ_NULL;
699
700
        } else {
            // recv argument given
701
            mp_get_buffer_raise(args[1].u_obj, &bufinfo_recv, MP_BUFFER_WRITE);
702
703
704
            if (bufinfo_recv.len != bufinfo_send.len) {
                nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "recv must be same length as send"));
            }
705
            o_ret = args[1].u_obj;
706
        }
Damien George's avatar
Damien George committed
707
708
    }

709
    // send and receive the data
710
    HAL_StatusTypeDef status;
711
    if (bufinfo_send.len == 1 || query_irq() == IRQ_STATE_DISABLED) {
712
713
        status = HAL_SPI_TransmitReceive(self->spi, bufinfo_send.buf, bufinfo_recv.buf, bufinfo_send.len, args[2].u_int);
    } else {
714
        DMA_HandleTypeDef tx_dma, rx_dma;
715
        dma_init(&tx_dma, self->tx_dma_descr, self->spi);
716
        self->spi->hdmatx = &tx_dma;
717
        dma_init(&rx_dma, self->rx_dma_descr, self->spi);
718
        self->spi->hdmarx = &rx_dma;
719
720
721
722
        status = HAL_SPI_TransmitReceive_DMA(self->spi, bufinfo_send.buf, bufinfo_recv.buf, bufinfo_send.len);
        if (status == HAL_OK) {
            status = spi_wait_dma_finished(self->spi, args[2].u_int);
        }
723
724
        dma_deinit(self->tx_dma_descr);
        dma_deinit(self->rx_dma_descr);
725
    }
Damien George's avatar
Damien George committed
726
727

    if (status != HAL_OK) {
728
        mp_hal_raise(status);
Damien George's avatar
Damien George committed
729
730
    }

731
    // return the received data
732
733
    if (o_ret != MP_OBJ_NULL) {
        return o_ret;
734
    } else {
735
        return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr_recv);
736
    }
Damien George's avatar
Damien George committed
737
}
738
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_spi_send_recv_obj, 1, pyb_spi_send_recv);
Damien George's avatar
Damien George committed
739
740
741
742
743
744
745
746
747
748

STATIC const mp_map_elem_t pyb_spi_locals_dict_table[] = {
    // instance methods
    { MP_OBJ_NEW_QSTR(MP_QSTR_init), (mp_obj_t)&pyb_spi_init_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_deinit), (mp_obj_t)&pyb_spi_deinit_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_send), (mp_obj_t)&pyb_spi_send_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_recv), (mp_obj_t)&pyb_spi_recv_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_send_recv), (mp_obj_t)&pyb_spi_send_recv_obj },

    // class constants
749
750
751
752
    /// \constant MASTER - for initialising the bus to master mode
    /// \constant SLAVE - for initialising the bus to slave mode
    /// \constant MSB - set the first bit to MSB
    /// \constant LSB - set the first bit to LSB
753
754
755
756
    { MP_OBJ_NEW_QSTR(MP_QSTR_MASTER), MP_OBJ_NEW_SMALL_INT(SPI_MODE_MASTER) },
    { MP_OBJ_NEW_QSTR(MP_QSTR_SLAVE),  MP_OBJ_NEW_SMALL_INT(SPI_MODE_SLAVE) },
    { MP_OBJ_NEW_QSTR(MP_QSTR_MSB),    MP_OBJ_NEW_SMALL_INT(SPI_FIRSTBIT_MSB) },
    { MP_OBJ_NEW_QSTR(MP_QSTR_LSB),    MP_OBJ_NEW_SMALL_INT(SPI_FIRSTBIT_LSB) },
Damien George's avatar
Damien George committed
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
    /* TODO
    { MP_OBJ_NEW_QSTR(MP_QSTR_DIRECTION_2LINES             ((uint32_t)0x00000000)
    { MP_OBJ_NEW_QSTR(MP_QSTR_DIRECTION_2LINES_RXONLY      SPI_CR1_RXONLY
    { MP_OBJ_NEW_QSTR(MP_QSTR_DIRECTION_1LINE              SPI_CR1_BIDIMODE
    { MP_OBJ_NEW_QSTR(MP_QSTR_NSS_SOFT                    SPI_CR1_SSM
    { MP_OBJ_NEW_QSTR(MP_QSTR_NSS_HARD_INPUT              ((uint32_t)0x00000000)
    { MP_OBJ_NEW_QSTR(MP_QSTR_NSS_HARD_OUTPUT             ((uint32_t)0x00040000)
    */
};

STATIC MP_DEFINE_CONST_DICT(pyb_spi_locals_dict, pyb_spi_locals_dict_table);

const mp_obj_type_t pyb_spi_type = {
    { &mp_type_type },
    .name = MP_QSTR_SPI,
    .print = pyb_spi_print,
    .make_new = pyb_spi_make_new,
    .locals_dict = (mp_obj_t)&pyb_spi_locals_dict,
};