blob: 6eb83fc09c37abcce16b60a2be6a29ae3b13a7e2 [file] [log] [blame]
Damien Georgebc08c882016-12-06 12:20:10 +11001/*
2 * This file is part of the MicroPython project, http://micropython.org/
3 *
4 * The MIT License (MIT)
5 *
6 * Copyright (c) 2017 "Eric Poulsen" <eric@zyxod.com>
7 *
8 * Permission is hereby granted, free of charge, to any person obtaining a copy
9 * of this software and associated documentation files (the "Software"), to deal
10 * in the Software without restriction, including without limitation the rights
11 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 * copies of the Software, and to permit persons to whom the Software is
13 * furnished to do so, subject to the following conditions:
14 *
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24 * THE SOFTWARE.
25 */
26
27#include <stdio.h>
28#include <stdint.h>
29#include <string.h>
30
31#include "py/runtime.h"
32#include "py/stream.h"
33#include "py/mphal.h"
Damien George90023b42023-10-26 11:39:40 +110034#include "extmod/modmachine.h"
Damien Georgebc08c882016-12-06 12:20:10 +110035
36#include "driver/spi_master.h"
Damien Georgee4650122023-05-09 09:52:54 +100037#include "soc/gpio_sig_map.h"
38#include "soc/spi_pins.h"
Damien Georgebc08c882016-12-06 12:20:10 +110039
Tomas Vanekd0888652021-11-29 12:57:28 +010040// SPI mappings by device, naming used by IDF old/new
Andrew Leech6d799372023-06-26 11:53:28 +100041// upython | ESP32 | ESP32S2 | ESP32S3 | ESP32C3 | ESP32C6
42// ----------+-----------+-----------+---------+---------+---------
43// SPI(id=1) | HSPI/SPI2 | FSPI/SPI2 | SPI2 | SPI2 | SPI2
44// SPI(id=2) | VSPI/SPI3 | HSPI/SPI3 | SPI3 | err | err
Tomas Vanekd0888652021-11-29 12:57:28 +010045
Damien Georgeb2adfc82023-07-25 11:33:51 +100046// Number of available hardware SPI peripherals.
47#if SOC_SPI_PERIPH_NUM > 2
48#define MICROPY_HW_SPI_MAX (2)
49#else
50#define MICROPY_HW_SPI_MAX (1)
51#endif
52
Tomas Vanekd0888652021-11-29 12:57:28 +010053// Default pins for SPI(id=1) aka IDF SPI2, can be overridden by a board
Damien Georgeb24fcd72021-03-11 13:32:00 +110054#ifndef MICROPY_HW_SPI1_SCK
Tomas Vanekd0888652021-11-29 12:57:28 +010055// Use IO_MUX pins by default.
56// If SPI lines are routed to other pins through GPIO matrix
57// routing adds some delay and lower limit applies to SPI clk freq
Damien Georgee4650122023-05-09 09:52:54 +100058#define MICROPY_HW_SPI1_SCK SPI2_IOMUX_PIN_NUM_CLK
59#define MICROPY_HW_SPI1_MOSI SPI2_IOMUX_PIN_NUM_MOSI
60#define MICROPY_HW_SPI1_MISO SPI2_IOMUX_PIN_NUM_MISO
Tomas Vanekd0888652021-11-29 12:57:28 +010061#endif
Damien Georgeb24fcd72021-03-11 13:32:00 +110062
Tomas Vaneke7611522021-11-29 16:49:11 +010063// Default pins for SPI(id=2) aka IDF SPI3, can be overridden by a board
Damien Georgeb24fcd72021-03-11 13:32:00 +110064#ifndef MICROPY_HW_SPI2_SCK
Tomas Vaneke7611522021-11-29 16:49:11 +010065#if CONFIG_IDF_TARGET_ESP32
66// ESP32 has IO_MUX pins for VSPI/SPI3 lines, use them as defaults
Damien Georgee4650122023-05-09 09:52:54 +100067#define MICROPY_HW_SPI2_SCK SPI3_IOMUX_PIN_NUM_CLK // pin 18
68#define MICROPY_HW_SPI2_MOSI SPI3_IOMUX_PIN_NUM_MOSI // pin 23
69#define MICROPY_HW_SPI2_MISO SPI3_IOMUX_PIN_NUM_MISO // pin 19
Tomas Vaneke7611522021-11-29 16:49:11 +010070#elif CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32S3
71// ESP32S2 and S3 uses GPIO matrix for SPI3 pins, no IO_MUX possible
72// Set defaults to the pins used by SPI2 in Octal mode
73#define MICROPY_HW_SPI2_SCK (36)
74#define MICROPY_HW_SPI2_MOSI (35)
75#define MICROPY_HW_SPI2_MISO (37)
76#endif
Damien Georgeb24fcd72021-03-11 13:32:00 +110077#endif
78
Eric Poulsen9123c8d2017-11-28 18:48:30 -080079#define MP_HW_SPI_MAX_XFER_BYTES (4092)
80#define MP_HW_SPI_MAX_XFER_BITS (MP_HW_SPI_MAX_XFER_BYTES * 8) // Has to be an even multiple of 8
81
Damien Georgeb24fcd72021-03-11 13:32:00 +110082typedef struct _machine_hw_spi_default_pins_t {
Trent Piepho31e131b2024-02-10 12:07:46 -080083 union {
84 int8_t array[3];
85 struct {
86 // Must be in enum's ARG_sck, ARG_mosi, ARG_miso, etc. order
87 int8_t sck;
88 int8_t mosi;
89 int8_t miso;
90 } pins;
91 };
Damien Georgeb24fcd72021-03-11 13:32:00 +110092} machine_hw_spi_default_pins_t;
93
Damien Georgebc08c882016-12-06 12:20:10 +110094typedef struct _machine_hw_spi_obj_t {
95 mp_obj_base_t base;
96 spi_host_device_t host;
97 uint32_t baudrate;
98 uint8_t polarity;
99 uint8_t phase;
100 uint8_t bits;
101 uint8_t firstbit;
102 int8_t sck;
103 int8_t mosi;
104 int8_t miso;
105 spi_device_handle_t spi;
106 enum {
107 MACHINE_HW_SPI_STATE_NONE,
108 MACHINE_HW_SPI_STATE_INIT,
109 MACHINE_HW_SPI_STATE_DEINIT
110 } state;
111} machine_hw_spi_obj_t;
112
Damien Georgeb24fcd72021-03-11 13:32:00 +1100113// Default pin mappings for the hardware SPI instances
Angus Grattondecf8e62024-02-27 15:32:29 +1100114static const machine_hw_spi_default_pins_t machine_hw_spi_default_pins[MICROPY_HW_SPI_MAX] = {
Trent Piepho31e131b2024-02-10 12:07:46 -0800115 { .pins = { .sck = MICROPY_HW_SPI1_SCK, .mosi = MICROPY_HW_SPI1_MOSI, .miso = MICROPY_HW_SPI1_MISO }},
Tomas Vaneke7611522021-11-29 16:49:11 +0100116 #ifdef MICROPY_HW_SPI2_SCK
Trent Piepho31e131b2024-02-10 12:07:46 -0800117 { .pins = { .sck = MICROPY_HW_SPI2_SCK, .mosi = MICROPY_HW_SPI2_MOSI, .miso = MICROPY_HW_SPI2_MISO }},
Tomas Vaneke7611522021-11-29 16:49:11 +0100118 #endif
Damien Georgeb24fcd72021-03-11 13:32:00 +1100119};
120
Trent Piepho31e131b2024-02-10 12:07:46 -0800121// Common arguments for init() and make new
122enum { ARG_id, ARG_baudrate, ARG_polarity, ARG_phase, ARG_bits, ARG_firstbit, ARG_sck, ARG_mosi, ARG_miso };
123static const mp_arg_t spi_allowed_args[] = {
124 { MP_QSTR_id, MP_ARG_REQUIRED | MP_ARG_INT, {.u_int = -1} },
125 { MP_QSTR_baudrate, MP_ARG_INT, {.u_int = -1} },
126 { MP_QSTR_polarity, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = -1} },
127 { MP_QSTR_phase, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = -1} },
128 { MP_QSTR_bits, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = -1} },
129 { MP_QSTR_firstbit, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = -1} },
130 { MP_QSTR_sck, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
131 { MP_QSTR_mosi, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
132 { MP_QSTR_miso, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
133};
134
Damien Georgeb2adfc82023-07-25 11:33:51 +1000135// Static objects mapping to SPI2 (and SPI3 if available) hardware peripherals.
Angus Grattondecf8e62024-02-27 15:32:29 +1100136static machine_hw_spi_obj_t machine_hw_spi_obj[MICROPY_HW_SPI_MAX];
Damien Georgeda72bb62019-01-23 23:47:36 +1100137
Angus Grattondecf8e62024-02-27 15:32:29 +1100138static void machine_hw_spi_deinit_internal(machine_hw_spi_obj_t *self) {
Damien Georgebc08c882016-12-06 12:20:10 +1100139 switch (spi_bus_remove_device(self->spi)) {
140 case ESP_ERR_INVALID_ARG:
Jim Mussareddef76fe2020-03-02 22:35:22 +1100141 mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("invalid configuration"));
Damien Georgebc08c882016-12-06 12:20:10 +1100142 return;
143
144 case ESP_ERR_INVALID_STATE:
Jim Mussareddef76fe2020-03-02 22:35:22 +1100145 mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("SPI device already freed"));
Damien Georgebc08c882016-12-06 12:20:10 +1100146 return;
147 }
148
149 switch (spi_bus_free(self->host)) {
150 case ESP_ERR_INVALID_ARG:
Jim Mussareddef76fe2020-03-02 22:35:22 +1100151 mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("invalid configuration"));
Damien Georgebc08c882016-12-06 12:20:10 +1100152 return;
153
154 case ESP_ERR_INVALID_STATE:
Jim Mussareddef76fe2020-03-02 22:35:22 +1100155 mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("SPI bus already freed"));
Damien Georgebc08c882016-12-06 12:20:10 +1100156 return;
157 }
158
159 int8_t pins[3] = {self->miso, self->mosi, self->sck};
160
161 for (int i = 0; i < 3; i++) {
162 if (pins[i] != -1) {
Damien Georgee4650122023-05-09 09:52:54 +1000163 esp_rom_gpio_pad_select_gpio(pins[i]);
164 esp_rom_gpio_connect_out_signal(pins[i], SIG_GPIO_OUT_IDX, false, false);
Damien Georgebc08c882016-12-06 12:20:10 +1100165 gpio_set_direction(pins[i], GPIO_MODE_INPUT);
166 }
167 }
168}
169
Angus Grattondecf8e62024-02-27 15:32:29 +1100170static void machine_hw_spi_init_internal(machine_hw_spi_obj_t *self, mp_arg_val_t args[]) {
Damien Georgebc08c882016-12-06 12:20:10 +1100171
172 // if we're not initialized, then we're
173 // implicitly 'changed', since this is the init routine
174 bool changed = self->state != MACHINE_HW_SPI_STATE_INIT;
175
176 esp_err_t ret;
177
178 machine_hw_spi_obj_t old_self = *self;
179
Trent Piepho31e131b2024-02-10 12:07:46 -0800180 if (args[ARG_baudrate].u_int != -1) {
Jonathan Hoggeb3029c2021-07-12 11:35:25 +0100181 // calculate the actual clock frequency that the SPI peripheral can produce
Trent Piepho31e131b2024-02-10 12:07:46 -0800182 uint32_t baudrate = spi_get_actual_clock(APB_CLK_FREQ, args[ARG_baudrate].u_int, 0);
Jonathan Hoggeb3029c2021-07-12 11:35:25 +0100183 if (baudrate != self->baudrate) {
184 self->baudrate = baudrate;
185 changed = true;
186 }
Damien Georgebc08c882016-12-06 12:20:10 +1100187 }
188
Trent Piepho31e131b2024-02-10 12:07:46 -0800189 if (args[ARG_polarity].u_int != -1 && args[ARG_polarity].u_int != self->polarity) {
190 self->polarity = args[ARG_polarity].u_int;
Damien Georgebc08c882016-12-06 12:20:10 +1100191 changed = true;
192 }
193
Trent Piepho31e131b2024-02-10 12:07:46 -0800194 if (args[ARG_phase].u_int != -1 && args[ARG_phase].u_int != self->phase) {
195 self->phase = args[ARG_phase].u_int;
Damien Georgebc08c882016-12-06 12:20:10 +1100196 changed = true;
197 }
198
Alessandro Gatti86c71a02024-10-01 21:40:06 +0200199 if (args[ARG_bits].u_int != -1 && args[ARG_bits].u_int <= 0) {
200 mp_raise_ValueError(MP_ERROR_TEXT("invalid bits"));
201 }
202
Trent Piepho31e131b2024-02-10 12:07:46 -0800203 if (args[ARG_bits].u_int != -1 && args[ARG_bits].u_int != self->bits) {
204 self->bits = args[ARG_bits].u_int;
Damien Georgebc08c882016-12-06 12:20:10 +1100205 changed = true;
206 }
207
Trent Piepho31e131b2024-02-10 12:07:46 -0800208 if (args[ARG_firstbit].u_int != -1 && args[ARG_firstbit].u_int != self->firstbit) {
209 self->firstbit = args[ARG_firstbit].u_int;
Damien Georgebc08c882016-12-06 12:20:10 +1100210 changed = true;
211 }
212
Trent Piepho31e131b2024-02-10 12:07:46 -0800213 if (args[ARG_sck].u_int != -2 && args[ARG_sck].u_int != self->sck) {
214 self->sck = args[ARG_sck].u_int;
Damien Georgebc08c882016-12-06 12:20:10 +1100215 changed = true;
216 }
217
Trent Piepho31e131b2024-02-10 12:07:46 -0800218 if (args[ARG_mosi].u_int != -2 && args[ARG_mosi].u_int != self->mosi) {
219 self->mosi = args[ARG_mosi].u_int;
Damien Georgebc08c882016-12-06 12:20:10 +1100220 changed = true;
221 }
222
Trent Piepho31e131b2024-02-10 12:07:46 -0800223 if (args[ARG_miso].u_int != -2 && args[ARG_miso].u_int != self->miso) {
224 self->miso = args[ARG_miso].u_int;
Damien Georgebc08c882016-12-06 12:20:10 +1100225 changed = true;
226 }
227
Damien Georgebc08c882016-12-06 12:20:10 +1100228 if (changed) {
229 if (self->state == MACHINE_HW_SPI_STATE_INIT) {
230 self->state = MACHINE_HW_SPI_STATE_DEINIT;
231 machine_hw_spi_deinit_internal(&old_self);
232 }
233 } else {
234 return; // no changes
235 }
236
237 spi_bus_config_t buscfg = {
238 .miso_io_num = self->miso,
239 .mosi_io_num = self->mosi,
240 .sclk_io_num = self->sck,
241 .quadwp_io_num = -1,
242 .quadhd_io_num = -1
243 };
244
245 spi_device_interface_config_t devcfg = {
246 .clock_speed_hz = self->baudrate,
247 .mode = self->phase | (self->polarity << 1),
248 .spics_io_num = -1, // No CS pin
Jonathan Hogg8be29b92021-07-16 16:12:45 +0100249 .queue_size = 2,
Damien Georgebc08c882016-12-06 12:20:10 +1100250 .flags = self->firstbit == MICROPY_PY_MACHINE_SPI_LSB ? SPI_DEVICE_TXBIT_LSBFIRST | SPI_DEVICE_RXBIT_LSBFIRST : 0,
251 .pre_cb = NULL
252 };
253
stijn84fa3312020-04-16 09:13:57 +0200254 // Initialize the SPI bus
Damien Georgebc08c882016-12-06 12:20:10 +1100255
Damien Georged82f3442019-01-23 23:40:06 +1100256 // Select DMA channel based on the hardware SPI host
257 int dma_chan = 0;
Andrew Leech6d799372023-06-26 11:53:28 +1000258 #if CONFIG_IDF_TARGET_ESP32
Damien Georgee4650122023-05-09 09:52:54 +1000259 if (self->host == SPI2_HOST) {
Damien Georged82f3442019-01-23 23:40:06 +1100260 dma_chan = 1;
Damien George95c614e2022-10-04 17:43:04 +1100261 } else {
Damien Georged82f3442019-01-23 23:40:06 +1100262 dma_chan = 2;
263 }
Andrew Leech6d799372023-06-26 11:53:28 +1000264 #else
265 dma_chan = SPI_DMA_CH_AUTO;
Damien George95c614e2022-10-04 17:43:04 +1100266 #endif
Damien Georged82f3442019-01-23 23:40:06 +1100267
268 ret = spi_bus_initialize(self->host, &buscfg, dma_chan);
Damien Georgebc08c882016-12-06 12:20:10 +1100269 switch (ret) {
270 case ESP_ERR_INVALID_ARG:
Jim Mussareddef76fe2020-03-02 22:35:22 +1100271 mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("invalid configuration"));
Damien Georgebc08c882016-12-06 12:20:10 +1100272 return;
273
274 case ESP_ERR_INVALID_STATE:
Jim Mussareddef76fe2020-03-02 22:35:22 +1100275 mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("SPI host already in use"));
Damien Georgebc08c882016-12-06 12:20:10 +1100276 return;
277 }
278
279 ret = spi_bus_add_device(self->host, &devcfg, &self->spi);
280 switch (ret) {
281 case ESP_ERR_INVALID_ARG:
Jim Mussareddef76fe2020-03-02 22:35:22 +1100282 mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("invalid configuration"));
Damien Georgebc08c882016-12-06 12:20:10 +1100283 spi_bus_free(self->host);
284 return;
285
286 case ESP_ERR_NO_MEM:
Jim Mussareddef76fe2020-03-02 22:35:22 +1100287 mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("out of memory"));
Damien Georgebc08c882016-12-06 12:20:10 +1100288 spi_bus_free(self->host);
289 return;
290
291 case ESP_ERR_NOT_FOUND:
Jim Mussareddef76fe2020-03-02 22:35:22 +1100292 mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("no free slots"));
Damien Georgebc08c882016-12-06 12:20:10 +1100293 spi_bus_free(self->host);
294 return;
295 }
296 self->state = MACHINE_HW_SPI_STATE_INIT;
297}
298
Angus Grattondecf8e62024-02-27 15:32:29 +1100299static void machine_hw_spi_deinit(mp_obj_base_t *self_in) {
Damien George1a3e3862020-03-27 00:35:04 +1100300 machine_hw_spi_obj_t *self = (machine_hw_spi_obj_t *)self_in;
Damien Georgebc08c882016-12-06 12:20:10 +1100301 if (self->state == MACHINE_HW_SPI_STATE_INIT) {
302 self->state = MACHINE_HW_SPI_STATE_DEINIT;
303 machine_hw_spi_deinit_internal(self);
304 }
305}
306
Angus Grattondecf8e62024-02-27 15:32:29 +1100307static mp_uint_t gcd(mp_uint_t x, mp_uint_t y) {
Jonathan Hogg8be29b92021-07-16 16:12:45 +0100308 while (x != y) {
309 if (x > y) {
310 x -= y;
311 } else {
312 y -= x;
313 }
314 }
315 return x;
316}
317
Angus Grattondecf8e62024-02-27 15:32:29 +1100318static void machine_hw_spi_transfer(mp_obj_base_t *self_in, size_t len, const uint8_t *src, uint8_t *dest) {
Damien Georgebc08c882016-12-06 12:20:10 +1100319 machine_hw_spi_obj_t *self = MP_OBJ_TO_PTR(self_in);
320
Damien Georgebc08c882016-12-06 12:20:10 +1100321 if (self->state == MACHINE_HW_SPI_STATE_DEINIT) {
Jim Mussareddef76fe2020-03-02 22:35:22 +1100322 mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("transfer on deinitialized SPI"));
Damien Georgebc08c882016-12-06 12:20:10 +1100323 return;
324 }
325
Eric Poulsen9123c8d2017-11-28 18:48:30 -0800326 // Round to nearest whole set of bits
327 int bits_to_send = len * 8 / self->bits * self->bits;
328
Jonathan Hogg8be29b92021-07-16 16:12:45 +0100329 if (!bits_to_send) {
330 mp_raise_ValueError(MP_ERROR_TEXT("buffer too short"));
331 }
Eric Poulsen9123c8d2017-11-28 18:48:30 -0800332
333 if (len <= 4) {
Jonathan Hogg8be29b92021-07-16 16:12:45 +0100334 spi_transaction_t transaction = { 0 };
335
Damien Georgebc08c882016-12-06 12:20:10 +1100336 if (src != NULL) {
337 memcpy(&transaction.tx_data, src, len);
338 }
Eric Poulsen9123c8d2017-11-28 18:48:30 -0800339
340 transaction.flags = SPI_TRANS_USE_TXDATA | SPI_TRANS_USE_RXDATA;
341 transaction.length = bits_to_send;
342 spi_device_transmit(self->spi, &transaction);
343
344 if (dest != NULL) {
345 memcpy(dest, &transaction.rx_data, len);
346 }
Damien Georgebc08c882016-12-06 12:20:10 +1100347 } else {
Eric Poulsen9123c8d2017-11-28 18:48:30 -0800348 int offset = 0;
349 int bits_remaining = bits_to_send;
Jonathan Hogg8be29b92021-07-16 16:12:45 +0100350 int optimum_word_size = 8 * self->bits / gcd(8, self->bits);
351 int max_transaction_bits = MP_HW_SPI_MAX_XFER_BITS / optimum_word_size * optimum_word_size;
352 spi_transaction_t *transaction, *result, transactions[2];
353 int i = 0;
354
355 spi_device_acquire_bus(self->spi, portMAX_DELAY);
Damien Georgebc08c882016-12-06 12:20:10 +1100356
Eric Poulsen9123c8d2017-11-28 18:48:30 -0800357 while (bits_remaining) {
Jonathan Hogg8be29b92021-07-16 16:12:45 +0100358 transaction = transactions + i++ % 2;
359 memset(transaction, 0, sizeof(spi_transaction_t));
Damien Georgebc08c882016-12-06 12:20:10 +1100360
Jonathan Hogg8be29b92021-07-16 16:12:45 +0100361 transaction->length =
362 bits_remaining > max_transaction_bits ? max_transaction_bits : bits_remaining;
Eric Poulsen9123c8d2017-11-28 18:48:30 -0800363
364 if (src != NULL) {
Jonathan Hogg8be29b92021-07-16 16:12:45 +0100365 transaction->tx_buffer = src + offset;
Eric Poulsen9123c8d2017-11-28 18:48:30 -0800366 }
367 if (dest != NULL) {
Jonathan Hogg8be29b92021-07-16 16:12:45 +0100368 transaction->rx_buffer = dest + offset;
Eric Poulsen9123c8d2017-11-28 18:48:30 -0800369 }
370
Jonathan Hogg8be29b92021-07-16 16:12:45 +0100371 spi_device_queue_trans(self->spi, transaction, portMAX_DELAY);
372 bits_remaining -= transaction->length;
373
374 if (offset > 0) {
375 // wait for previously queued transaction
Jonathan Hogg5b655662021-08-15 17:13:16 +0100376 MP_THREAD_GIL_EXIT();
Jonathan Hogg8be29b92021-07-16 16:12:45 +0100377 spi_device_get_trans_result(self->spi, &result, portMAX_DELAY);
Jonathan Hogg5b655662021-08-15 17:13:16 +0100378 MP_THREAD_GIL_ENTER();
Jonathan Hogg8be29b92021-07-16 16:12:45 +0100379 }
Eric Poulsen9123c8d2017-11-28 18:48:30 -0800380
381 // doesn't need ceil(); loop ends when bits_remaining is 0
Jonathan Hogg8be29b92021-07-16 16:12:45 +0100382 offset += transaction->length / 8;
Eric Poulsen9123c8d2017-11-28 18:48:30 -0800383 }
Jonathan Hogg8be29b92021-07-16 16:12:45 +0100384
385 // wait for last transaction
Jonathan Hogg5b655662021-08-15 17:13:16 +0100386 MP_THREAD_GIL_EXIT();
Jonathan Hogg8be29b92021-07-16 16:12:45 +0100387 spi_device_get_trans_result(self->spi, &result, portMAX_DELAY);
Jonathan Hogg5b655662021-08-15 17:13:16 +0100388 MP_THREAD_GIL_ENTER();
Jonathan Hogg8be29b92021-07-16 16:12:45 +0100389 spi_device_release_bus(self->spi);
Damien Georgebc08c882016-12-06 12:20:10 +1100390 }
391}
392
393/******************************************************************************/
394// MicroPython bindings for hw_spi
395
Angus Grattondecf8e62024-02-27 15:32:29 +1100396static void machine_hw_spi_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
Damien Georgebc08c882016-12-06 12:20:10 +1100397 machine_hw_spi_obj_t *self = MP_OBJ_TO_PTR(self_in);
398 mp_printf(print, "SPI(id=%u, baudrate=%u, polarity=%u, phase=%u, bits=%u, firstbit=%u, sck=%d, mosi=%d, miso=%d)",
Damien George69661f32020-02-27 15:36:53 +1100399 self->host, self->baudrate, self->polarity,
400 self->phase, self->bits, self->firstbit,
401 self->sck, self->mosi, self->miso);
Damien Georgebc08c882016-12-06 12:20:10 +1100402}
403
Trent Piepho31e131b2024-02-10 12:07:46 -0800404// Take an arg list made from spi_allowed_args, and put in default or "keep same" values
405// into all the u_int fields.
406// The behavior is slightly different for a new call vs an init method on an existing object.
407// Unspecified arguments for new will use defaults, for init they keep the existing value.
Angus Grattondecf8e62024-02-27 15:32:29 +1100408static void machine_hw_spi_argcheck(mp_arg_val_t args[], const machine_hw_spi_default_pins_t *default_pins) {
Trent Piepho31e131b2024-02-10 12:07:46 -0800409// A non-NULL default_pins argument will trigger the "use default" behavior.
410 // Replace pin args with default/current values for new vs init call, respectively
411 for (int i = ARG_sck; i <= ARG_miso; i++) {
412 if (args[i].u_obj == MP_OBJ_NULL) {
413 args[i].u_int = default_pins ? default_pins->array[i - ARG_sck] : -2;
414 } else if (args[i].u_obj == mp_const_none) {
415 args[i].u_int = -1;
416 } else {
417 args[i].u_int = machine_pin_get_id(args[i].u_obj);
418 }
419 }
420}
421
Angus Grattondecf8e62024-02-27 15:32:29 +1100422static void machine_hw_spi_init(mp_obj_base_t *self_in, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
Damien George1a3e3862020-03-27 00:35:04 +1100423 machine_hw_spi_obj_t *self = (machine_hw_spi_obj_t *)self_in;
Damien Georgebc08c882016-12-06 12:20:10 +1100424
Trent Piepho31e131b2024-02-10 12:07:46 -0800425 mp_arg_val_t args[MP_ARRAY_SIZE(spi_allowed_args)];
426 // offset arg lists by 1 to skip first arg, id, which is not valid for init()
427 mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(spi_allowed_args) - 1,
428 spi_allowed_args + 1, args + 1);
Damien Georgebc08c882016-12-06 12:20:10 +1100429
Trent Piepho31e131b2024-02-10 12:07:46 -0800430 machine_hw_spi_argcheck(args, NULL);
431 machine_hw_spi_init_internal(self, args);
Damien Georgebc08c882016-12-06 12:20:10 +1100432}
433
434mp_obj_t machine_hw_spi_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) {
Damien George71f3ade2020-09-25 14:47:34 +1000435 MP_MACHINE_SPI_CHECK_FOR_LEGACY_SOFTSPI_CONSTRUCTION(n_args, n_kw, all_args);
436
Trent Piepho31e131b2024-02-10 12:07:46 -0800437 mp_arg_val_t args[MP_ARRAY_SIZE(spi_allowed_args)];
438 mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(spi_allowed_args), spi_allowed_args, args);
Damien Georgebc08c882016-12-06 12:20:10 +1100439
Trent Piepho31e131b2024-02-10 12:07:46 -0800440 const mp_int_t spi_id = args[ARG_id].u_int;
Damien Georgeb2adfc82023-07-25 11:33:51 +1000441 if (1 <= spi_id && spi_id <= MICROPY_HW_SPI_MAX) {
Trent Piepho31e131b2024-02-10 12:07:46 -0800442 machine_hw_spi_argcheck(args, &machine_hw_spi_default_pins[spi_id - 1]);
Damien Georgeda72bb62019-01-23 23:47:36 +1100443 } else {
Damien Georgeb2adfc82023-07-25 11:33:51 +1000444 mp_raise_msg_varg(&mp_type_ValueError, MP_ERROR_TEXT("SPI(%d) doesn't exist"), spi_id);
Damien Georgeda72bb62019-01-23 23:47:36 +1100445 }
Trent Piepho31e131b2024-02-10 12:07:46 -0800446 // Replace -1 non-pin args with default values
447 static const mp_int_t defaults[] = { 500000, 0, 0, 8, MICROPY_PY_MACHINE_SPI_MSB };
448 for (int i = ARG_baudrate; i <= ARG_firstbit; i++) {
449 if (args[i].u_int == -1) {
450 args[i].u_int = defaults[i - ARG_baudrate];
451 }
452 }
453
454 machine_hw_spi_obj_t *self = &machine_hw_spi_obj[spi_id - 1];
455 self->host = spi_id;
Damien Georgeb2adfc82023-07-25 11:33:51 +1000456
iabdalkader427670c2022-10-06 20:20:03 +0200457 self->base.type = &machine_spi_type;
Damien Georgebc08c882016-12-06 12:20:10 +1100458
Trent Piepho31e131b2024-02-10 12:07:46 -0800459 machine_hw_spi_init_internal(self, args);
Damien Georgebc08c882016-12-06 12:20:10 +1100460
461 return MP_OBJ_FROM_PTR(self);
462}
463
Damien Tournoude982c1d2023-01-12 21:04:07 -0800464spi_host_device_t machine_hw_spi_get_host(mp_obj_t in) {
465 if (mp_obj_get_type(in) != &machine_spi_type) {
466 mp_raise_ValueError(MP_ERROR_TEXT("expecting a SPI object"));
467 }
468 machine_hw_spi_obj_t *self = (machine_hw_spi_obj_t *)in;
469 return self->host;
470}
471
Angus Grattondecf8e62024-02-27 15:32:29 +1100472static const mp_machine_spi_p_t machine_hw_spi_p = {
Damien Georgebc08c882016-12-06 12:20:10 +1100473 .init = machine_hw_spi_init,
474 .deinit = machine_hw_spi_deinit,
475 .transfer = machine_hw_spi_transfer,
476};
477
Jim Mussared662b9762021-07-14 14:38:38 +1000478MP_DEFINE_CONST_OBJ_TYPE(
iabdalkader427670c2022-10-06 20:20:03 +0200479 machine_spi_type,
Jim Mussared662b9762021-07-14 14:38:38 +1000480 MP_QSTR_SPI,
481 MP_TYPE_FLAG_NONE,
Jim Mussared94beeab2022-09-17 00:31:23 +1000482 make_new, machine_hw_spi_make_new,
Jim Mussared662b9762021-07-14 14:38:38 +1000483 print, machine_hw_spi_print,
484 protocol, &machine_hw_spi_p,
Jim Mussared9dce8272022-06-24 16:27:46 +1000485 locals_dict, &mp_machine_spi_locals_dict
Jim Mussared662b9762021-07-14 14:38:38 +1000486 );