spi.c 41.6 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 "extmod/machine_spi.h"
34
#include "irq.h"
Damien George's avatar
Damien George committed
35
36
#include "pin.h"
#include "genhdr/pins.h"
37
#include "bufhelper.h"
38
#include "dma.h"
Damien George's avatar
Damien George committed
39
40
#include "spi.h"

41
42
43
44
45
46
47
48
49
50
/// \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
51
///     spi = SPI(1, SPI.MASTER, baudrate=600000, polarity=1, phase=0, crc=0x7)
52
53
///
/// Only required parameter is mode, SPI.MASTER or SPI.SLAVE.  Polarity can be
54
55
56
/// 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.
57
58
59
60
61
62
63
///
/// 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
64

65
66
67
68
69
70
71
// 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
72
73
74
75
76
77
// 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
78
79
80
81

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

86
#if defined(MICROPY_HW_SPI1_SCK)
Damien George's avatar
Damien George committed
87
SPI_HandleTypeDef SPIHandle1 = {.Instance = NULL};
88
#endif
89
#if defined(MICROPY_HW_SPI2_SCK)
Damien George's avatar
Damien George committed
90
SPI_HandleTypeDef SPIHandle2 = {.Instance = NULL};
91
#endif
92
#if defined(MICROPY_HW_SPI3_SCK)
Damien George's avatar
Damien George committed
93
SPI_HandleTypeDef SPIHandle3 = {.Instance = NULL};
94
#endif
95
96
97
98
99
100
101
102
103
#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
104

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

Damien George's avatar
Damien George committed
138
139
void spi_init0(void) {
    // reset the SPI handles
140
    #if defined(MICROPY_HW_SPI1_SCK)
Damien George's avatar
Damien George committed
141
142
    memset(&SPIHandle1, 0, sizeof(SPI_HandleTypeDef));
    SPIHandle1.Instance = SPI1;
143
144
    #endif
    #if defined(MICROPY_HW_SPI2_SCK)
Damien George's avatar
Damien George committed
145
146
    memset(&SPIHandle2, 0, sizeof(SPI_HandleTypeDef));
    SPIHandle2.Instance = SPI2;
147
148
    #endif
    #if defined(MICROPY_HW_SPI3_SCK)
Damien George's avatar
Damien George committed
149
150
    memset(&SPIHandle3, 0, sizeof(SPI_HandleTypeDef));
    SPIHandle3.Instance = SPI3;
151
    #endif
152
153
154
155
156
157
158
159
160
161
162
163
    #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
164
165
}

166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
STATIC int spi_find(mp_obj_t id) {
    if (MP_OBJ_IS_STR(id)) {
        // given a string id
        const char *port = mp_obj_str_get_str(id);
        if (0) {
        #ifdef MICROPY_HW_SPI1_NAME
        } else if (strcmp(port, MICROPY_HW_SPI1_NAME) == 0) {
            return 1;
        #endif
        #ifdef MICROPY_HW_SPI2_NAME
        } else if (strcmp(port, MICROPY_HW_SPI2_NAME) == 0) {
            return 2;
        #endif
        #ifdef MICROPY_HW_SPI3_NAME
        } else if (strcmp(port, MICROPY_HW_SPI3_NAME) == 0) {
            return 3;
        #endif
        }
        nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
            "SPI(%s) does not exist", port));
    } else {
        // given an integer id
        int spi_id = mp_obj_get_int(id);
        if (spi_id >= 1 && spi_id <= MP_ARRAY_SIZE(pyb_spi_obj)
            && pyb_spi_obj[spi_id - 1].spi != NULL) {
            return spi_id;
        }
        nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
            "SPI(%d) does not exist", spi_id));
    }
}

// sets the parameters in the SPI_InitTypeDef struct
// if an argument is -1 then the corresponding parameter is not changed
STATIC void spi_set_params(SPI_HandleTypeDef *spi, uint32_t prescale, int32_t baudrate,
    int32_t polarity, int32_t phase, int32_t bits, int32_t firstbit) {
    SPI_InitTypeDef *init = &spi->Init;

    if (prescale != 0xffffffff || baudrate != -1) {
        if (prescale == 0xffffffff) {
            // prescaler not given, so select one that yields at most the requested baudrate
            mp_uint_t spi_clock;
            if (spi->Instance == SPI2 || spi->Instance == SPI3) {
                // SPI2 and SPI3 are on APB1
                spi_clock = HAL_RCC_GetPCLK1Freq();
            } else {
                // SPI1, SPI4, SPI5 and SPI6 are on APB2
                spi_clock = HAL_RCC_GetPCLK2Freq();
            }
            prescale = spi_clock / baudrate;
        }
        if (prescale <= 2) { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_2; }
        else if (prescale <= 4) { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_4; }
        else if (prescale <= 8) { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_8; }
        else if (prescale <= 16) { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_16; }
        else if (prescale <= 32) { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_32; }
        else if (prescale <= 64) { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_64; }
        else if (prescale <= 128) { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_128; }
        else { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_256; }
    }

    if (polarity != -1) {
        init->CLKPolarity = polarity == 0 ? SPI_POLARITY_LOW : SPI_POLARITY_HIGH;
    }

    if (phase != -1) {
        init->CLKPhase = phase == 0 ? SPI_PHASE_1EDGE : SPI_PHASE_2EDGE;
    }

    if (bits != -1) {
        init->DataSize = (bits == 16) ? SPI_DATASIZE_16BIT : SPI_DATASIZE_8BIT;
    }

    if (firstbit != -1) {
        init->FirstBit = firstbit;
    }
}

Damien George's avatar
Damien George committed
244
// TODO allow to take a list of pins to use
245
void spi_init(SPI_HandleTypeDef *spi, bool enable_nss_pin) {
246
    const pyb_spi_obj_t *self;
Damien George's avatar
Damien George committed
247
    const pin_obj_t *pins[4];
248
    pins[0] = NULL;
249

250
    if (0) {
251
    #if defined(MICROPY_HW_SPI1_SCK)
252
    } else if (spi->Instance == SPI1) {
253
        self = &pyb_spi_obj[0];
254
        #if defined(MICROPY_HW_SPI1_NSS)
255
        pins[0] = &MICROPY_HW_SPI1_NSS;
256
        #endif
257
258
259
        pins[1] = &MICROPY_HW_SPI1_SCK;
        pins[2] = &MICROPY_HW_SPI1_MISO;
        pins[3] = &MICROPY_HW_SPI1_MOSI;
260
261
        // enable the SPI clock
        __SPI1_CLK_ENABLE();
262
263
    #endif
    #if defined(MICROPY_HW_SPI2_SCK)
264
    } else if (spi->Instance == SPI2) {
265
        self = &pyb_spi_obj[1];
266
        #if defined(MICROPY_HW_SPI2_NSS)
267
        pins[0] = &MICROPY_HW_SPI2_NSS;
268
        #endif
269
270
271
        pins[1] = &MICROPY_HW_SPI2_SCK;
        pins[2] = &MICROPY_HW_SPI2_MISO;
        pins[3] = &MICROPY_HW_SPI2_MOSI;
272
273
        // enable the SPI clock
        __SPI2_CLK_ENABLE();
274
275
    #endif
    #if defined(MICROPY_HW_SPI3_SCK)
276
    } else if (spi->Instance == SPI3) {
277
        self = &pyb_spi_obj[2];
278
        #if defined(MICROPY_HW_SPI3_NSS)
279
        pins[0] = &MICROPY_HW_SPI3_NSS;
280
        #endif
281
282
283
        pins[1] = &MICROPY_HW_SPI3_SCK;
        pins[2] = &MICROPY_HW_SPI3_MISO;
        pins[3] = &MICROPY_HW_SPI3_MOSI;
284
285
        // enable the SPI clock
        __SPI3_CLK_ENABLE();
286
    #endif
287
288
289
    #if defined(MICROPY_HW_SPI4_SCK)
    } else if (spi->Instance == SPI4) {
        self = &pyb_spi_obj[3];
290
        #if defined(MICROPY_HW_SPI4_NSS)
291
        pins[0] = &MICROPY_HW_SPI4_NSS;
292
        #endif
293
294
295
296
297
298
299
300
301
        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];
302
        #if defined(MICROPY_HW_SPI5_NSS)
303
        pins[0] = &MICROPY_HW_SPI5_NSS;
304
        #endif
305
306
307
308
309
310
311
312
313
        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];
314
        #if defined(MICROPY_HW_SPI6_NSS)
315
        pins[0] = &MICROPY_HW_SPI6_NSS;
316
        #endif
317
318
319
320
321
322
        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
323
324
325
    } 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
326
327
    }

328
329
330
    // init the GPIO lines
    uint32_t mode = MP_HAL_PIN_MODE_ALT;
    uint32_t pull = spi->Init.CLKPolarity == SPI_POLARITY_LOW ? MP_HAL_PIN_PULL_DOWN : MP_HAL_PIN_PULL_UP;
331
    for (uint i = (enable_nss_pin && pins[0] ? 0 : 1); i < 4; i++) {
332
        mp_hal_pin_config_alt(pins[i], mode, pull, AF_FN_SPI, (self - &pyb_spi_obj[0]) + 1);
Damien George's avatar
Damien George committed
333
334
    }

335
    // init the SPI device
Damien George's avatar
Damien George committed
336
337
338
339
    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
340
        printf("OSError: HAL_SPI_Init failed\n");
Damien George's avatar
Damien George committed
341
342
        return;
    }
343

344
345
346
    // 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.
347
348
    dma_invalidate_channel(self->tx_dma_descr);
    dma_invalidate_channel(self->rx_dma_descr);
Damien George's avatar
Damien George committed
349
350
351
352
}

void spi_deinit(SPI_HandleTypeDef *spi) {
    HAL_SPI_DeInit(spi);
353
    if (0) {
354
    #if defined(MICROPY_HW_SPI1_SCK)
355
    } else if (spi->Instance == SPI1) {
356
357
        __SPI1_FORCE_RESET();
        __SPI1_RELEASE_RESET();
Damien George's avatar
Damien George committed
358
        __SPI1_CLK_DISABLE();
359
360
    #endif
    #if defined(MICROPY_HW_SPI2_SCK)
Damien George's avatar
Damien George committed
361
    } else if (spi->Instance == SPI2) {
362
363
        __SPI2_FORCE_RESET();
        __SPI2_RELEASE_RESET();
Damien George's avatar
Damien George committed
364
        __SPI2_CLK_DISABLE();
365
366
    #endif
    #if defined(MICROPY_HW_SPI3_SCK)
367
    } else if (spi->Instance == SPI3) {
368
369
        __SPI3_FORCE_RESET();
        __SPI3_RELEASE_RESET();
Damien George's avatar
Damien George committed
370
        __SPI3_CLK_DISABLE();
371
    #endif
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
    #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
390
391
392
    }
}

393
STATIC HAL_StatusTypeDef spi_wait_dma_finished(SPI_HandleTypeDef *spi, uint32_t timeout) {
394
395
396
    // 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).
397
398
399
400
401
402
403
404
405
    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;
}

406
STATIC void spi_transfer(const pyb_spi_obj_t *self, size_t len, const uint8_t *src, uint8_t *dest, uint32_t timeout) {
407
408
409
410
411
412
    // 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.

    HAL_StatusTypeDef status;

413
    if (dest == NULL) {
414
        // send only
415
416
        if (len == 1 || query_irq() == IRQ_STATE_DISABLED) {
            status = HAL_SPI_Transmit(self->spi, (uint8_t*)src, len, timeout);
417
418
419
420
421
        } else {
            DMA_HandleTypeDef tx_dma;
            dma_init(&tx_dma, self->tx_dma_descr, self->spi);
            self->spi->hdmatx = &tx_dma;
            self->spi->hdmarx = NULL;
422
            status = HAL_SPI_Transmit_DMA(self->spi, (uint8_t*)src, len);
423
424
425
426
427
            if (status == HAL_OK) {
                status = spi_wait_dma_finished(self->spi, timeout);
            }
            dma_deinit(self->tx_dma_descr);
        }
428
    } else if (src == NULL) {
429
        // receive only
430
431
        if (len == 1 || query_irq() == IRQ_STATE_DISABLED) {
            status = HAL_SPI_Receive(self->spi, dest, len, timeout);
432
433
434
435
436
437
438
439
440
441
442
443
        } else {
            DMA_HandleTypeDef tx_dma, rx_dma;
            if (self->spi->Init.Mode == SPI_MODE_MASTER) {
                // in master mode the HAL actually does a TransmitReceive call
                dma_init(&tx_dma, self->tx_dma_descr, self->spi);
                self->spi->hdmatx = &tx_dma;
            } else {
                self->spi->hdmatx = NULL;
            }
            dma_init(&rx_dma, self->rx_dma_descr, self->spi);
            self->spi->hdmarx = &rx_dma;

444
            status = HAL_SPI_Receive_DMA(self->spi, dest, len);
445
446
447
448
449
450
451
452
453
454
            if (status == HAL_OK) {
                status = spi_wait_dma_finished(self->spi, timeout);
            }
            if (self->spi->hdmatx != NULL) {
                dma_deinit(self->tx_dma_descr);
            }
            dma_deinit(self->rx_dma_descr);
        }
    } else {
        // send and receive
455
456
        if (len == 1 || query_irq() == IRQ_STATE_DISABLED) {
            status = HAL_SPI_TransmitReceive(self->spi, (uint8_t*)src, dest, len, timeout);
457
458
459
460
461
462
        } else {
            DMA_HandleTypeDef tx_dma, rx_dma;
            dma_init(&tx_dma, self->tx_dma_descr, self->spi);
            self->spi->hdmatx = &tx_dma;
            dma_init(&rx_dma, self->rx_dma_descr, self->spi);
            self->spi->hdmarx = &rx_dma;
463
            status = HAL_SPI_TransmitReceive_DMA(self->spi, (uint8_t*)src, dest, len);
464
465
466
467
468
469
470
471
472
473
474
475
476
            if (status == HAL_OK) {
                status = spi_wait_dma_finished(self->spi, timeout);
            }
            dma_deinit(self->tx_dma_descr);
            dma_deinit(self->rx_dma_descr);
        }
    }

    if (status != HAL_OK) {
        mp_hal_raise(status);
    }
}

477
STATIC void spi_print(const mp_print_t *print, SPI_HandleTypeDef *spi, bool legacy) {
478
    uint spi_num = 1; // default to SPI1
479
480
    if (spi->Instance == SPI2) { spi_num = 2; }
    else if (spi->Instance == SPI3) { spi_num = 3; }
481
    #if defined(SPI4)
482
    else if (spi->Instance == SPI4) { spi_num = 4; }
483
484
    #endif
    #if defined(SPI5)
485
    else if (spi->Instance == SPI5) { spi_num = 5; }
486
487
    #endif
    #if defined(SPI6)
488
    else if (spi->Instance == SPI6) { spi_num = 6; }
489
    #endif
Damien George's avatar
Damien George committed
490

491
492
493
    mp_printf(print, "SPI(%u", spi_num);
    if (spi->State != HAL_SPI_STATE_RESET) {
        if (spi->Init.Mode == SPI_MODE_MASTER) {
Damien George's avatar
Damien George committed
494
495
            // compute baudrate
            uint spi_clock;
496
            if (spi->Instance == SPI2 || spi->Instance == SPI3) {
Damien George's avatar
Damien George committed
497
498
                // SPI2 and SPI3 are on APB1
                spi_clock = HAL_RCC_GetPCLK1Freq();
499
500
501
            } else {
                // SPI1, SPI4, SPI5 and SPI6 are on APB2
                spi_clock = HAL_RCC_GetPCLK2Freq();
Damien George's avatar
Damien George committed
502
            }
503
            uint log_prescaler = (spi->Init.BaudRatePrescaler >> 3) + 1;
504
            uint baudrate = spi_clock >> log_prescaler;
505
506
507
508
509
510
511
            if (legacy) {
                mp_printf(print, ", SPI.MASTER");
            }
            mp_printf(print, ", baudrate=%u", baudrate);
            if (legacy) {
                mp_printf(print, ", prescaler=%u", 1 << log_prescaler);
            }
Damien George's avatar
Damien George committed
512
        } else {
513
            mp_printf(print, ", SPI.SLAVE");
Damien George's avatar
Damien George committed
514
        }
515
516
517
        mp_printf(print, ", polarity=%u, phase=%u, bits=%u", spi->Init.CLKPolarity == SPI_POLARITY_LOW ? 0 : 1, spi->Init.CLKPhase == SPI_PHASE_1EDGE ? 0 : 1, spi->Init.DataSize == SPI_DATASIZE_8BIT ? 8 : 16);
        if (spi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) {
            mp_printf(print, ", crc=0x%x", spi->Init.CRCPolynomial);
518
        }
Damien George's avatar
Damien George committed
519
    }
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
    mp_print_str(print, ")");
}

/******************************************************************************/
/* MicroPython bindings for legacy pyb API                                    */

SPI_HandleTypeDef *spi_get_handle(mp_obj_t o) {
    if (!MP_OBJ_IS_TYPE(o, &pyb_spi_type)) {
        mp_raise_ValueError("expecting an SPI object");
    }
    pyb_spi_obj_t *self = o;
    return self->spi;
}

STATIC void pyb_spi_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
    pyb_spi_obj_t *self = self_in;
    spi_print(print, self->spi, true);
Damien George's avatar
Damien George committed
537
538
}

539
/// \method init(mode, baudrate=328125, *, polarity=1, phase=0, bits=8, firstbit=SPI.MSB, ti=False, crc=None)
540
541
542
543
544
///
/// 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).
545
546
547
548
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} },
549
        { MP_QSTR_prescaler, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0xffffffff} },
550
551
552
553
554
555
556
557
558
        { 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
559

560
    // parse args
561
562
    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
563
564
565

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

568
569
570
    spi_set_params(self->spi, args[2].u_int, args[1].u_int, args[3].u_int, args[4].u_int,
        args[6].u_int, args[8].u_int);

571
572
573
574
    init->Direction = args[5].u_int;
    init->NSS = args[7].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
575
576
577
578
        init->CRCCalculation = SPI_CRCCALCULATION_DISABLED;
        init->CRCPolynomial = 0;
    } else {
        init->CRCCalculation = SPI_CRCCALCULATION_ENABLED;
579
        init->CRCPolynomial = mp_obj_get_int(args[10].u_obj);
Damien George's avatar
Damien George committed
580
581
582
    }

    // init the SPI bus
583
    spi_init(self->spi, init->NSS != SPI_NSS_SOFT);
Damien George's avatar
Damien George committed
584
585
586
587

    return mp_const_none;
}

588
589
590
591
592
593
594
/// \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.
595
596
597
598
599
600
601
602
///
/// 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.
603
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
604
605
606
    // check arguments
    mp_arg_check_num(n_args, n_kw, 1, MP_OBJ_FUN_ARGS_MAX, true);

607
    // work out SPI bus
608
    int spi_id = spi_find(args[0]);
Damien George's avatar
Damien George committed
609
610

    // get SPI object
611
    const pyb_spi_obj_t *spi_obj = &pyb_spi_obj[spi_id - 1];
Damien George's avatar
Damien George committed
612
613
614
615
616
617
618
619
620
621
622

    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;
}

623
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
624
625
626
627
    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);

628
629
/// \method deinit()
/// Turn off the SPI bus.
Damien George's avatar
Damien George committed
630
631
632
633
634
635
636
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);

637
638
639
640
641
642
643
/// \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`.
644
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
645
646
    // TODO assumes transmission size is 8-bits wide

647
648
649
650
    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
651

652
    // parse args
653
654
655
    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);
656
657

    // get the buffer to send from
Damien George's avatar
Damien George committed
658
    mp_buffer_info_t bufinfo;
659
    uint8_t data[1];
660
    pyb_buf_get_for_send(args[0].u_obj, &bufinfo, data);
Damien George's avatar
Damien George committed
661

662
    // send the data
663
    spi_transfer(self, bufinfo.len, bufinfo.buf, NULL, args[1].u_int);
Damien George's avatar
Damien George committed
664
665
666

    return mp_const_none;
}
667
668
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_spi_send_obj, 1, pyb_spi_send);

669
670
671
672
673
674
675
676
677
678
/// \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`.
679
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
680
681
    // TODO assumes transmission size is 8-bits wide

682
683
684
685
    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} },
    };
686
687

    // parse args
688
689
690
    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
691

692
    // get the buffer to receive into
693
694
    vstr_t vstr;
    mp_obj_t o_ret = pyb_buf_get_for_recv(args[0].u_obj, &vstr);
695
696

    // receive the data
697
    spi_transfer(self, vstr.len, NULL, (uint8_t*)vstr.buf, args[1].u_int);
Damien George's avatar
Damien George committed
698

699
    // return the received data
700
701
    if (o_ret != MP_OBJ_NULL) {
        return o_ret;
702
    } else {
703
        return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
704
    }
Damien George's avatar
Damien George committed
705
}
706
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_spi_recv_obj, 1, pyb_spi_recv);
Damien George's avatar
Damien George committed
707

708
709
710
711
712
713
714
715
716
717
718
/// \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.
719
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
720
721
    // TODO assumes transmission size is 8-bits wide

722
723
724
725
726
    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
727

728
    // parse args
729
730
731
    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);
732
733
734

    // get buffers to send from/receive to
    mp_buffer_info_t bufinfo_send;
Damien George's avatar
Damien George committed
735
    uint8_t data_send[1];
736
    mp_buffer_info_t bufinfo_recv;
737
    vstr_t vstr_recv;
738
739
    mp_obj_t o_ret;

740
    if (args[0].u_obj == args[1].u_obj) {
741
        // same object for send and receive, it must be a r/w buffer
742
        mp_get_buffer_raise(args[0].u_obj, &bufinfo_send, MP_BUFFER_RW);
743
        bufinfo_recv = bufinfo_send;
744
        o_ret = args[0].u_obj;
Damien George's avatar
Damien George committed
745
    } else {
746
        // get the buffer to send from
747
        pyb_buf_get_for_send(args[0].u_obj, &bufinfo_send, data_send);
748
749

        // get the buffer to receive into
750
        if (args[1].u_obj == MP_OBJ_NULL) {
751
            // only send argument given, so create a fresh buffer of the send length
752
753
754
755
            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;
756
757
        } else {
            // recv argument given
758
            mp_get_buffer_raise(args[1].u_obj, &bufinfo_recv, MP_BUFFER_WRITE);
759
760
761
            if (bufinfo_recv.len != bufinfo_send.len) {
                nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "recv must be same length as send"));
            }
762
            o_ret = args[1].u_obj;
763
        }
Damien George's avatar
Damien George committed
764
765
    }

766
    // do the transfer
767
    spi_transfer(self, bufinfo_send.len, bufinfo_send.buf, bufinfo_recv.buf, args[2].u_int);
Damien George's avatar
Damien George committed
768

769
    // return the received data
770
771
    if (o_ret != MP_OBJ_NULL) {
        return o_ret;
772
    } else {
773
        return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr_recv);
774
    }
Damien George's avatar
Damien George committed
775
}
776
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_spi_send_recv_obj, 1, pyb_spi_send_recv);
Damien George's avatar
Damien George committed
777
778
779
780
781

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 },
782
783
784
785
786
787
788

    { MP_OBJ_NEW_QSTR(MP_QSTR_read), (mp_obj_t)&mp_machine_spi_read_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_readinto), (mp_obj_t)&mp_machine_spi_readinto_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_write), (mp_obj_t)&mp_machine_spi_write_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_write_readinto), (mp_obj_t)&mp_machine_spi_write_readinto_obj },

    // legacy methods
Damien George's avatar
Damien George committed
789
790
791
792
793
    { 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
794
795
796
797
    /// \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
798
799
800
801
    { 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
802
803
804
805
806
807
808
809
810
811
812
813
    /* 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);

814
815
816
817
STATIC void spi_transfer_machine(mp_obj_base_t *self_in, size_t len, const uint8_t *src, uint8_t *dest) {
    spi_transfer((pyb_spi_obj_t*)self_in, len, src, dest, 100);
}

818
819
820
821
STATIC const mp_machine_spi_p_t pyb_spi_p = {
    .transfer = spi_transfer_machine,
};

Damien George's avatar
Damien George committed
822
823
824
825
826
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,
827
    .protocol = &pyb_spi_p,
Damien George's avatar
Damien George committed
828
829
    .locals_dict = (mp_obj_t)&pyb_spi_locals_dict,
};
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867

/******************************************************************************/
/* MicroPython bindings for machine API                                       */

// for make_new
enum {
    ARG_NEW_id,
    ARG_NEW_baudrate,
    ARG_NEW_polarity,
    ARG_NEW_phase,
    ARG_NEW_bits,
    ARG_NEW_firstbit,
    ARG_NEW_sck,
    ARG_NEW_mosi,
    ARG_NEW_miso
};

// for init
enum {
    ARG_INIT_baudrate,
    ARG_INIT_polarity,
    ARG_INIT_phase,
    ARG_INIT_bits,
    ARG_INIT_firstbit
};

STATIC mp_obj_t machine_soft_spi_make_new(mp_arg_val_t *args);
STATIC void machine_soft_spi_init(mp_obj_t self, mp_arg_val_t *args);
STATIC void machine_soft_spi_deinit(mp_obj_t self);

STATIC mp_obj_t machine_hard_spi_make_new(mp_arg_val_t *args);
STATIC void machine_hard_spi_init(mp_obj_t self, mp_arg_val_t *args);
STATIC void machine_hard_spi_deinit(mp_obj_t self);

/* common code for both soft and hard implementations *************************/

STATIC mp_obj_t machine_spi_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) {
    static const mp_arg_t allowed_args[] = {
868
        { MP_QSTR_id,       MP_ARG_OBJ, {.u_obj = MP_OBJ_NEW_SMALL_INT(-1)} },
869
870
871
872
873
874
875
876
877
878
879
880
881
882
        { MP_QSTR_baudrate, MP_ARG_INT, {.u_int = 500000} },
        { MP_QSTR_polarity, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} },
        { MP_QSTR_phase,    MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} },
        { MP_QSTR_bits,     MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 8} },
        { MP_QSTR_firstbit, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = SPI_FIRSTBIT_MSB} },
        { MP_QSTR_sck,      MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
        { MP_QSTR_mosi,     MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
        { MP_QSTR_miso,     MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
    };

    // parse args
    mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
    mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);

883
    if (args[ARG_NEW_id].u_obj == MP_OBJ_NEW_SMALL_INT(-1)) {
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
        // software SPI
        return machine_soft_spi_make_new(args);
    } else {
        // hardware peripheral id given
        return machine_hard_spi_make_new(args);
    }
}

STATIC mp_obj_t machine_spi_init(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
    static const mp_arg_t allowed_args[] = {
        { MP_QSTR_baudrate, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = -1} },
        { 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 = -1} },
        { MP_QSTR_bits,     MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = -1} },
        { MP_QSTR_firstbit, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = -1} },
    };

    // parse args
    mp_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);

    // dispatch to specific implementation
    if (mp_obj_get_type(self) == &machine_soft_spi_type) {
        machine_soft_spi_init(self, args);
    } else {
        machine_hard_spi_init(self, args);
    }

    return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(machine_spi_init_obj, 1, machine_spi_init);

STATIC mp_obj_t machine_spi_deinit(mp_obj_t self) {
    // dispatch to specific implementation
    if (mp_obj_get_type(self) == &machine_soft_spi_type) {
        machine_soft_spi_deinit(self);
    } else {
        machine_hard_spi_deinit(self);
    }
    return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(machine_spi_deinit_obj, machine_spi_deinit);

STATIC const mp_rom_map_elem_t machine_spi_locals_dict_table[] = {
    { MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&machine_spi_init_obj) },
    { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&machine_spi_deinit_obj) },
    { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_machine_spi_read_obj) },
    { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&mp_machine_spi_readinto_obj) },
    { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_machine_spi_write_obj) },
    { MP_ROM_QSTR(MP_QSTR_write_readinto), MP_ROM_PTR(&mp_machine_spi_write_readinto_obj) },

    { MP_ROM_QSTR(MP_QSTR_MSB), MP_ROM_INT(SPI_FIRSTBIT_MSB) },
    { MP_ROM_QSTR(MP_QSTR_LSB), MP_ROM_INT(SPI_FIRSTBIT_LSB) },
};

STATIC MP_DEFINE_CONST_DICT(machine_spi_locals_dict, machine_spi_locals_dict_table);

/* code for soft implementation ***********************************************/

944
945
946
// for the software SPI implementation, this is roughly the max baudrate
#define MAX_BAUDRATE (HAL_RCC_GetSysClockFreq() / 48)

947
STATIC uint32_t baudrate_from_delay_half(uint32_t delay_half) {
948
949
950
951
952
    if (delay_half == MICROPY_PY_MACHINE_SPI_MIN_DELAY) {
        return MAX_BAUDRATE;
    } else {
        return 500000 / delay_half;
    }
953
954
955
}

STATIC uint32_t baudrate_to_delay_half(uint32_t baudrate) {
956
957
958
959
960
961
962
963
964
    if (baudrate >= MAX_BAUDRATE) {
        return MICROPY_PY_MACHINE_SPI_MIN_DELAY;
    } else {
        uint32_t delay_half = 500000 / baudrate;
        // round delay_half up so that: actual_baudrate <= requested_baudrate
        if (500000 % baudrate != 0) {
            delay_half += 1;
        }
        return delay_half;
965
966
967
    }
}

968
969
970
STATIC void machine_soft_spi_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
    mp_machine_soft_spi_obj_t *self = MP_OBJ_TO_PTR(self_in);
    mp_printf(print, "SPI(-1, baudrate=%u, polarity=%u, phase=%u, sck=%q, mosi=%q, miso=%q)",
971
        baudrate_from_delay_half(self->delay_half), self->polarity, self->phase,
972
973
974
975
976
977
978
979
980
        self->sck->name, self->mosi->name, self->miso->name);
}

STATIC mp_obj_t machine_soft_spi_make_new(mp_arg_val_t *args) {
    // create new object
    mp_machine_soft_spi_obj_t *self = m_new_obj(mp_machine_soft_spi_obj_t);
    self->base.type = &machine_soft_spi_type;

    // set parameters
981
    self->delay_half = baudrate_to_delay_half(args[ARG_NEW_baudrate].u_int);
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
    self->polarity = args[ARG_NEW_polarity].u_int;
    self->phase = args[ARG_NEW_phase].u_int;
    if (args[ARG_NEW_bits].u_int != 8) {
        mp_raise_ValueError("bits must be 8");
    }
    if (args[ARG_NEW_firstbit].u_int != SPI_FIRSTBIT_MSB) {
        mp_raise_ValueError("firstbit must be MSB");
    }
    if (args[ARG_NEW_sck].u_obj == MP_OBJ_NULL
        || args[ARG_NEW_mosi].u_obj == MP_OBJ_NULL
        || args[ARG_NEW_miso].u_obj == MP_OBJ_NULL) {
        mp_raise_ValueError("must specify all of sck/mosi/miso");
    }
    self->sck = mp_hal_get_pin_obj(args[ARG_NEW_sck].u_obj);
    self->mosi = mp_hal_get_pin_obj(args[ARG_NEW_mosi].u_obj);
    self->miso = mp_hal_get_pin_obj(args[ARG_NEW_miso].u_obj);

    // configure pins
    mp_hal_pin_write(self->sck, self->polarity);
    mp_hal_pin_output(self->sck);
    mp_hal_pin_output(self->mosi);
    mp_hal_pin_input(self->miso);

    return MP_OBJ_FROM_PTR(self);
}

STATIC void machine_soft_spi_init(mp_obj_t self_in, mp_arg_val_t *args) {
    mp_machine_soft_spi_obj_t *self = MP_OBJ_TO_PTR(self_in);

    // update parameters
    if (args[ARG_INIT_baudrate].u_int != -1) {
1013
        self->delay_half = baudrate_to_delay_half(args[ARG_INIT_baudrate].u_int);
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
    }
    if (args[ARG_INIT_polarity].u_int != -1) {
        self->polarity = args[ARG_INIT_polarity].u_int;
    }
    if (args[ARG_INIT_phase].u_int != -1) {
        self->phase = args[ARG_INIT_phase].u_int;
    }
}

STATIC void machine_soft_spi_deinit(mp_obj_t self) {
    // nothing to do
    (void)self;
}

STATIC const mp_machine_spi_p_t machine_soft_spi_p = {
    .transfer = mp_machine_soft_spi_transfer,
};

const mp_obj_type_t machine_soft_spi_type = {
    { &mp_type_type },
    .name = MP_QSTR_SoftSPI,
    .print = machine_soft_spi_print,
    .make_new = machine_spi_make_new,
    .protocol = &machine_soft_spi_p,
    .locals_dict = (mp_obj_t)&machine_spi_locals_dict,
};

/* code for hard implementation ***********************************************/

typedef struct _machine_hard_spi_obj_t {
    mp_obj_base_t base;
    const pyb_spi_obj_t *pyb;
} machine_hard_spi_obj_t;

STATIC const machine_hard_spi_obj_t machine_hard_spi_obj[] = {
    {{&machine_hard_spi_type}, &pyb_spi_obj[0]},
    {{&machine_hard_spi_type}, &pyb_spi_obj[1]},
    {{&machine_hard_spi_type}, &pyb_spi_obj[2]},
    {{&machine_hard_spi_type}, &pyb_spi_obj[3]},
    {{&machine_hard_spi_type}, &pyb_spi_obj[4]},
    {{&machine_hard_spi_type}, &pyb_spi_obj[5]},
};

STATIC void machine_hard_spi_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
    machine_hard_spi_obj_t *self = self_in;
    spi_print(print, self->pyb->spi, false);
}

STATIC mp_obj_t machine_hard_spi_make_new(mp_arg_val_t *args) {
    // get static peripheral object
    int spi_id = spi_find(args[ARG_NEW_id].u_obj);
    const machine_hard_spi_obj_t *self = &machine_hard_spi_obj[spi_id - 1];

    // here we would check the sck/mosi/miso pins and configure them, but it's not implemented
    if (args[ARG_NEW_sck].u_obj != MP_OBJ_NULL
        || args[ARG_NEW_mosi].u_obj != MP_OBJ_NULL
        || args[ARG_NEW_miso].u_obj != MP_OBJ_NULL) {
        mp_raise_ValueError("explicit choice of sck/mosi/miso is not implemented");
    }

    // set the SPI configuration values
    SPI_InitTypeDef *init = &self->pyb->spi->Init;
    init->Mode = SPI_MODE_MASTER;

    // these parameters are not currently configurable
    init->Direction = SPI_DIRECTION_2LINES;
    init->NSS = SPI_NSS_SOFT;
    init->TIMode = SPI_TIMODE_DISABLED;
    init->CRCCalculation = SPI_CRCCALCULATION_DISABLED;
    init->CRCPolynomial = 0;

    // set configurable paramaters
    spi_set_params(self->pyb->spi, 0xffffffff, args[ARG_NEW_baudrate].u_int,
        args[ARG_NEW_polarity].u_int, args[ARG_NEW_phase].u_int, args[ARG_NEW_bits].u_int,
        args[ARG_NEW_firstbit].u_int);

    // init the SPI bus
    spi_init(self->pyb->spi, false);

    return MP_OBJ_FROM_PTR(self);
}

STATIC void machine_hard_spi_init(mp_obj_t self_in, mp_arg_val_t *args) {
    machine_hard_spi_obj_t *self = self_in;

    // set the SPI configuration values
    spi_set_params(self->pyb->spi, 0xffffffff, args[ARG_INIT_baudrate].u_int,
        args[ARG_INIT_polarity].u_int, args[ARG_INIT_phase].u_int, args[ARG_INIT_bits].u_int,
        args[ARG_INIT_firstbit].u_int);

    // re-init the SPI bus
    spi_init(self->pyb->spi, false);
}

STATIC void machine_hard_spi_deinit(mp_obj_t self_in) {
    machine_hard_spi_obj_t *self = self_in;
    spi_deinit(self->pyb->spi);
}

STATIC void machine_hard_spi_transfer(mp_obj_base_t *self_in, size_t len, const uint8_t *src, uint8_t *dest) {
    machine_hard_spi_obj_t *self = (machine_hard_spi_obj_t*)self_in;
    spi_transfer(self->pyb, len, src, dest, 100);
}

STATIC const mp_machine_spi_p_t machine_hard_spi_p = {
    .transfer = machine_hard_spi_transfer,
};

const mp_obj_type_t machine_hard_spi_type = {
    { &mp_type_type },
    .name = MP_QSTR_SPI,
    .print = machine_hard_spi_print,
    .make_new = machine_spi_make_new,
    .protocol = &machine_hard_spi_p,
    .locals_dict = (mp_obj_t)&machine_spi_locals_dict,
};