From d0401f02a947a468d3019e70b5b0f5f633429c5d Mon Sep 17 00:00:00 2001 From: Scott Shawcroft Date: Thu, 28 May 2020 15:51:33 -0700 Subject: [PATCH 01/22] Add initial I2C support, not quite working fully though --- ports/esp32s2/Makefile | 1 + ports/esp32s2/common-hal/busio/I2C.c | 239 +++++++++++ ports/esp32s2/common-hal/busio/I2C.h | 49 +++ ports/esp32s2/common-hal/busio/OneWire.h | 33 ++ ports/esp32s2/common-hal/busio/SPI.c | 249 +++++++++++ ports/esp32s2/common-hal/busio/SPI.h | 44 ++ ports/esp32s2/common-hal/busio/UART.c | 405 ++++++++++++++++++ ports/esp32s2/common-hal/busio/UART.h | 48 +++ ports/esp32s2/common-hal/busio/__init__.c | 1 + .../esp32s2/common-hal/microcontroller/Pin.c | 4 + .../esp32s2/common-hal/microcontroller/Pin.h | 1 + ports/esp32s2/mpconfigport.mk | 4 +- ports/esp32s2/supervisor/port.c | 10 +- 13 files changed, 1085 insertions(+), 3 deletions(-) create mode 100644 ports/esp32s2/common-hal/busio/I2C.c create mode 100644 ports/esp32s2/common-hal/busio/I2C.h create mode 100644 ports/esp32s2/common-hal/busio/OneWire.h create mode 100644 ports/esp32s2/common-hal/busio/SPI.c create mode 100644 ports/esp32s2/common-hal/busio/SPI.h create mode 100644 ports/esp32s2/common-hal/busio/UART.c create mode 100644 ports/esp32s2/common-hal/busio/UART.h create mode 100644 ports/esp32s2/common-hal/busio/__init__.c diff --git a/ports/esp32s2/Makefile b/ports/esp32s2/Makefile index 5ad5c2f1d3..4eac07f99f 100644 --- a/ports/esp32s2/Makefile +++ b/ports/esp32s2/Makefile @@ -78,6 +78,7 @@ INC += -Iesp-idf/components/freertos/xtensa/include INC += -Iesp-idf/components/esp32s2/include INC += -Iesp-idf/components/xtensa/esp32s2/include INC += -Iesp-idf/components/esp_common/include +INC += -Iesp-idf/components/esp_ringbuf/include INC += -Iesp-idf/components/esp_rom/include INC += -Iesp-idf/components/xtensa/include INC += -Iesp-idf/components/esp_timer/include diff --git a/ports/esp32s2/common-hal/busio/I2C.c b/ports/esp32s2/common-hal/busio/I2C.c new file mode 100644 index 0000000000..80743dc894 --- /dev/null +++ b/ports/esp32s2/common-hal/busio/I2C.c @@ -0,0 +1,239 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2016 Scott Shawcroft + * + * 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. + */ + +#include "shared-bindings/busio/I2C.h" +#include "py/mperrno.h" +#include "py/runtime.h" + +#include "driver/i2c.h" + +#include "esp_log.h" + +#include "shared-bindings/microcontroller/__init__.h" +#include "supervisor/shared/translate.h" + +// Number of times to try to send packet if failed. +#define ATTEMPTS 2 + +static const char* TAG = "CircuitPython I2C"; + +typedef enum { + STATUS_FREE = 0, + STATUS_IN_USE, + STATUS_NEVER_RESET +} i2c_status_t; + +static i2c_status_t i2c_status[I2C_NUM_MAX]; + +void never_reset_i2c(i2c_port_t num) { + i2c_status[num] = STATUS_NEVER_RESET; +} + +void i2c_reset(void) { + for (i2c_port_t num = 0; num < I2C_NUM_MAX; num++) { + if (i2c_status[num] == STATUS_IN_USE) { + i2c_driver_delete(num); + i2c_status[num] = STATUS_FREE; + } + } +} + +void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, + const mcu_pin_obj_t* scl, const mcu_pin_obj_t* sda, uint32_t frequency, uint32_t timeout) { + + // Make sure scl and sda aren't input only + +#if CIRCUITPY_REQUIRE_I2C_PULLUPS + // // Test that the pins are in a high state. (Hopefully indicating they are pulled up.) + // gpio_set_pin_function(sda->number, GPIO_PIN_FUNCTION_OFF); + // gpio_set_pin_function(scl->number, GPIO_PIN_FUNCTION_OFF); + // gpio_set_pin_direction(sda->number, GPIO_DIRECTION_IN); + // gpio_set_pin_direction(scl->number, GPIO_DIRECTION_IN); + + // gpio_set_pin_pull_mode(sda->number, GPIO_PULL_DOWN); + // gpio_set_pin_pull_mode(scl->number, GPIO_PULL_DOWN); + + // common_hal_mcu_delay_us(10); + + // gpio_set_pin_pull_mode(sda->number, GPIO_PULL_OFF); + // gpio_set_pin_pull_mode(scl->number, GPIO_PULL_OFF); + + // // We must pull up within 3us to achieve 400khz. + // common_hal_mcu_delay_us(3); + + // if (!gpio_get_pin_level(sda->number) || !gpio_get_pin_level(scl->number)) { + // reset_pin_number(sda->number); + // reset_pin_number(scl->number); + // mp_raise_RuntimeError(translate("SDA or SCL needs a pull up")); + // } +#endif + ESP_EARLY_LOGW(TAG, "create I2C"); + + + self->semaphore_handle = xSemaphoreCreateBinaryStatic(&self->semaphore); + xSemaphoreGive(self->semaphore_handle); + ESP_EARLY_LOGW(TAG, "new I2C lock %x", self->semaphore_handle); + self->sda_pin = sda; + self->scl_pin = scl; + ESP_EARLY_LOGW(TAG, "scl %d sda %d", self->sda_pin->number, self->scl_pin->number); + self->i2c_num = I2C_NUM_MAX; + for (i2c_port_t num = 0; num < I2C_NUM_MAX; num++) { + if (i2c_status[num] == STATUS_FREE) { + self->i2c_num = num; + } + } + if (self->i2c_num == I2C_NUM_MAX) { + mp_raise_ValueError(translate("All I2C peripherals are in use")); + } + i2c_status[self->i2c_num] = STATUS_IN_USE; + i2c_config_t i2c_conf = { + .mode = I2C_MODE_MASTER, + .sda_io_num = self->sda_pin->number, + .scl_io_num = self->scl_pin->number, + .sda_pullup_en = GPIO_PULLUP_DISABLE, /*!< Internal GPIO pull mode for I2C sda signal*/ + .scl_pullup_en = GPIO_PULLUP_DISABLE, /*!< Internal GPIO pull mode for I2C scl signal*/ + + .master = { + .clk_speed = frequency, + } + }; + // ESP_EARLY_LOGW(TAG, "param config %p %p %d %d", &i2c_conf, &(i2c_conf.mode), i2c_conf.mode, I2C_MODE_MAX); + ESP_EARLY_LOGW(TAG, "param config %p %d %d", &i2c_conf, i2c_conf.mode, I2C_MODE_MAX); + esp_err_t result = i2c_param_config(self->i2c_num, &i2c_conf); + if (result != ESP_OK) { + ESP_EARLY_LOGW(TAG, "error %d %p %d %d", result, &i2c_conf, (&i2c_conf)->mode, I2C_MODE_MAX); + vTaskDelay(0); + mp_raise_ValueError(translate("Invalid pins")); + } + ESP_EARLY_LOGW(TAG, "param config I2C done"); + result = i2c_driver_install(self->i2c_num, + I2C_MODE_MASTER, + 0, + 0, + 0); + if (result != ESP_OK) { + mp_raise_OSError(MP_EIO); + } + + claim_pin(sda); + claim_pin(scl); + ESP_EARLY_LOGW(TAG, "create I2C done"); +} + +bool common_hal_busio_i2c_deinited(busio_i2c_obj_t *self) { + return self->sda_pin == NULL; +} + +void common_hal_busio_i2c_deinit(busio_i2c_obj_t *self) { + if (common_hal_busio_i2c_deinited(self)) { + return; + } + + i2c_driver_delete(self->i2c_num); + i2c_status[self->i2c_num] = STATUS_FREE; + + reset_pin(self->sda_pin); + reset_pin(self->scl_pin); + self->sda_pin = NULL; + self->scl_pin = NULL; +} + +bool common_hal_busio_i2c_probe(busio_i2c_obj_t *self, uint8_t addr) { + i2c_cmd_handle_t cmd = i2c_cmd_link_create(); + i2c_master_start(cmd); + i2c_master_write_byte(cmd, addr << 1, true); + i2c_master_stop(cmd); + esp_err_t result = i2c_master_cmd_begin(self->i2c_num, cmd, 100); + i2c_cmd_link_delete(cmd); + return result == ESP_OK; +} + +bool common_hal_busio_i2c_try_lock(busio_i2c_obj_t *self) { + ESP_EARLY_LOGW(TAG, "locking I2C %x", self->semaphore_handle); + self->has_lock = xSemaphoreTake(self->semaphore_handle, 0) == pdTRUE; + if (self->has_lock) { + ESP_EARLY_LOGW(TAG, "lock grabbed"); + } else { + ESP_EARLY_LOGW(TAG, "unable to grab lock"); + } + return self->has_lock; +} + +bool common_hal_busio_i2c_has_lock(busio_i2c_obj_t *self) { + return self->has_lock; +} + +void common_hal_busio_i2c_unlock(busio_i2c_obj_t *self) { + ESP_EARLY_LOGW(TAG, "unlocking I2C"); + xSemaphoreGive(self->semaphore_handle); + self->has_lock = false; +} + +uint8_t common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t addr, + const uint8_t *data, size_t len, bool transmit_stop_bit) { + i2c_cmd_handle_t cmd = i2c_cmd_link_create(); + i2c_master_start(cmd); + i2c_master_write_byte(cmd, addr << 1, true); + i2c_master_write(cmd, (uint8_t*) data, len, true); + if (transmit_stop_bit) { + i2c_master_stop(cmd); + } + esp_err_t result = i2c_master_cmd_begin(self->i2c_num, cmd, 100 /* wait in ticks */); + i2c_cmd_link_delete(cmd); + + if (result == ESP_OK) { + return 0; + } else if (result == ESP_FAIL) { + return MP_ENODEV; + } + return MP_EIO; +} + +uint8_t common_hal_busio_i2c_read(busio_i2c_obj_t *self, uint16_t addr, + uint8_t *data, size_t len) { + + i2c_cmd_handle_t cmd = i2c_cmd_link_create(); + i2c_master_start(cmd); + i2c_master_write_byte(cmd, addr << 1 | 1, true); // | 1 to indicate read + i2c_master_read(cmd, data, len, true); + i2c_master_stop(cmd); + esp_err_t result = i2c_master_cmd_begin(self->i2c_num, cmd, 100 /* wait in ticks */); + i2c_cmd_link_delete(cmd); + + if (result == ESP_OK) { + return 0; + } else if (result == ESP_FAIL) { + return MP_ENODEV; + } + return MP_EIO; +} + +void common_hal_busio_i2c_never_reset(busio_i2c_obj_t *self) { + never_reset_i2c(self->i2c_num); + + never_reset_pin(self->scl_pin); + never_reset_pin(self->sda_pin); +} diff --git a/ports/esp32s2/common-hal/busio/I2C.h b/ports/esp32s2/common-hal/busio/I2C.h new file mode 100644 index 0000000000..d90fb2713a --- /dev/null +++ b/ports/esp32s2/common-hal/busio/I2C.h @@ -0,0 +1,49 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2016 Scott Shawcroft + * + * 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. + */ + +#ifndef MICROPY_INCLUDED_ESP32S2_COMMON_HAL_BUSIO_I2C_H +#define MICROPY_INCLUDED_ESP32S2_COMMON_HAL_BUSIO_I2C_H + +#include "common-hal/microcontroller/Pin.h" + +#include "esp-idf/components/soc/include/hal/i2c_types.h" +#include "FreeRTOS.h" +#include "freertos/semphr.h" +#include "py/obj.h" + +typedef struct { + mp_obj_base_t base; + const mcu_pin_obj_t* scl_pin; + const mcu_pin_obj_t* sda_pin; + i2c_port_t i2c_num; + StaticSemaphore_t semaphore; + SemaphoreHandle_t semaphore_handle; + bool has_lock; +} busio_i2c_obj_t; + +void i2c_reset(void); + +#endif // MICROPY_INCLUDED_ATMEL_SAMD_COMMON_HAL_BUSIO_I2C_H diff --git a/ports/esp32s2/common-hal/busio/OneWire.h b/ports/esp32s2/common-hal/busio/OneWire.h new file mode 100644 index 0000000000..bb6a014190 --- /dev/null +++ b/ports/esp32s2/common-hal/busio/OneWire.h @@ -0,0 +1,33 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2020 Scott Shawcroft + * + * 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. + */ + +#ifndef MICROPY_INCLUDED_ESP32S2_COMMON_HAL_BUSIO_ONEWIRE_H +#define MICROPY_INCLUDED_ESP32S2_COMMON_HAL_BUSIO_ONEWIRE_H + +// Use bitbangio. +#include "shared-module/busio/OneWire.h" + +#endif // MICROPY_INCLUDED_ESP32S2_COMMON_HAL_BUSIO_ONEWIRE_H diff --git a/ports/esp32s2/common-hal/busio/SPI.c b/ports/esp32s2/common-hal/busio/SPI.c new file mode 100644 index 0000000000..e761eb49be --- /dev/null +++ b/ports/esp32s2/common-hal/busio/SPI.c @@ -0,0 +1,249 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2016 Scott Shawcroft + * + * 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. + */ + +#include "shared-bindings/busio/SPI.h" +#include "py/mperrno.h" +#include "py/runtime.h" + +#include "boards/board.h" +#include "common-hal/microcontroller/Pin.h" +#include "supervisor/shared/rgb_led_status.h" + +void spi_reset(void) { + +} + +void common_hal_busio_spi_construct(busio_spi_obj_t *self, + const mcu_pin_obj_t * clock, const mcu_pin_obj_t * mosi, + const mcu_pin_obj_t * miso) { + // uint8_t sercom_index; + // uint32_t clock_pinmux = 0; + // bool mosi_none = mosi == NULL; + // bool miso_none = miso == NULL; + // uint32_t mosi_pinmux = 0; + // uint32_t miso_pinmux = 0; + // uint8_t clock_pad = 0; + // uint8_t mosi_pad = 0; + // uint8_t miso_pad = 0; + // uint8_t dopo = 255; + + // if (sercom == NULL) { + // mp_raise_ValueError(translate("Invalid pins")); + // } + + // // Set up SPI clocks on SERCOM. + // samd_peripherals_sercom_clock_init(sercom, sercom_index); + + #if defined(MICROPY_HW_APA102_SCK) && defined(MICROPY_HW_APA102_MOSI) && !CIRCUITPY_BITBANG_APA102 + // // if we're re-using the dotstar sercom, make sure it is disabled or the init will fail out + // hri_sercomspi_clear_CTRLA_ENABLE_bit(sercom); + #endif + // if (spi_m_sync_init(&self->spi_desc, sercom) != ERR_NONE) { + // mp_raise_OSError(MP_EIO); + // } + + // Pads must be set after spi_m_sync_init(), which uses default values from + // the prototypical SERCOM. + // hri_sercomspi_write_CTRLA_DOPO_bf(sercom, dopo); + // hri_sercomspi_write_CTRLA_DIPO_bf(sercom, miso_pad); + + // Always start at 250khz which is what SD cards need. They are sensitive to + // SPI bus noise before they are put into SPI mode. + // uint8_t baud_value = samd_peripherals_spi_baudrate_to_baud_reg_value(250000); + // if (spi_m_sync_set_baudrate(&self->spi_desc, baud_value) != ERR_NONE) { + // // spi_m_sync_set_baudrate does not check for validity, just whether the device is + // // busy or not + // mp_raise_OSError(MP_EIO); + // } + + // gpio_set_pin_direction(clock->number, GPIO_DIRECTION_OUT); + // gpio_set_pin_pull_mode(clock->number, GPIO_PULL_OFF); + // gpio_set_pin_function(clock->number, clock_pinmux); + // claim_pin(clock); + // self->clock_pin = clock->number; + + // if (mosi_none) { + // self->MOSI_pin = NO_PIN; + // } else { + // gpio_set_pin_direction(mosi->number, GPIO_DIRECTION_OUT); + // gpio_set_pin_pull_mode(mosi->number, GPIO_PULL_OFF); + // gpio_set_pin_function(mosi->number, mosi_pinmux); + // self->MOSI_pin = mosi->number; + // claim_pin(mosi); + // } + + // if (miso_none) { + // self->MISO_pin = NO_PIN; + // } else { + // gpio_set_pin_direction(miso->number, GPIO_DIRECTION_IN); + // gpio_set_pin_pull_mode(miso->number, GPIO_PULL_OFF); + // gpio_set_pin_function(miso->number, miso_pinmux); + // self->MISO_pin = miso->number; + // claim_pin(miso); + // } + + // spi_m_sync_enable(&self->spi_desc); +} + +void common_hal_busio_spi_never_reset(busio_spi_obj_t *self) { + // never_reset_sercom(self->spi_desc.dev.prvt); + + never_reset_pin(self->clock_pin); + never_reset_pin(self->MOSI_pin); + never_reset_pin(self->MISO_pin); +} + +bool common_hal_busio_spi_deinited(busio_spi_obj_t *self) { + return self->clock_pin == NULL; +} + +void common_hal_busio_spi_deinit(busio_spi_obj_t *self) { + if (common_hal_busio_spi_deinited(self)) { + return; + } + // allow_reset_sercom(self->spi_desc.dev.prvt); + + // spi_m_sync_disable(&self->spi_desc); + // spi_m_sync_deinit(&self->spi_desc); + reset_pin(self->clock_pin); + reset_pin(self->MOSI_pin); + reset_pin(self->MISO_pin); + self->clock_pin = NULL; +} + +bool common_hal_busio_spi_configure(busio_spi_obj_t *self, + uint32_t baudrate, uint8_t polarity, uint8_t phase, uint8_t bits) { + // If the settings are already what we want then don't reset them. + // if (hri_sercomspi_get_CTRLA_CPHA_bit(hw) == phase && + // hri_sercomspi_get_CTRLA_CPOL_bit(hw) == polarity && + // hri_sercomspi_read_CTRLB_CHSIZE_bf(hw) == ((uint32_t)bits - 8) && + // hri_sercomspi_read_BAUD_BAUD_bf(hw) == baud_reg_value) { + // return true; + // } + + // Disable, set values (most or all are enable-protected), and re-enable. + // spi_m_sync_disable(&self->spi_desc); + // hri_sercomspi_wait_for_sync(hw, SERCOM_SPI_SYNCBUSY_MASK); + + // hri_sercomspi_write_CTRLA_CPHA_bit(hw, phase); + // hri_sercomspi_write_CTRLA_CPOL_bit(hw, polarity); + // hri_sercomspi_write_CTRLB_CHSIZE_bf(hw, bits - 8); + // hri_sercomspi_write_BAUD_BAUD_bf(hw, baud_reg_value); + // hri_sercomspi_wait_for_sync(hw, SERCOM_SPI_SYNCBUSY_MASK); + + // spi_m_sync_enable(&self->spi_desc); + // hri_sercomspi_wait_for_sync(hw, SERCOM_SPI_SYNCBUSY_MASK); + + return true; +} + +bool common_hal_busio_spi_try_lock(busio_spi_obj_t *self) { + bool grabbed_lock = false; + // CRITICAL_SECTION_ENTER() + if (!self->has_lock) { + grabbed_lock = true; + self->has_lock = true; + } + // CRITICAL_SECTION_LEAVE(); + return grabbed_lock; +} + +bool common_hal_busio_spi_has_lock(busio_spi_obj_t *self) { + return self->has_lock; +} + +void common_hal_busio_spi_unlock(busio_spi_obj_t *self) { + self->has_lock = false; +} + +bool common_hal_busio_spi_write(busio_spi_obj_t *self, + const uint8_t *data, size_t len) { + if (len == 0) { + return true; + } + // int32_t status; + if (len >= 16) { + // status = sercom_dma_write(self->spi_desc.dev.prvt, data, len); + } else { + // struct io_descriptor *spi_io; + // spi_m_sync_get_io_descriptor(&self->spi_desc, &spi_io); + // status = spi_io->write(spi_io, data, len); + } + return false; // Status is number of chars read or an error code < 0. +} + +bool common_hal_busio_spi_read(busio_spi_obj_t *self, + uint8_t *data, size_t len, uint8_t write_value) { + if (len == 0) { + return true; + } + // int32_t status; + if (len >= 16) { + // status = sercom_dma_read(self->spi_desc.dev.prvt, data, len, write_value); + } else { + // self->spi_desc.dev.dummy_byte = write_value; + + // struct io_descriptor *spi_io; + // spi_m_sync_get_io_descriptor(&self->spi_desc, &spi_io); + + // status = spi_io->read(spi_io, data, len); + } + return false; // Status is number of chars read or an error code < 0. +} + +bool common_hal_busio_spi_transfer(busio_spi_obj_t *self, uint8_t *data_out, uint8_t *data_in, size_t len) { + if (len == 0) { + return true; + } + // int32_t status; + if (len >= 16) { + // status = sercom_dma_transfer(self->spi_desc.dev.prvt, data_out, data_in, len); + } else { + // struct spi_xfer xfer; + // xfer.txbuf = data_out; + // xfer.rxbuf = data_in; + // xfer.size = len; + // status = spi_m_sync_transfer(&self->spi_desc, &xfer); + } + return false; // Status is number of chars read or an error code < 0. +} + +uint32_t common_hal_busio_spi_get_frequency(busio_spi_obj_t* self) { + // return samd_peripherals_spi_baud_reg_value_to_baudrate(hri_sercomspi_read_BAUD_reg(self->spi_desc.dev.prvt)); + return 0; +} + +uint8_t common_hal_busio_spi_get_phase(busio_spi_obj_t* self) { + // void * hw = self->spi_desc.dev.prvt; + // return hri_sercomspi_get_CTRLA_CPHA_bit(hw); + return 0; +} + +uint8_t common_hal_busio_spi_get_polarity(busio_spi_obj_t* self) { + // void * hw = self->spi_desc.dev.prvt; + // return hri_sercomspi_get_CTRLA_CPOL_bit(hw); + return 0; +} diff --git a/ports/esp32s2/common-hal/busio/SPI.h b/ports/esp32s2/common-hal/busio/SPI.h new file mode 100644 index 0000000000..0ff1a4f7ea --- /dev/null +++ b/ports/esp32s2/common-hal/busio/SPI.h @@ -0,0 +1,44 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2016 Scott Shawcroft + * + * 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. + */ + +#ifndef MICROPY_INCLUDED_ESP32S2_COMMON_HAL_BUSIO_SPI_H +#define MICROPY_INCLUDED_ESP32S2_COMMON_HAL_BUSIO_SPI_H + +#include "common-hal/microcontroller/Pin.h" + +#include "py/obj.h" + +typedef struct { + mp_obj_base_t base; + bool has_lock; + const mcu_pin_obj_t* clock_pin; + const mcu_pin_obj_t* MOSI_pin; + const mcu_pin_obj_t* MISO_pin; +} busio_spi_obj_t; + +void spi_reset(void); + +#endif // MICROPY_INCLUDED_ESP32S2_COMMON_HAL_BUSIO_SPI_H diff --git a/ports/esp32s2/common-hal/busio/UART.c b/ports/esp32s2/common-hal/busio/UART.c new file mode 100644 index 0000000000..4a016ad1a8 --- /dev/null +++ b/ports/esp32s2/common-hal/busio/UART.c @@ -0,0 +1,405 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2016 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. + */ + +#include "shared-bindings/microcontroller/__init__.h" +#include "shared-bindings/busio/UART.h" + +#include "mpconfigport.h" +#include "lib/utils/interrupt_char.h" +#include "py/gc.h" +#include "py/mperrno.h" +#include "py/runtime.h" +#include "py/stream.h" +#include "supervisor/shared/translate.h" +#include "supervisor/shared/tick.h" + +#define UART_DEBUG(...) (void)0 +// #define UART_DEBUG(...) mp_printf(&mp_plat_print __VA_OPT__(,) __VA_ARGS__) + +// Do-nothing callback needed so that usart_async code will enable rx interrupts. +// See comment below re usart_async_register_callback() +// static void usart_async_rxc_callback(const struct usart_async_descriptor *const descr) { +// // Nothing needs to be done by us. +// } + +void uart_reset(void) { + +} + +void common_hal_busio_uart_construct(busio_uart_obj_t *self, + const mcu_pin_obj_t * tx, const mcu_pin_obj_t * rx, + const mcu_pin_obj_t * rts, const mcu_pin_obj_t * cts, + const mcu_pin_obj_t * rs485_dir, bool rs485_invert, + uint32_t baudrate, uint8_t bits, uart_parity_t parity, uint8_t stop, + mp_float_t timeout, uint16_t receiver_buffer_size, byte* receiver_buffer, + bool sigint_enabled) { + + // uint8_t sercom_index = 255; // Unset index + // uint32_t rx_pinmux = 0; + // uint8_t rx_pad = 255; // Unset pad + // uint32_t tx_pinmux = 0; + // uint8_t tx_pad = 255; // Unset pad + + // if ((rts != NULL) || (cts != NULL) || (rs485_dir != NULL) || (rs485_invert)) { + // mp_raise_ValueError(translate("RTS/CTS/RS485 Not yet supported on this device")); + // } + + // if (bits > 8) { + // mp_raise_NotImplementedError(translate("bytes > 8 bits not supported")); + // } + + bool have_tx = tx != NULL; + bool have_rx = rx != NULL; + if (!have_tx && !have_rx) { + mp_raise_ValueError(translate("tx and rx cannot both be None")); + } + + self->baudrate = baudrate; + self->character_bits = bits; + self->timeout_ms = timeout * 1000; + + // This assignment is only here because the usart_async routines take a *const argument. +// struct usart_async_descriptor * const usart_desc_p = (struct usart_async_descriptor * const) &self->usart_desc; + +// for (int i = 0; i < NUM_SERCOMS_PER_PIN; i++) { +// Sercom* potential_sercom = NULL; +// if (have_tx) { +// sercom_index = tx->sercom[i].index; +// if (sercom_index >= SERCOM_INST_NUM) { +// continue; +// } +// potential_sercom = sercom_insts[sercom_index]; +// #ifdef SAMD21 +// if (potential_sercom->USART.CTRLA.bit.ENABLE != 0 || +// !(tx->sercom[i].pad == 0 || +// tx->sercom[i].pad == 2)) { +// continue; +// } +// #endif +// #ifdef SAMD51 +// if (potential_sercom->USART.CTRLA.bit.ENABLE != 0 || +// !(tx->sercom[i].pad == 0)) { +// continue; +// } +// #endif +// tx_pinmux = PINMUX(tx->number, (i == 0) ? MUX_C : MUX_D); +// tx_pad = tx->sercom[i].pad; +// if (rx == NULL) { +// sercom = potential_sercom; +// break; +// } +// } +// for (int j = 0; j < NUM_SERCOMS_PER_PIN; j++) { +// if (((!have_tx && rx->sercom[j].index < SERCOM_INST_NUM && +// sercom_insts[rx->sercom[j].index]->USART.CTRLA.bit.ENABLE == 0) || +// sercom_index == rx->sercom[j].index) && +// rx->sercom[j].pad != tx_pad) { +// rx_pinmux = PINMUX(rx->number, (j == 0) ? MUX_C : MUX_D); +// rx_pad = rx->sercom[j].pad; +// sercom = sercom_insts[rx->sercom[j].index]; +// sercom_index = rx->sercom[j].index; +// break; +// } +// } +// if (sercom != NULL) { +// break; +// } +// } + // if (sercom == NULL) { + // mp_raise_ValueError(translate("Invalid pins")); + // } + // if (!have_tx) { + // tx_pad = 0; + // if (rx_pad == 0) { + // tx_pad = 2; + // } + // } + // if (!have_rx) { + // rx_pad = (tx_pad + 1) % 4; + // } + + // // Set up clocks on SERCOM. + // samd_peripherals_sercom_clock_init(sercom, sercom_index); + + // if (rx && receiver_buffer_size > 0) { + // self->buffer_length = receiver_buffer_size; + // // Initially allocate the UART's buffer in the long-lived part of the + // // heap. UARTs are generally long-lived objects, but the "make long- + // // lived" machinery is incapable of moving internal pointers like + // // self->buffer, so do it manually. (However, as long as internal + // // pointers like this are NOT moved, allocating the buffer + // // in the long-lived pool is not strictly necessary) + // self->buffer = (uint8_t *) gc_alloc(self->buffer_length * sizeof(uint8_t), false, true); + // if (self->buffer == NULL) { + // common_hal_busio_uart_deinit(self); + // mp_raise_msg_varg(&mp_type_MemoryError, translate("Failed to allocate RX buffer of %d bytes"), self->buffer_length * sizeof(uint8_t)); + // } + // } else { + // self->buffer_length = 0; + // self->buffer = NULL; + // } + + // if (usart_async_init(usart_desc_p, sercom, self->buffer, self->buffer_length, NULL) != ERR_NONE) { + // mp_raise_ValueError(translate("Could not initialize UART")); + // } + + // usart_async_init() sets a number of defaults based on a prototypical SERCOM + // which don't necessarily match what we need. After calling it, set the values + // specific to this instantiation of UART. + + // Set pads computed for this SERCOM. + // TXPO: + // 0x0: TX pad 0; no RTS/CTS + // 0x1: TX pad 2; no RTS/CTS + // 0x2: TX pad 0; RTS: pad 2, CTS: pad 3 (not used by us right now) + // So divide by 2 to map pad to value. + // RXPO: + // 0x0: RX pad 0 + // 0x1: RX pad 1 + // 0x2: RX pad 2 + // 0x3: RX pad 3 + + // Doing a group mask and set of the registers saves 60 bytes over setting the bitfields individually. + + // sercom->USART.CTRLA.reg &= ~(SERCOM_USART_CTRLA_TXPO_Msk | + // SERCOM_USART_CTRLA_RXPO_Msk | + // SERCOM_USART_CTRLA_FORM_Msk); + // sercom->USART.CTRLA.reg |= SERCOM_USART_CTRLA_TXPO(tx_pad / 2) | + // SERCOM_USART_CTRLA_RXPO(rx_pad) | + // (parity == PARITY_NONE ? 0 : SERCOM_USART_CTRLA_FORM(1)); + + // Enable tx and/or rx based on whether the pins were specified. + // CHSIZE is 0 for 8 bits, 5, 6, 7 for 5, 6, 7 bits. 1 for 9 bits, but we don't support that. + // sercom->USART.CTRLB.reg &= ~(SERCOM_USART_CTRLB_TXEN | + // SERCOM_USART_CTRLB_RXEN | + // SERCOM_USART_CTRLB_PMODE | + // SERCOM_USART_CTRLB_SBMODE | + // SERCOM_USART_CTRLB_CHSIZE_Msk); + // sercom->USART.CTRLB.reg |= (have_tx ? SERCOM_USART_CTRLB_TXEN : 0) | + // (have_rx ? SERCOM_USART_CTRLB_RXEN : 0) | + // (parity == PARITY_ODD ? SERCOM_USART_CTRLB_PMODE : 0) | + // (stop > 1 ? SERCOM_USART_CTRLB_SBMODE : 0) | + // SERCOM_USART_CTRLB_CHSIZE(bits % 8); + + // Set baud rate + // common_hal_busio_uart_set_baudrate(self, baudrate); + + // Turn on rx interrupt handling. The UART async driver has its own set of internal callbacks, + // which are set up by uart_async_init(). These in turn can call user-specified callbacks. + // In fact, the actual interrupts are not enabled unless we set up a user-specified callback. + // This is confusing. It's explained in the Atmel START User Guide -> Implementation Description -> + // Different read function behavior in some asynchronous drivers. As of this writing: + // http://start.atmel.com/static/help/index.html?GUID-79201A5A-226F-4FBB-B0B8-AB0BE0554836 + // Look at the ASFv4 code example for async USART. + // usart_async_register_callback(usart_desc_p, USART_ASYNC_RXC_CB, usart_async_rxc_callback); + + + // if (have_tx) { + // gpio_set_pin_direction(tx->number, GPIO_DIRECTION_OUT); + // gpio_set_pin_pull_mode(tx->number, GPIO_PULL_OFF); + // gpio_set_pin_function(tx->number, tx_pinmux); + // self->tx_pin = tx->number; + // claim_pin(tx); + // } else { + // self->tx_pin = NO_PIN; + // } + + // if (have_rx) { + // gpio_set_pin_direction(rx->number, GPIO_DIRECTION_IN); + // gpio_set_pin_pull_mode(rx->number, GPIO_PULL_OFF); + // gpio_set_pin_function(rx->number, rx_pinmux); + // self->rx_pin = rx->number; + // claim_pin(rx); + // } else { + // self->rx_pin = NO_PIN; + // } + + // usart_async_enable(usart_desc_p); +} + +bool common_hal_busio_uart_deinited(busio_uart_obj_t *self) { + return self->rx_pin == NULL && self->tx_pin == NULL; +} + +void common_hal_busio_uart_deinit(busio_uart_obj_t *self) { + if (common_hal_busio_uart_deinited(self)) { + return; + } + // // This assignment is only here because the usart_async routines take a *const argument. + // struct usart_async_descriptor * const usart_desc_p = (struct usart_async_descriptor * const) &self->usart_desc; + // usart_async_disable(usart_desc_p); + // usart_async_deinit(usart_desc_p); + reset_pin(self->rx_pin); + reset_pin(self->tx_pin); + self->rx_pin = NULL; + self->tx_pin = NULL; +} + +// Read characters. +size_t common_hal_busio_uart_read(busio_uart_obj_t *self, uint8_t *data, size_t len, int *errcode) { + if (self->rx_pin == NULL) { + mp_raise_ValueError(translate("No RX pin")); + } + + // This assignment is only here because the usart_async routines take a *const argument. + // struct usart_async_descriptor * const usart_desc_p = (struct usart_async_descriptor * const) &self->usart_desc; + + if (len == 0) { + // Nothing to read. + return 0; + } + + // struct io_descriptor *io; + // usart_async_get_io_descriptor(usart_desc_p, &io); + + // size_t total_read = 0; + // uint64_t start_ticks = supervisor_ticks_ms64(); + + // Busy-wait until timeout or until we've read enough chars. + // while (supervisor_ticks_ms64() - start_ticks <= self->timeout_ms) { + // // Read as many chars as we can right now, up to len. + // size_t num_read = io_read(io, data, len); + + // // Advance pointer in data buffer, and decrease how many chars left to read. + // data += num_read; + // len -= num_read; + // total_read += num_read; + // if (len == 0) { + // // Don't need to read any more: data buf is full. + // break; + // } + // if (num_read > 0) { + // // Reset the timeout on every character read. + // start_ticks = supervisor_ticks_ms64(); + // } + // RUN_BACKGROUND_TASKS; + // // Allow user to break out of a timeout with a KeyboardInterrupt. + // if (mp_hal_is_interrupted()) { + // break; + // } + // // If we are zero timeout, make sure we don't loop again (in the event + // // we read in under 1ms) + // if (self->timeout_ms == 0) { + // break; + // } + // } + + // if (total_read == 0) { + // *errcode = EAGAIN; + // return MP_STREAM_ERROR; + // } + + // return total_read; + return 0; +} + +// Write characters. +size_t common_hal_busio_uart_write(busio_uart_obj_t *self, const uint8_t *data, size_t len, int *errcode) { + if (self->tx_pin == NULL) { + mp_raise_ValueError(translate("No TX pin")); + } + + // This assignment is only here because the usart_async routines take a *const argument. + // struct usart_async_descriptor * const usart_desc_p = (struct usart_async_descriptor * const) &self->usart_desc; + + // struct io_descriptor *io; + // usart_async_get_io_descriptor(usart_desc_p, &io); + + // // Start writing characters. This is non-blocking and will + // // return immediately after setting up the write. + // if (io_write(io, data, len) < 0) { + // *errcode = MP_EAGAIN; + // return MP_STREAM_ERROR; + // } + + // // Busy-wait until all characters transmitted. + // struct usart_async_status async_status; + // while (true) { + // usart_async_get_status(usart_desc_p, &async_status); + // if (async_status.txcnt >= len) { + // break; + // } + // RUN_BACKGROUND_TASKS; + // } + + return len; +} + +uint32_t common_hal_busio_uart_get_baudrate(busio_uart_obj_t *self) { + return self->baudrate; +} + +void common_hal_busio_uart_set_baudrate(busio_uart_obj_t *self, uint32_t baudrate) { + // This assignment is only here because the usart_async routines take a *const argument. + // struct usart_async_descriptor * const usart_desc_p = (struct usart_async_descriptor * const) &self->usart_desc; + // usart_async_set_baud_rate(usart_desc_p, + // // Samples and ARITHMETIC vs FRACTIONAL must correspond to USART_SAMPR in + // // hpl_sercom_config.h. + // _usart_async_calculate_baud_rate(baudrate, // e.g. 9600 baud + // PROTOTYPE_SERCOM_USART_ASYNC_CLOCK_FREQUENCY, + // 16, // samples + // USART_BAUDRATE_ASYNCH_ARITHMETIC, + // 0 // fraction - not used for ARITHMETIC + // )); + self->baudrate = baudrate; +} + +mp_float_t common_hal_busio_uart_get_timeout(busio_uart_obj_t *self) { + return (mp_float_t) (self->timeout_ms / 1000.0f); +} + +void common_hal_busio_uart_set_timeout(busio_uart_obj_t *self, mp_float_t timeout) { + self->timeout_ms = timeout * 1000; +} + +uint32_t common_hal_busio_uart_rx_characters_available(busio_uart_obj_t *self) { + // This assignment is only here because the usart_async routines take a *const argument. + // struct usart_async_descriptor * const usart_desc_p = (struct usart_async_descriptor * const) &self->usart_desc; + // struct usart_async_status async_status; + // usart_async_get_status(usart_desc_p, &async_status); + // return async_status.rxcnt; + return 0; +} + +void common_hal_busio_uart_clear_rx_buffer(busio_uart_obj_t *self) { + // This assignment is only here because the usart_async routines take a *const argument. + // struct usart_async_descriptor * const usart_desc_p = (struct usart_async_descriptor * const) &self->usart_desc; + // usart_async_flush_rx_buffer(usart_desc_p); + +} + +// True if there are no characters still to be written. +bool common_hal_busio_uart_ready_to_tx(busio_uart_obj_t *self) { + if (self->tx_pin == NULL) { + return false; + } + // This assignment is only here because the usart_async routines take a *const argument. + // struct usart_async_descriptor * const usart_desc_p = (struct usart_async_descriptor * const) &self->usart_desc; + // struct usart_async_status async_status; + // usart_async_get_status(usart_desc_p, &async_status); + // return !(async_status.flags & USART_ASYNC_STATUS_BUSY); + return false; +} diff --git a/ports/esp32s2/common-hal/busio/UART.h b/ports/esp32s2/common-hal/busio/UART.h new file mode 100644 index 0000000000..3c2bd1dac5 --- /dev/null +++ b/ports/esp32s2/common-hal/busio/UART.h @@ -0,0 +1,48 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2016 Scott Shawcroft + * + * 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. + */ + +#ifndef MICROPY_INCLUDED_ESP32S2_COMMON_HAL_BUSIO_UART_H +#define MICROPY_INCLUDED_ESP32S2_COMMON_HAL_BUSIO_UART_H + +#include "common-hal/microcontroller/Pin.h" + +#include "py/obj.h" + +typedef struct { + mp_obj_base_t base; + const mcu_pin_obj_t* rx_pin; + const mcu_pin_obj_t* tx_pin; + uint8_t character_bits; + bool rx_error; + uint32_t baudrate; + uint32_t timeout_ms; + uint32_t buffer_length; + uint8_t* buffer; +} busio_uart_obj_t; + +void uart_reset(void); + +#endif // MICROPY_INCLUDED_ESP32S2_COMMON_HAL_BUSIO_UART_H diff --git a/ports/esp32s2/common-hal/busio/__init__.c b/ports/esp32s2/common-hal/busio/__init__.c new file mode 100644 index 0000000000..41761b6743 --- /dev/null +++ b/ports/esp32s2/common-hal/busio/__init__.c @@ -0,0 +1 @@ +// No busio module functions. diff --git a/ports/esp32s2/common-hal/microcontroller/Pin.c b/ports/esp32s2/common-hal/microcontroller/Pin.c index 4c39eea164..fd815518d5 100644 --- a/ports/esp32s2/common-hal/microcontroller/Pin.c +++ b/ports/esp32s2/common-hal/microcontroller/Pin.c @@ -49,6 +49,10 @@ void reset_pin_number(gpio_num_t pin_number) { in_use[pin_number / 32] &= ~(1 << pin_number % 32); } +void reset_pin(const mcu_pin_obj_t* pin) { + reset_pin_number(pin->number); +} + void reset_all_pins(void) { for (uint8_t i = 0; i < GPIO_PIN_COUNT; i++) { uint32_t iomux_address = GPIO_PIN_MUX_REG[i]; diff --git a/ports/esp32s2/common-hal/microcontroller/Pin.h b/ports/esp32s2/common-hal/microcontroller/Pin.h index 6f47b1ed31..573eec392b 100644 --- a/ports/esp32s2/common-hal/microcontroller/Pin.h +++ b/ports/esp32s2/common-hal/microcontroller/Pin.h @@ -35,6 +35,7 @@ void reset_all_pins(void); // reset_pin_number takes the pin number instead of the pointer so that objects don't // need to store a full pointer. void reset_pin_number(gpio_num_t pin_number); +void reset_pin(const mcu_pin_obj_t* pin); void claim_pin(const mcu_pin_obj_t* pin); bool pin_number_is_free(gpio_num_t pin_number); void never_reset_pin_number(gpio_num_t pin_number); diff --git a/ports/esp32s2/mpconfigport.mk b/ports/esp32s2/mpconfigport.mk index c9df81db03..9f59c1b467 100644 --- a/ports/esp32s2/mpconfigport.mk +++ b/ports/esp32s2/mpconfigport.mk @@ -16,10 +16,10 @@ CIRCUITPY_FULL_BUILD = 0 CIRCUITPY_ANALOGIO = 0 CIRCUITPY_AUDIOBUSIO = 0 CIRCUITPY_AUDIOIO = 0 -CIRCUITPY_BITBANGIO = 0 +CIRCUITPY_BITBANGIO = 1 CIRCUITPY_BOARD = 1 CIRCUITPY_DIGITALIO = 1 -CIRCUITPY_BUSIO = 0 +CIRCUITPY_BUSIO = 1 CIRCUITPY_DISPLAYIO = 0 CIRCUITPY_FREQUENCYIO = 0 CIRCUITPY_I2CSLAVE = 0 diff --git a/ports/esp32s2/supervisor/port.c b/ports/esp32s2/supervisor/port.c index 2437b4f341..fbfbc9f2eb 100644 --- a/ports/esp32s2/supervisor/port.c +++ b/ports/esp32s2/supervisor/port.c @@ -35,6 +35,9 @@ #include "freertos/task.h" #include "common-hal/microcontroller/Pin.h" +#include "common-hal/busio/I2C.h" +#include "common-hal/busio/SPI.h" +#include "common-hal/busio/UART.h" #include "supervisor/memory.h" #include "supervisor/shared/tick.h" @@ -64,8 +67,13 @@ safe_mode_t port_init(void) { } void reset_port(void) { - reset_all_pins(); + +#if CIRCUITPY_BUSIO + i2c_reset(); + spi_reset(); + uart_reset(); +#endif } void reset_to_bootloader(void) { From ae52d052cb6b4fb6cd89702dafe8448565b4aa5e Mon Sep 17 00:00:00 2001 From: Scott Shawcroft Date: Fri, 29 May 2020 16:32:31 -0700 Subject: [PATCH 02/22] Fix I2C thanks to Mark! --- ports/esp32s2/common-hal/busio/I2C.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/ports/esp32s2/common-hal/busio/I2C.c b/ports/esp32s2/common-hal/busio/I2C.c index 80743dc894..0a696bed61 100644 --- a/ports/esp32s2/common-hal/busio/I2C.c +++ b/ports/esp32s2/common-hal/busio/I2C.c @@ -218,7 +218,10 @@ uint8_t common_hal_busio_i2c_read(busio_i2c_obj_t *self, uint16_t addr, i2c_cmd_handle_t cmd = i2c_cmd_link_create(); i2c_master_start(cmd); i2c_master_write_byte(cmd, addr << 1 | 1, true); // | 1 to indicate read - i2c_master_read(cmd, data, len, true); + if (len > 1) { + i2c_master_read(cmd, data, len - 1, 0); + } + i2c_master_read_byte(cmd, data + len - 1, 1); i2c_master_stop(cmd); esp_err_t result = i2c_master_cmd_begin(self->i2c_num, cmd, 100 /* wait in ticks */); i2c_cmd_link_delete(cmd); From 6f050d7af368afb3eb45ac34533727794fa66c58 Mon Sep 17 00:00:00 2001 From: Scott Shawcroft Date: Wed, 3 Jun 2020 14:05:21 -0700 Subject: [PATCH 03/22] Add pull up testing, proper us delay and stop supporting 45 and 46 for I2C --- ports/esp32s2/common-hal/busio/I2C.c | 72 ++++++++++------------------ ports/esp32s2/mphalport.c | 3 +- 2 files changed, 28 insertions(+), 47 deletions(-) diff --git a/ports/esp32s2/common-hal/busio/I2C.c b/ports/esp32s2/common-hal/busio/I2C.c index 0a696bed61..fd983619ff 100644 --- a/ports/esp32s2/common-hal/busio/I2C.c +++ b/ports/esp32s2/common-hal/busio/I2C.c @@ -3,7 +3,7 @@ * * The MIT License (MIT) * - * Copyright (c) 2016 Scott Shawcroft + * Copyright (c) 2020 Scott Shawcroft for Adafruit Industries LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -30,16 +30,9 @@ #include "driver/i2c.h" -#include "esp_log.h" - #include "shared-bindings/microcontroller/__init__.h" #include "supervisor/shared/translate.h" -// Number of times to try to send packet if failed. -#define ATTEMPTS 2 - -static const char* TAG = "CircuitPython I2C"; - typedef enum { STATUS_FREE = 0, STATUS_IN_USE, @@ -63,42 +56,43 @@ void i2c_reset(void) { void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, const mcu_pin_obj_t* scl, const mcu_pin_obj_t* sda, uint32_t frequency, uint32_t timeout) { - - // Make sure scl and sda aren't input only + // Pins 45 and 46 are "strapping" pins that impact start up behavior. They usually need to + // be pulled-down so pulling them up for I2C is a bad idea. To make this hard, we don't + // support I2C on these pins. + // + // 46 is also input-only so it'll never work. + if (scl->number == 45 || scl->number == 46 || sda->number == 45 || sda->number == 46) { + mp_raise_ValueError(translate("Invalid pins")); + } #if CIRCUITPY_REQUIRE_I2C_PULLUPS - // // Test that the pins are in a high state. (Hopefully indicating they are pulled up.) - // gpio_set_pin_function(sda->number, GPIO_PIN_FUNCTION_OFF); - // gpio_set_pin_function(scl->number, GPIO_PIN_FUNCTION_OFF); - // gpio_set_pin_direction(sda->number, GPIO_DIRECTION_IN); - // gpio_set_pin_direction(scl->number, GPIO_DIRECTION_IN); + // Test that the pins are in a high state. (Hopefully indicating they are pulled up.) + gpio_set_direction(sda->number, GPIO_MODE_DEF_INPUT); + gpio_set_direction(scl->number, GPIO_MODE_DEF_INPUT); - // gpio_set_pin_pull_mode(sda->number, GPIO_PULL_DOWN); - // gpio_set_pin_pull_mode(scl->number, GPIO_PULL_DOWN); + gpio_pulldown_en(sda->number); + gpio_pulldown_en(scl->number); - // common_hal_mcu_delay_us(10); + common_hal_mcu_delay_us(10); - // gpio_set_pin_pull_mode(sda->number, GPIO_PULL_OFF); - // gpio_set_pin_pull_mode(scl->number, GPIO_PULL_OFF); + gpio_pulldown_dis(sda->number); + gpio_pulldown_dis(scl->number); - // // We must pull up within 3us to achieve 400khz. - // common_hal_mcu_delay_us(3); + // We must pull up within 3us to achieve 400khz. + common_hal_mcu_delay_us(3); - // if (!gpio_get_pin_level(sda->number) || !gpio_get_pin_level(scl->number)) { - // reset_pin_number(sda->number); - // reset_pin_number(scl->number); - // mp_raise_RuntimeError(translate("SDA or SCL needs a pull up")); - // } + if (gpio_get_level(sda->number) == 0 || gpio_get_level(scl->number) == 0) { + reset_pin_number(sda->number); + reset_pin_number(scl->number); + mp_raise_RuntimeError(translate("SDA or SCL needs a pull up")); + } #endif - ESP_EARLY_LOGW(TAG, "create I2C"); self->semaphore_handle = xSemaphoreCreateBinaryStatic(&self->semaphore); xSemaphoreGive(self->semaphore_handle); - ESP_EARLY_LOGW(TAG, "new I2C lock %x", self->semaphore_handle); self->sda_pin = sda; self->scl_pin = scl; - ESP_EARLY_LOGW(TAG, "scl %d sda %d", self->sda_pin->number, self->scl_pin->number); self->i2c_num = I2C_NUM_MAX; for (i2c_port_t num = 0; num < I2C_NUM_MAX; num++) { if (i2c_status[num] == STATUS_FREE) { @@ -120,15 +114,10 @@ void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, .clk_speed = frequency, } }; - // ESP_EARLY_LOGW(TAG, "param config %p %p %d %d", &i2c_conf, &(i2c_conf.mode), i2c_conf.mode, I2C_MODE_MAX); - ESP_EARLY_LOGW(TAG, "param config %p %d %d", &i2c_conf, i2c_conf.mode, I2C_MODE_MAX); esp_err_t result = i2c_param_config(self->i2c_num, &i2c_conf); if (result != ESP_OK) { - ESP_EARLY_LOGW(TAG, "error %d %p %d %d", result, &i2c_conf, (&i2c_conf)->mode, I2C_MODE_MAX); - vTaskDelay(0); mp_raise_ValueError(translate("Invalid pins")); } - ESP_EARLY_LOGW(TAG, "param config I2C done"); result = i2c_driver_install(self->i2c_num, I2C_MODE_MASTER, 0, @@ -140,7 +129,6 @@ void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, claim_pin(sda); claim_pin(scl); - ESP_EARLY_LOGW(TAG, "create I2C done"); } bool common_hal_busio_i2c_deinited(busio_i2c_obj_t *self) { @@ -166,19 +154,13 @@ bool common_hal_busio_i2c_probe(busio_i2c_obj_t *self, uint8_t addr) { i2c_master_start(cmd); i2c_master_write_byte(cmd, addr << 1, true); i2c_master_stop(cmd); - esp_err_t result = i2c_master_cmd_begin(self->i2c_num, cmd, 100); + esp_err_t result = i2c_master_cmd_begin(self->i2c_num, cmd, 10); i2c_cmd_link_delete(cmd); return result == ESP_OK; } bool common_hal_busio_i2c_try_lock(busio_i2c_obj_t *self) { - ESP_EARLY_LOGW(TAG, "locking I2C %x", self->semaphore_handle); self->has_lock = xSemaphoreTake(self->semaphore_handle, 0) == pdTRUE; - if (self->has_lock) { - ESP_EARLY_LOGW(TAG, "lock grabbed"); - } else { - ESP_EARLY_LOGW(TAG, "unable to grab lock"); - } return self->has_lock; } @@ -187,7 +169,6 @@ bool common_hal_busio_i2c_has_lock(busio_i2c_obj_t *self) { } void common_hal_busio_i2c_unlock(busio_i2c_obj_t *self) { - ESP_EARLY_LOGW(TAG, "unlocking I2C"); xSemaphoreGive(self->semaphore_handle); self->has_lock = false; } @@ -213,8 +194,7 @@ uint8_t common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t addr, } uint8_t common_hal_busio_i2c_read(busio_i2c_obj_t *self, uint16_t addr, - uint8_t *data, size_t len) { - + uint8_t *data, size_t len) { i2c_cmd_handle_t cmd = i2c_cmd_link_create(); i2c_master_start(cmd); i2c_master_write_byte(cmd, addr << 1 | 1, true); // | 1 to indicate read diff --git a/ports/esp32s2/mphalport.c b/ports/esp32s2/mphalport.c index da5258b0e2..e1662a6ce2 100644 --- a/ports/esp32s2/mphalport.c +++ b/ports/esp32s2/mphalport.c @@ -32,9 +32,10 @@ #include "py/gc.h" #include "esp-idf/components/xtensa/include/esp_debug_helpers.h" +#include "esp-idf/components/esp_rom/include/esp32s2/rom/ets_sys.h" void mp_hal_delay_us(mp_uint_t delay) { - mp_hal_delay_ms(delay / 1000); + ets_delay_us(delay); } // This is provided by the esp-idf/components/xtensa/esp32s2/libhal.a binary From a26102607e3fe5b6f888fcd246e20ac82a70af7b Mon Sep 17 00:00:00 2001 From: Scott Shawcroft Date: Tue, 9 Jun 2020 18:28:02 -0700 Subject: [PATCH 04/22] Add UART support --- Makefile | 9 + ports/atmel-samd/common-hal/busio/UART.c | 6 +- ports/cxd56/common-hal/busio/UART.c | 4 +- ports/esp32s2/common-hal/busio/UART.c | 480 ++++++++++------------- ports/esp32s2/common-hal/busio/UART.h | 7 +- ports/esp32s2/esp-idf | 2 +- ports/mimxrt10xx/common-hal/busio/UART.c | 4 +- ports/nrf/common-hal/busio/UART.c | 6 +- ports/stm/common-hal/busio/UART.c | 6 +- shared-bindings/busio/UART.c | 14 +- shared-bindings/busio/UART.h | 10 +- shared-module/board/__init__.c | 2 +- 12 files changed, 250 insertions(+), 300 deletions(-) diff --git a/Makefile b/Makefile index 55f64b17df..0df1950938 100644 --- a/Makefile +++ b/Makefile @@ -243,3 +243,12 @@ stubs: update-frozen-libraries: @echo "Updating all frozen libraries to latest tagged version." cd frozen; for library in *; do cd $$library; ../../tools/git-checkout-latest-tag.sh; cd ..; done + +one-of-each: all-source + make -C ports/atmel-samd BOARD=trinket_m0 + make -C ports/atmel-samd BOARD=feather_m4_express + make -C ports/esp32s2 BOARD=espressif_saola_1_wroom + make -C ports/litex BOARD=fomu + make -C ports/mimxrt10xx BOARD=feather_mimxrt1011 + make -C ports/nrf BOARD=feather_nrf52840_express + make -C ports/stm BOARD=feather_stm32f405_express diff --git a/ports/atmel-samd/common-hal/busio/UART.c b/ports/atmel-samd/common-hal/busio/UART.c index 9f740dc8af..9e213e061a 100644 --- a/ports/atmel-samd/common-hal/busio/UART.c +++ b/ports/atmel-samd/common-hal/busio/UART.c @@ -58,7 +58,7 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, const mcu_pin_obj_t * tx, const mcu_pin_obj_t * rx, const mcu_pin_obj_t * rts, const mcu_pin_obj_t * cts, const mcu_pin_obj_t * rs485_dir, bool rs485_invert, - uint32_t baudrate, uint8_t bits, uart_parity_t parity, uint8_t stop, + uint32_t baudrate, uint8_t bits, busio_uart_parity_t parity, uint8_t stop, mp_float_t timeout, uint16_t receiver_buffer_size, byte* receiver_buffer, bool sigint_enabled) { @@ -195,7 +195,7 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, SERCOM_USART_CTRLA_FORM_Msk); sercom->USART.CTRLA.reg |= SERCOM_USART_CTRLA_TXPO(tx_pad / 2) | SERCOM_USART_CTRLA_RXPO(rx_pad) | - (parity == PARITY_NONE ? 0 : SERCOM_USART_CTRLA_FORM(1)); + (parity == BUSIO_UART_PARITY_NONE ? 0 : SERCOM_USART_CTRLA_FORM(1)); // Enable tx and/or rx based on whether the pins were specified. // CHSIZE is 0 for 8 bits, 5, 6, 7 for 5, 6, 7 bits. 1 for 9 bits, but we don't support that. @@ -206,7 +206,7 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, SERCOM_USART_CTRLB_CHSIZE_Msk); sercom->USART.CTRLB.reg |= (have_tx ? SERCOM_USART_CTRLB_TXEN : 0) | (have_rx ? SERCOM_USART_CTRLB_RXEN : 0) | - (parity == PARITY_ODD ? SERCOM_USART_CTRLB_PMODE : 0) | + (parity == BUSIO_UART_PARITY_ODD ? SERCOM_USART_CTRLB_PMODE : 0) | (stop > 1 ? SERCOM_USART_CTRLB_SBMODE : 0) | SERCOM_USART_CTRLB_CHSIZE(bits % 8); diff --git a/ports/cxd56/common-hal/busio/UART.c b/ports/cxd56/common-hal/busio/UART.c index e455b0568d..52d2afc0c2 100644 --- a/ports/cxd56/common-hal/busio/UART.c +++ b/ports/cxd56/common-hal/busio/UART.c @@ -56,7 +56,7 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, const mcu_pin_obj_t * tx, const mcu_pin_obj_t * rx, const mcu_pin_obj_t * rts, const mcu_pin_obj_t * cts, const mcu_pin_obj_t * rs485_dir, bool rs485_invert, - uint32_t baudrate, uint8_t bits, uart_parity_t parity, uint8_t stop, + uint32_t baudrate, uint8_t bits, busio_uart_parity_t parity, uint8_t stop, mp_float_t timeout, uint16_t receiver_buffer_size, byte* receiver_buffer, bool sigint_enabled) { struct termios tio; @@ -69,7 +69,7 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, mp_raise_ValueError(translate("Could not initialize UART")); } - if (parity != PARITY_NONE) { + if (parity != BUSIO_UART_PARITY_NONE) { mp_raise_ValueError(translate("Could not initialize UART")); } diff --git a/ports/esp32s2/common-hal/busio/UART.c b/ports/esp32s2/common-hal/busio/UART.c index 4a016ad1a8..d52e50cade 100644 --- a/ports/esp32s2/common-hal/busio/UART.c +++ b/ports/esp32s2/common-hal/busio/UART.c @@ -3,7 +3,7 @@ * * The MIT License (MIT) * - * Copyright (c) 2016 Damien P. George + * Copyright (c) 2020 Scott Shawcroft for Adafruit Industries LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -27,6 +27,8 @@ #include "shared-bindings/microcontroller/__init__.h" #include "shared-bindings/busio/UART.h" +#include "driver/uart.h" + #include "mpconfigport.h" #include "lib/utils/interrupt_char.h" #include "py/gc.h" @@ -36,208 +38,178 @@ #include "supervisor/shared/translate.h" #include "supervisor/shared/tick.h" -#define UART_DEBUG(...) (void)0 -// #define UART_DEBUG(...) mp_printf(&mp_plat_print __VA_OPT__(,) __VA_ARGS__) - -// Do-nothing callback needed so that usart_async code will enable rx interrupts. -// See comment below re usart_async_register_callback() -// static void usart_async_rxc_callback(const struct usart_async_descriptor *const descr) { -// // Nothing needs to be done by us. -// } - void uart_reset(void) { - + for (uart_port_t num = 0; num < UART_NUM_MAX; num++) { + // Ignore the UART used by the IDF. + #ifdef CONFIG_CONSOLE_UART_NUM + if (num == CONFIG_CONSOLE_UART_NUM) { + continue; + } + #endif + if (uart_is_driver_installed(num)) { + uart_driver_delete(num); + } + } } void common_hal_busio_uart_construct(busio_uart_obj_t *self, const mcu_pin_obj_t * tx, const mcu_pin_obj_t * rx, const mcu_pin_obj_t * rts, const mcu_pin_obj_t * cts, const mcu_pin_obj_t * rs485_dir, bool rs485_invert, - uint32_t baudrate, uint8_t bits, uart_parity_t parity, uint8_t stop, + uint32_t baudrate, uint8_t bits, busio_uart_parity_t parity, uint8_t stop, mp_float_t timeout, uint16_t receiver_buffer_size, byte* receiver_buffer, bool sigint_enabled) { - // uint8_t sercom_index = 255; // Unset index - // uint32_t rx_pinmux = 0; - // uint8_t rx_pad = 255; // Unset pad - // uint32_t tx_pinmux = 0; - // uint8_t tx_pad = 255; // Unset pad - - // if ((rts != NULL) || (cts != NULL) || (rs485_dir != NULL) || (rs485_invert)) { - // mp_raise_ValueError(translate("RTS/CTS/RS485 Not yet supported on this device")); - // } - - // if (bits > 8) { - // mp_raise_NotImplementedError(translate("bytes > 8 bits not supported")); - // } + if (bits > 8) { + mp_raise_NotImplementedError(translate("bytes > 8 bits not supported")); + } bool have_tx = tx != NULL; bool have_rx = rx != NULL; + bool have_rts = rts != NULL; + bool have_cts = cts != NULL; + bool have_rs485_dir = rs485_dir != NULL; if (!have_tx && !have_rx) { mp_raise_ValueError(translate("tx and rx cannot both be None")); } - self->baudrate = baudrate; - self->character_bits = bits; + // Filter for sane settings for RS485 + if (have_rs485_dir) { + if (have_rts || have_cts) { + mp_raise_ValueError(translate("Cannot specify RTS or CTS in RS485 mode")); + } + } else if (rs485_invert) { + mp_raise_ValueError(translate("RS485 inversion specified when not in RS485 mode")); + } + self->timeout_ms = timeout * 1000; - // This assignment is only here because the usart_async routines take a *const argument. -// struct usart_async_descriptor * const usart_desc_p = (struct usart_async_descriptor * const) &self->usart_desc; + self->uart_num = UART_NUM_MAX; + for (uart_port_t num = 0; num < UART_NUM_MAX; num++) { + if (!uart_is_driver_installed(num)) { + self->uart_num = num; + } + } + if (self->uart_num == UART_NUM_MAX) { + mp_raise_ValueError(translate("All UART peripherals are in use")); + } -// for (int i = 0; i < NUM_SERCOMS_PER_PIN; i++) { -// Sercom* potential_sercom = NULL; -// if (have_tx) { -// sercom_index = tx->sercom[i].index; -// if (sercom_index >= SERCOM_INST_NUM) { -// continue; -// } -// potential_sercom = sercom_insts[sercom_index]; -// #ifdef SAMD21 -// if (potential_sercom->USART.CTRLA.bit.ENABLE != 0 || -// !(tx->sercom[i].pad == 0 || -// tx->sercom[i].pad == 2)) { -// continue; -// } -// #endif -// #ifdef SAMD51 -// if (potential_sercom->USART.CTRLA.bit.ENABLE != 0 || -// !(tx->sercom[i].pad == 0)) { -// continue; -// } -// #endif -// tx_pinmux = PINMUX(tx->number, (i == 0) ? MUX_C : MUX_D); -// tx_pad = tx->sercom[i].pad; -// if (rx == NULL) { -// sercom = potential_sercom; -// break; -// } -// } -// for (int j = 0; j < NUM_SERCOMS_PER_PIN; j++) { -// if (((!have_tx && rx->sercom[j].index < SERCOM_INST_NUM && -// sercom_insts[rx->sercom[j].index]->USART.CTRLA.bit.ENABLE == 0) || -// sercom_index == rx->sercom[j].index) && -// rx->sercom[j].pad != tx_pad) { -// rx_pinmux = PINMUX(rx->number, (j == 0) ? MUX_C : MUX_D); -// rx_pad = rx->sercom[j].pad; -// sercom = sercom_insts[rx->sercom[j].index]; -// sercom_index = rx->sercom[j].index; -// break; -// } -// } -// if (sercom != NULL) { -// break; -// } -// } - // if (sercom == NULL) { - // mp_raise_ValueError(translate("Invalid pins")); - // } - // if (!have_tx) { - // tx_pad = 0; - // if (rx_pad == 0) { - // tx_pad = 2; - // } - // } - // if (!have_rx) { - // rx_pad = (tx_pad + 1) % 4; - // } + uart_mode_t mode = UART_MODE_UART; + uart_hw_flowcontrol_t flow_control = UART_HW_FLOWCTRL_DISABLE; + if (have_rs485_dir) { + mode = UART_MODE_RS485_HALF_DUPLEX; + if (!rs485_invert) { + uart_set_line_inverse(self->uart_num, UART_SIGNAL_DTR_INV); + } + } else if (have_rts && have_cts) { + flow_control = UART_HW_FLOWCTRL_CTS_RTS; + } else if (have_rts) { + flow_control = UART_HW_FLOWCTRL_RTS; + } else if (have_rts) { + flow_control = UART_HW_FLOWCTRL_CTS; + } - // // Set up clocks on SERCOM. - // samd_peripherals_sercom_clock_init(sercom, sercom_index); + if (receiver_buffer_size <= UART_FIFO_LEN) { + receiver_buffer_size = UART_FIFO_LEN + 8; + } - // if (rx && receiver_buffer_size > 0) { - // self->buffer_length = receiver_buffer_size; - // // Initially allocate the UART's buffer in the long-lived part of the - // // heap. UARTs are generally long-lived objects, but the "make long- - // // lived" machinery is incapable of moving internal pointers like - // // self->buffer, so do it manually. (However, as long as internal - // // pointers like this are NOT moved, allocating the buffer - // // in the long-lived pool is not strictly necessary) - // self->buffer = (uint8_t *) gc_alloc(self->buffer_length * sizeof(uint8_t), false, true); - // if (self->buffer == NULL) { - // common_hal_busio_uart_deinit(self); - // mp_raise_msg_varg(&mp_type_MemoryError, translate("Failed to allocate RX buffer of %d bytes"), self->buffer_length * sizeof(uint8_t)); - // } - // } else { - // self->buffer_length = 0; - // self->buffer = NULL; - // } - - // if (usart_async_init(usart_desc_p, sercom, self->buffer, self->buffer_length, NULL) != ERR_NONE) { - // mp_raise_ValueError(translate("Could not initialize UART")); - // } - - // usart_async_init() sets a number of defaults based on a prototypical SERCOM - // which don't necessarily match what we need. After calling it, set the values - // specific to this instantiation of UART. - - // Set pads computed for this SERCOM. - // TXPO: - // 0x0: TX pad 0; no RTS/CTS - // 0x1: TX pad 2; no RTS/CTS - // 0x2: TX pad 0; RTS: pad 2, CTS: pad 3 (not used by us right now) - // So divide by 2 to map pad to value. - // RXPO: - // 0x0: RX pad 0 - // 0x1: RX pad 1 - // 0x2: RX pad 2 - // 0x3: RX pad 3 - - // Doing a group mask and set of the registers saves 60 bytes over setting the bitfields individually. - - // sercom->USART.CTRLA.reg &= ~(SERCOM_USART_CTRLA_TXPO_Msk | - // SERCOM_USART_CTRLA_RXPO_Msk | - // SERCOM_USART_CTRLA_FORM_Msk); - // sercom->USART.CTRLA.reg |= SERCOM_USART_CTRLA_TXPO(tx_pad / 2) | - // SERCOM_USART_CTRLA_RXPO(rx_pad) | - // (parity == PARITY_NONE ? 0 : SERCOM_USART_CTRLA_FORM(1)); - - // Enable tx and/or rx based on whether the pins were specified. - // CHSIZE is 0 for 8 bits, 5, 6, 7 for 5, 6, 7 bits. 1 for 9 bits, but we don't support that. - // sercom->USART.CTRLB.reg &= ~(SERCOM_USART_CTRLB_TXEN | - // SERCOM_USART_CTRLB_RXEN | - // SERCOM_USART_CTRLB_PMODE | - // SERCOM_USART_CTRLB_SBMODE | - // SERCOM_USART_CTRLB_CHSIZE_Msk); - // sercom->USART.CTRLB.reg |= (have_tx ? SERCOM_USART_CTRLB_TXEN : 0) | - // (have_rx ? SERCOM_USART_CTRLB_RXEN : 0) | - // (parity == PARITY_ODD ? SERCOM_USART_CTRLB_PMODE : 0) | - // (stop > 1 ? SERCOM_USART_CTRLB_SBMODE : 0) | - // SERCOM_USART_CTRLB_CHSIZE(bits % 8); + uint8_t rx_threshold = UART_FIFO_LEN - 8; + // Install the driver before we change the settings. + if (uart_driver_install(self->uart_num, receiver_buffer_size, 0, 0, NULL, 0) != ESP_OK || + uart_set_mode(self->uart_num, mode) != ESP_OK) { + mp_raise_ValueError(translate("Could not initialize UART")); + } + uart_set_hw_flow_ctrl(self->uart_num, flow_control, rx_threshold); // Set baud rate - // common_hal_busio_uart_set_baudrate(self, baudrate); + common_hal_busio_uart_set_baudrate(self, baudrate); - // Turn on rx interrupt handling. The UART async driver has its own set of internal callbacks, - // which are set up by uart_async_init(). These in turn can call user-specified callbacks. - // In fact, the actual interrupts are not enabled unless we set up a user-specified callback. - // This is confusing. It's explained in the Atmel START User Guide -> Implementation Description -> - // Different read function behavior in some asynchronous drivers. As of this writing: - // http://start.atmel.com/static/help/index.html?GUID-79201A5A-226F-4FBB-B0B8-AB0BE0554836 - // Look at the ASFv4 code example for async USART. - // usart_async_register_callback(usart_desc_p, USART_ASYNC_RXC_CB, usart_async_rxc_callback); + uart_word_length_t word_length = UART_DATA_8_BITS; + switch (bits) { + // Shared bindings prevents data < 7 bits. + // case 5: + // word_length = UART_DATA_5_BITS; + // break; + // case 6: + // word_length = UART_DATA_6_BITS; + // break; + case 7: + word_length = UART_DATA_7_BITS; + break; + case 8: + word_length = UART_DATA_8_BITS; + break; + default: + // Won't hit this because shared-bindings limits to 7-9 bits. We error on 9 above. + break; + } + uart_set_word_length(self->uart_num, word_length); + uart_parity_t parity_mode = UART_PARITY_DISABLE; + switch (parity) { + case BUSIO_UART_PARITY_NONE: + parity_mode = UART_PARITY_DISABLE; + break; + case BUSIO_UART_PARITY_EVEN: + parity_mode = UART_PARITY_EVEN; + break; + case BUSIO_UART_PARITY_ODD: + parity_mode = UART_PARITY_ODD; + break; + default: + // Won't reach here because the input is an enum that is completely handled. + break; + } + uart_set_parity(self->uart_num, parity_mode); - // if (have_tx) { - // gpio_set_pin_direction(tx->number, GPIO_DIRECTION_OUT); - // gpio_set_pin_pull_mode(tx->number, GPIO_PULL_OFF); - // gpio_set_pin_function(tx->number, tx_pinmux); - // self->tx_pin = tx->number; - // claim_pin(tx); - // } else { - // self->tx_pin = NO_PIN; - // } + // Stop is 1 or 2 always. + uart_stop_bits_t stop_bits= UART_STOP_BITS_1; + if (stop == 2) { + stop_bits = UART_STOP_BITS_2; + } + uart_set_stop_bits(self->uart_num, stop_bits); - // if (have_rx) { - // gpio_set_pin_direction(rx->number, GPIO_DIRECTION_IN); - // gpio_set_pin_pull_mode(rx->number, GPIO_PULL_OFF); - // gpio_set_pin_function(rx->number, rx_pinmux); - // self->rx_pin = rx->number; - // claim_pin(rx); - // } else { - // self->rx_pin = NO_PIN; - // } + self->tx_pin = NULL; + self->rx_pin = NULL; + self->rts_pin = NULL; + self->cts_pin = NULL; + int tx_num = -1; + int rx_num = -1; + int rts_num = -1; + int cts_num = -1; + if (have_tx) { + claim_pin(tx); + self->tx_pin = tx; + tx_num = tx->number; + } - // usart_async_enable(usart_desc_p); + if (have_rx) { + claim_pin(rx); + self->rx_pin = rx; + rx_num = rx->number; + } + + if (have_rts) { + claim_pin(rts); + self->rts_pin = rts; + rts_num = rts->number; + } + + if (have_cts) { + claim_pin(cts); + self->cts_pin = cts; + cts_num = cts->number; + } + + if (have_rs485_dir) { + claim_pin(rs485_dir); + // RTS is used for RS485 direction. + self->rts_pin = rs485_dir; + rts_num = rs485_dir->number; + } + if (uart_set_pin(self->uart_num, tx_num, rx_num, rts_num, cts_num) != ESP_OK) { + mp_raise_ValueError(translate("Invalid pins")); + } } bool common_hal_busio_uart_deinited(busio_uart_obj_t *self) { @@ -248,14 +220,16 @@ void common_hal_busio_uart_deinit(busio_uart_obj_t *self) { if (common_hal_busio_uart_deinited(self)) { return; } - // // This assignment is only here because the usart_async routines take a *const argument. - // struct usart_async_descriptor * const usart_desc_p = (struct usart_async_descriptor * const) &self->usart_desc; - // usart_async_disable(usart_desc_p); - // usart_async_deinit(usart_desc_p); + uart_driver_delete(self->uart_num); + reset_pin(self->rx_pin); reset_pin(self->tx_pin); + reset_pin(self->rts_pin); + reset_pin(self->cts_pin); self->rx_pin = NULL; self->tx_pin = NULL; + self->cts_pin = NULL; + self->rts_pin = NULL; } // Read characters. @@ -263,57 +237,49 @@ size_t common_hal_busio_uart_read(busio_uart_obj_t *self, uint8_t *data, size_t if (self->rx_pin == NULL) { mp_raise_ValueError(translate("No RX pin")); } - - // This assignment is only here because the usart_async routines take a *const argument. - // struct usart_async_descriptor * const usart_desc_p = (struct usart_async_descriptor * const) &self->usart_desc; - if (len == 0) { // Nothing to read. return 0; } - // struct io_descriptor *io; - // usart_async_get_io_descriptor(usart_desc_p, &io); - - // size_t total_read = 0; - // uint64_t start_ticks = supervisor_ticks_ms64(); + size_t total_read = 0; + uint64_t start_ticks = supervisor_ticks_ms64(); // Busy-wait until timeout or until we've read enough chars. - // while (supervisor_ticks_ms64() - start_ticks <= self->timeout_ms) { - // // Read as many chars as we can right now, up to len. - // size_t num_read = io_read(io, data, len); + while (supervisor_ticks_ms64() - start_ticks <= self->timeout_ms) { + // Read as many chars as we can right now, up to len. + size_t num_read = uart_read_bytes(self->uart_num, data, len, 0); - // // Advance pointer in data buffer, and decrease how many chars left to read. - // data += num_read; - // len -= num_read; - // total_read += num_read; - // if (len == 0) { - // // Don't need to read any more: data buf is full. - // break; - // } - // if (num_read > 0) { - // // Reset the timeout on every character read. - // start_ticks = supervisor_ticks_ms64(); - // } - // RUN_BACKGROUND_TASKS; - // // Allow user to break out of a timeout with a KeyboardInterrupt. - // if (mp_hal_is_interrupted()) { - // break; - // } - // // If we are zero timeout, make sure we don't loop again (in the event - // // we read in under 1ms) - // if (self->timeout_ms == 0) { - // break; - // } - // } + // Advance pointer in data buffer, and decrease how many chars left to read. + data += num_read; + len -= num_read; + total_read += num_read; + if (len == 0) { + // Don't need to read any more: data buf is full. + break; + } + if (num_read > 0) { + // Reset the timeout on every character read. + start_ticks = supervisor_ticks_ms64(); + } + RUN_BACKGROUND_TASKS; + // Allow user to break out of a timeout with a KeyboardInterrupt. + if (mp_hal_is_interrupted()) { + break; + } + // If we are zero timeout, make sure we don't loop again (in the event + // we read in under 1ms) + if (self->timeout_ms == 0) { + break; + } + } - // if (total_read == 0) { - // *errcode = EAGAIN; - // return MP_STREAM_ERROR; - // } + if (total_read == 0) { + *errcode = EAGAIN; + return MP_STREAM_ERROR; + } - // return total_read; - return 0; + return total_read; } // Write characters. @@ -322,49 +288,34 @@ size_t common_hal_busio_uart_write(busio_uart_obj_t *self, const uint8_t *data, mp_raise_ValueError(translate("No TX pin")); } - // This assignment is only here because the usart_async routines take a *const argument. - // struct usart_async_descriptor * const usart_desc_p = (struct usart_async_descriptor * const) &self->usart_desc; - - // struct io_descriptor *io; - // usart_async_get_io_descriptor(usart_desc_p, &io); - - // // Start writing characters. This is non-blocking and will - // // return immediately after setting up the write. - // if (io_write(io, data, len) < 0) { - // *errcode = MP_EAGAIN; - // return MP_STREAM_ERROR; - // } - - // // Busy-wait until all characters transmitted. - // struct usart_async_status async_status; - // while (true) { - // usart_async_get_status(usart_desc_p, &async_status); - // if (async_status.txcnt >= len) { - // break; - // } - // RUN_BACKGROUND_TASKS; - // } + while (len > 0) { + int count = uart_tx_chars(self->uart_num, (const char*) data, len); + if (count < 0) { + *errcode = MP_EAGAIN; + return MP_STREAM_ERROR; + } + len -= count; + data += count; + RUN_BACKGROUND_TASKS; + } + while (uart_wait_tx_done(self->uart_num, 0) == ESP_ERR_TIMEOUT) { + RUN_BACKGROUND_TASKS; + } return len; } uint32_t common_hal_busio_uart_get_baudrate(busio_uart_obj_t *self) { - return self->baudrate; + uint32_t baudrate; + uart_get_baudrate(self->uart_num, &baudrate); + return baudrate; } void common_hal_busio_uart_set_baudrate(busio_uart_obj_t *self, uint32_t baudrate) { - // This assignment is only here because the usart_async routines take a *const argument. - // struct usart_async_descriptor * const usart_desc_p = (struct usart_async_descriptor * const) &self->usart_desc; - // usart_async_set_baud_rate(usart_desc_p, - // // Samples and ARITHMETIC vs FRACTIONAL must correspond to USART_SAMPR in - // // hpl_sercom_config.h. - // _usart_async_calculate_baud_rate(baudrate, // e.g. 9600 baud - // PROTOTYPE_SERCOM_USART_ASYNC_CLOCK_FREQUENCY, - // 16, // samples - // USART_BAUDRATE_ASYNCH_ARITHMETIC, - // 0 // fraction - not used for ARITHMETIC - // )); - self->baudrate = baudrate; + if (baudrate > UART_BITRATE_MAX || + uart_set_baudrate(self->uart_num, baudrate) != ESP_OK) { + mp_raise_ValueError(translate("Unsupported baudrate")); + } } mp_float_t common_hal_busio_uart_get_timeout(busio_uart_obj_t *self) { @@ -376,19 +327,13 @@ void common_hal_busio_uart_set_timeout(busio_uart_obj_t *self, mp_float_t timeou } uint32_t common_hal_busio_uart_rx_characters_available(busio_uart_obj_t *self) { - // This assignment is only here because the usart_async routines take a *const argument. - // struct usart_async_descriptor * const usart_desc_p = (struct usart_async_descriptor * const) &self->usart_desc; - // struct usart_async_status async_status; - // usart_async_get_status(usart_desc_p, &async_status); - // return async_status.rxcnt; - return 0; + size_t count; + uart_get_buffered_data_len(self->uart_num, &count); + return count; } void common_hal_busio_uart_clear_rx_buffer(busio_uart_obj_t *self) { - // This assignment is only here because the usart_async routines take a *const argument. - // struct usart_async_descriptor * const usart_desc_p = (struct usart_async_descriptor * const) &self->usart_desc; - // usart_async_flush_rx_buffer(usart_desc_p); - + uart_flush(self->uart_num); } // True if there are no characters still to be written. @@ -396,10 +341,5 @@ bool common_hal_busio_uart_ready_to_tx(busio_uart_obj_t *self) { if (self->tx_pin == NULL) { return false; } - // This assignment is only here because the usart_async routines take a *const argument. - // struct usart_async_descriptor * const usart_desc_p = (struct usart_async_descriptor * const) &self->usart_desc; - // struct usart_async_status async_status; - // usart_async_get_status(usart_desc_p, &async_status); - // return !(async_status.flags & USART_ASYNC_STATUS_BUSY); - return false; + return uart_wait_tx_done(self->uart_num, 0) != ESP_ERR_TIMEOUT; } diff --git a/ports/esp32s2/common-hal/busio/UART.h b/ports/esp32s2/common-hal/busio/UART.h index 3c2bd1dac5..b3cc929665 100644 --- a/ports/esp32s2/common-hal/busio/UART.h +++ b/ports/esp32s2/common-hal/busio/UART.h @@ -29,18 +29,19 @@ #include "common-hal/microcontroller/Pin.h" +#include "esp-idf/components/soc/include/hal/uart_types.h" #include "py/obj.h" typedef struct { mp_obj_base_t base; const mcu_pin_obj_t* rx_pin; const mcu_pin_obj_t* tx_pin; + const mcu_pin_obj_t* rts_pin; + const mcu_pin_obj_t* cts_pin; + uart_port_t uart_num; uint8_t character_bits; bool rx_error; - uint32_t baudrate; uint32_t timeout_ms; - uint32_t buffer_length; - uint8_t* buffer; } busio_uart_obj_t; void uart_reset(void); diff --git a/ports/esp32s2/esp-idf b/ports/esp32s2/esp-idf index 7aae7f034b..648f959037 160000 --- a/ports/esp32s2/esp-idf +++ b/ports/esp32s2/esp-idf @@ -1 +1 @@ -Subproject commit 7aae7f034bab68d2dd6aaa763924c91eb697d87e +Subproject commit 648f959037896cff887a05b67105748790bfe63a diff --git a/ports/mimxrt10xx/common-hal/busio/UART.c b/ports/mimxrt10xx/common-hal/busio/UART.c index 5ef347e591..4ca2f8e497 100644 --- a/ports/mimxrt10xx/common-hal/busio/UART.c +++ b/ports/mimxrt10xx/common-hal/busio/UART.c @@ -85,7 +85,7 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, const mcu_pin_obj_t * tx, const mcu_pin_obj_t * rx, const mcu_pin_obj_t * rts, const mcu_pin_obj_t * cts, const mcu_pin_obj_t * rs485_dir, bool rs485_invert, - uint32_t baudrate, uint8_t bits, uart_parity_t parity, uint8_t stop, + uint32_t baudrate, uint8_t bits, busio_uart_parity_t parity, uint8_t stop, mp_float_t timeout, uint16_t receiver_buffer_size, byte* receiver_buffer, bool sigint_enabled) { @@ -94,7 +94,7 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, self->timeout_ms = timeout * 1000; // We are transmitting one direction if one pin is NULL and the other isn't. - bool is_onedirection = (rx != NULL) != (tx != NULL); + bool is_onedirection = (rx == NULL) != (tx == NULL); bool uart_taken = false; const uint32_t rx_count = MP_ARRAY_SIZE(mcu_uart_rx_list); diff --git a/ports/nrf/common-hal/busio/UART.c b/ports/nrf/common-hal/busio/UART.c index 89f3c9f327..012ebc3b5e 100644 --- a/ports/nrf/common-hal/busio/UART.c +++ b/ports/nrf/common-hal/busio/UART.c @@ -133,7 +133,7 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, const mcu_pin_obj_t * tx, const mcu_pin_obj_t * rx, const mcu_pin_obj_t * rts, const mcu_pin_obj_t * cts, const mcu_pin_obj_t * rs485_dir, bool rs485_invert, - uint32_t baudrate, uint8_t bits, uart_parity_t parity, uint8_t stop, + uint32_t baudrate, uint8_t bits, busio_uart_parity_t parity, uint8_t stop, mp_float_t timeout, uint16_t receiver_buffer_size, byte* receiver_buffer, bool sigint_enabled) { @@ -162,7 +162,7 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, mp_raise_ValueError(translate("Invalid buffer size")); } - if ( parity == PARITY_ODD ) { + if ( parity == BUSIO_UART_PARITY_ODD ) { mp_raise_ValueError(translate("Odd parity is not supported")); } @@ -176,7 +176,7 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, .interrupt_priority = 7, .hal_cfg = { .hwfc = NRF_UARTE_HWFC_DISABLED, - .parity = (parity == PARITY_NONE) ? NRF_UARTE_PARITY_EXCLUDED : NRF_UARTE_PARITY_INCLUDED + .parity = (parity == BUSIO_UART_PARITY_NONE) ? NRF_UARTE_PARITY_EXCLUDED : NRF_UARTE_PARITY_INCLUDED } }; diff --git a/ports/stm/common-hal/busio/UART.c b/ports/stm/common-hal/busio/UART.c index 86a932290a..7450f9897a 100644 --- a/ports/stm/common-hal/busio/UART.c +++ b/ports/stm/common-hal/busio/UART.c @@ -79,7 +79,7 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, const mcu_pin_obj_t * tx, const mcu_pin_obj_t * rx, const mcu_pin_obj_t * rts, const mcu_pin_obj_t * cts, const mcu_pin_obj_t * rs485_dir, bool rs485_invert, - uint32_t baudrate, uint8_t bits, uart_parity_t parity, uint8_t stop, + uint32_t baudrate, uint8_t bits, busio_uart_parity_t parity, uint8_t stop, mp_float_t timeout, uint16_t receiver_buffer_size, byte* receiver_buffer, bool sigint_enabled) { @@ -201,8 +201,8 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, self->handle.Init.BaudRate = baudrate; self->handle.Init.WordLength = (bits == 9) ? UART_WORDLENGTH_9B : UART_WORDLENGTH_8B; self->handle.Init.StopBits = (stop > 1) ? UART_STOPBITS_2 : UART_STOPBITS_1; - self->handle.Init.Parity = (parity == PARITY_ODD) ? UART_PARITY_ODD : - (parity == PARITY_EVEN) ? UART_PARITY_EVEN : + self->handle.Init.Parity = (parity == BUSIO_UART_PARITY_ODD) ? UART_PARITY_ODD : + (parity == BUSIO_UART_PARITY_EVEN) ? UART_PARITY_EVEN : UART_PARITY_NONE; self->handle.Init.Mode = (self->tx != NULL && self->rx != NULL) ? UART_MODE_TX_RX : (self->tx != NULL) ? UART_MODE_TX : diff --git a/shared-bindings/busio/UART.c b/shared-bindings/busio/UART.c index 8c0811266c..018ded1828 100644 --- a/shared-bindings/busio/UART.c +++ b/shared-bindings/busio/UART.c @@ -52,8 +52,8 @@ //| :param ~microcontroller.Pin rx: the pin to receive on, or ``None`` if this ``UART`` is transmit-only. //| :param ~microcontroller.Pin rts: the pin for rts, or ``None`` if rts not in use. //| :param ~microcontroller.Pin cts: the pin for cts, or ``None`` if cts not in use. -//| :param ~microcontroller.Pin rs485_dir: the pin for rs485 direction setting, or ``None`` if rs485 not in use. -//| :param bool rs485_invert: set to invert the sense of the rs485_dir pin. +//| :param ~microcontroller.Pin rs485_dir: the output pin for rs485 direction setting, or ``None`` if rs485 not in use. +//| :param bool rs485_invert: rs485_dir pin active high when set. Active low otherwise. //| :param int baudrate: the transmit and receive speed. //| :param int bits: the number of bits per byte, 7, 8 or 9. //| :param Parity parity: the parity used for error checking. @@ -87,8 +87,8 @@ STATIC mp_obj_t busio_uart_make_new(const mp_obj_type_t *type, size_t n_args, co enum { ARG_tx, ARG_rx, ARG_baudrate, ARG_bits, ARG_parity, ARG_stop, ARG_timeout, ARG_receiver_buffer_size, ARG_rts, ARG_cts, ARG_rs485_dir,ARG_rs485_invert}; static const mp_arg_t allowed_args[] = { - { MP_QSTR_tx, MP_ARG_REQUIRED | MP_ARG_OBJ }, - { MP_QSTR_rx, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_tx, MP_ARG_OBJ, {.u_obj = mp_const_none} }, + { MP_QSTR_rx, MP_ARG_OBJ, {.u_obj = mp_const_none} }, { MP_QSTR_baudrate, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 9600} }, { MP_QSTR_bits, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 8} }, { MP_QSTR_parity, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, @@ -115,11 +115,11 @@ STATIC mp_obj_t busio_uart_make_new(const mp_obj_type_t *type, size_t n_args, co mp_raise_ValueError(translate("bits must be 7, 8 or 9")); } - uart_parity_t parity = PARITY_NONE; + busio_uart_parity_t parity = BUSIO_UART_PARITY_NONE; if (args[ARG_parity].u_obj == &busio_uart_parity_even_obj) { - parity = PARITY_EVEN; + parity = BUSIO_UART_PARITY_EVEN; } else if (args[ARG_parity].u_obj == &busio_uart_parity_odd_obj) { - parity = PARITY_ODD; + parity = BUSIO_UART_PARITY_ODD; } uint8_t stop = args[ARG_stop].u_int; diff --git a/shared-bindings/busio/UART.h b/shared-bindings/busio/UART.h index 3aed4e534c..ce8da1445c 100644 --- a/shared-bindings/busio/UART.h +++ b/shared-bindings/busio/UART.h @@ -34,17 +34,17 @@ extern const mp_obj_type_t busio_uart_type; typedef enum { - PARITY_NONE, - PARITY_EVEN, - PARITY_ODD -} uart_parity_t; + BUSIO_UART_PARITY_NONE, + BUSIO_UART_PARITY_EVEN, + BUSIO_UART_PARITY_ODD +} busio_uart_parity_t; // Construct an underlying UART object. extern void common_hal_busio_uart_construct(busio_uart_obj_t *self, const mcu_pin_obj_t * tx, const mcu_pin_obj_t * rx, const mcu_pin_obj_t * rts, const mcu_pin_obj_t * cts, const mcu_pin_obj_t * rs485_dir, bool rs485_invert, - uint32_t baudrate, uint8_t bits, uart_parity_t parity, uint8_t stop, + uint32_t baudrate, uint8_t bits, busio_uart_parity_t parity, uint8_t stop, mp_float_t timeout, uint16_t receiver_buffer_size, byte* receiver_buffer, bool sigint_enabled); diff --git a/shared-module/board/__init__.c b/shared-module/board/__init__.c index 0fbf916cd9..2c9139d8af 100644 --- a/shared-module/board/__init__.c +++ b/shared-module/board/__init__.c @@ -123,7 +123,7 @@ mp_obj_t common_hal_board_create_uart(void) { #endif common_hal_busio_uart_construct(self, tx, rx, rts, cts, rs485_dir, rs485_invert, - 9600, 8, PARITY_NONE, 1, 1.0f, 64, NULL, false); + 9600, 8, BUSIO_UART_PARITY_NONE, 1, 1.0f, 64, NULL, false); MP_STATE_VM(shared_uart_bus) = MP_OBJ_FROM_PTR(self); return MP_STATE_VM(shared_uart_bus); } From 7b56617f8ef6cf9af9a5a8dbdadbc678918d52ca Mon Sep 17 00:00:00 2001 From: Scott Shawcroft Date: Wed, 10 Jun 2020 13:50:10 -0700 Subject: [PATCH 05/22] Turn off stub so flash works over native usb --- ports/esp32s2/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ports/esp32s2/Makefile b/ports/esp32s2/Makefile index 4eac07f99f..570eab0213 100644 --- a/ports/esp32s2/Makefile +++ b/ports/esp32s2/Makefile @@ -275,7 +275,7 @@ $(BUILD)/firmware.bin: $(BUILD)/esp-idf/partition_table/partition-table.bin $(BU $(Q)$(PYTHON) ../../tools/join_bins.py $@ 0x1000 $(BUILD)/esp-idf/bootloader/bootloader.bin 0x8000 $(BUILD)/esp-idf/partition_table/partition-table.bin 0x10000 $(BUILD)/circuitpython-firmware.bin flash: $(BUILD)/firmware.bin - esptool.py --chip esp32s2 -p $(PORT) -b 460800 --before=default_reset --after=hard_reset write_flash $(FLASH_FLAGS) 0x0000 $^ + esptool.py --chip esp32s2 -p $(PORT) --no-stub -b 460800 --before=default_reset --after=hard_reset write_flash $(FLASH_FLAGS) 0x0000 $^ include $(TOP)/py/mkrules.mk From f52f60b17d7fe5b7f139484e8b9988e3cf96eac1 Mon Sep 17 00:00:00 2001 From: Scott Shawcroft Date: Wed, 17 Jun 2020 10:57:52 -0700 Subject: [PATCH 06/22] Add UF2 build target --- ports/esp32s2/Makefile | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/ports/esp32s2/Makefile b/ports/esp32s2/Makefile index 570eab0213..29504065e9 100644 --- a/ports/esp32s2/Makefile +++ b/ports/esp32s2/Makefile @@ -258,7 +258,7 @@ ESP_AUTOGEN_LD = $(BUILD)/esp-idf/esp-idf/esp32s2/esp32s2_out.ld $(BUILD)/esp-id FLASH_FLAGS = --flash_mode $(CIRCUITPY_ESP_FLASH_MODE) --flash_freq $(CIRCUITPY_ESP_FLASH_FREQ) --flash_size $(CIRCUITPY_ESP_FLASH_SIZE) -all: $(BUILD)/firmware.bin +all: $(BUILD)/firmware.bin $(BUILD)/firmware.uf2 $(BUILD)/firmware.elf: $(OBJ) | $(ESP_IDF_COMPONENTS_EXPANDED) $(ESP_AUTOGEN_LD) $(STEPECHO) "LINK $@" @@ -274,6 +274,10 @@ $(BUILD)/circuitpython-firmware.bin: $(BUILD)/firmware.elf $(BUILD)/firmware.bin: $(BUILD)/esp-idf/partition_table/partition-table.bin $(BUILD)/esp-idf/bootloader/bootloader.bin $(BUILD)/circuitpython-firmware.bin $(Q)$(PYTHON) ../../tools/join_bins.py $@ 0x1000 $(BUILD)/esp-idf/bootloader/bootloader.bin 0x8000 $(BUILD)/esp-idf/partition_table/partition-table.bin 0x10000 $(BUILD)/circuitpython-firmware.bin +$(BUILD)/firmware.uf2: $(BUILD)/circuitpython-firmware.bin + $(STEPECHO) "Create $@" + $(Q)$(PYTHON3) $(TOP)/tools/uf2/utils/uf2conv.py -f 0xbfdd4eee -b 0x0000 -c -o $@ $^ + flash: $(BUILD)/firmware.bin esptool.py --chip esp32s2 -p $(PORT) --no-stub -b 460800 --before=default_reset --after=hard_reset write_flash $(FLASH_FLAGS) 0x0000 $^ From fc9c0ba5731a7eb1188366841a9a564074e7052f Mon Sep 17 00:00:00 2001 From: Scott Shawcroft Date: Wed, 17 Jun 2020 13:45:21 -0700 Subject: [PATCH 07/22] Initial SPI implementation. Almost certainly doesn't compile --- .../espressif_saola_1_wroom/mpconfigboard.mk | 2 - .../boards/unexpectedmaker_feathers2/board.c | 56 ++++ .../unexpectedmaker_feathers2/mpconfigboard.h | 36 +++ .../mpconfigboard.mk | 21 ++ .../boards/unexpectedmaker_feathers2/pins.c | 57 ++++ .../unexpectedmaker_feathers2/sdkconfig | 0 ports/esp32s2/common-hal/busio/I2C.c | 4 +- ports/esp32s2/common-hal/busio/SPI.c | 282 +++++++++++------- ports/esp32s2/common-hal/busio/SPI.h | 12 +- ports/esp32s2/common-hal/busio/UART.c | 8 +- .../esp32s2/common-hal/microcontroller/Pin.c | 5 +- .../esp32s2/common-hal/microcontroller/Pin.h | 5 +- 12 files changed, 366 insertions(+), 122 deletions(-) create mode 100644 ports/esp32s2/boards/unexpectedmaker_feathers2/board.c create mode 100644 ports/esp32s2/boards/unexpectedmaker_feathers2/mpconfigboard.h create mode 100644 ports/esp32s2/boards/unexpectedmaker_feathers2/mpconfigboard.mk create mode 100644 ports/esp32s2/boards/unexpectedmaker_feathers2/pins.c create mode 100644 ports/esp32s2/boards/unexpectedmaker_feathers2/sdkconfig diff --git a/ports/esp32s2/boards/espressif_saola_1_wroom/mpconfigboard.mk b/ports/esp32s2/boards/espressif_saola_1_wroom/mpconfigboard.mk index cd27356153..94e3b60f2d 100644 --- a/ports/esp32s2/boards/espressif_saola_1_wroom/mpconfigboard.mk +++ b/ports/esp32s2/boards/espressif_saola_1_wroom/mpconfigboard.mk @@ -12,8 +12,6 @@ LONGINT_IMPL = MPZ CFLAGS += -DCFG_TUD_TASK_QUEUE_SZ=32 CIRCUITPY_NEOPIXEL_WRITE = 0 -CIRCUITPY_DIGITALIO = 0 -CIRCUITPY_MICROCONTROLLER = 0 CIRCUITPY_ESP_FLASH_MODE=dio CIRCUITPY_ESP_FLASH_FREQ=40m diff --git a/ports/esp32s2/boards/unexpectedmaker_feathers2/board.c b/ports/esp32s2/boards/unexpectedmaker_feathers2/board.c new file mode 100644 index 0000000000..8890ec4c16 --- /dev/null +++ b/ports/esp32s2/boards/unexpectedmaker_feathers2/board.c @@ -0,0 +1,56 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2020 Scott Shawcroft for Adafruit Industries + * + * 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. + */ + +#include "boards/board.h" +#include "mpconfigboard.h" +#include "shared-bindings/microcontroller/Pin.h" + +void board_init(void) { + // USB + never_reset_pin(&pin_GPIO19); + never_reset_pin(&pin_GPIO20); + + // Debug UART + never_reset_pin(&pin_GPIO43); + never_reset_pin(&pin_GPIO44); + + // SPI Flash and RAM + never_reset_pin(&pin_GPIO26); + never_reset_pin(&pin_GPIO27); + never_reset_pin(&pin_GPIO28); + never_reset_pin(&pin_GPIO29); + never_reset_pin(&pin_GPIO30); + never_reset_pin(&pin_GPIO31); + never_reset_pin(&pin_GPIO32); +} + +bool board_requests_safe_mode(void) { + return false; +} + +void reset_board(void) { + +} diff --git a/ports/esp32s2/boards/unexpectedmaker_feathers2/mpconfigboard.h b/ports/esp32s2/boards/unexpectedmaker_feathers2/mpconfigboard.h new file mode 100644 index 0000000000..93fb0c573d --- /dev/null +++ b/ports/esp32s2/boards/unexpectedmaker_feathers2/mpconfigboard.h @@ -0,0 +1,36 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2019 Scott Shawcroft for Adafruit Industries + * + * 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. + */ + +//Micropython setup + +#define MICROPY_HW_BOARD_NAME "FeatherS2" +#define MICROPY_HW_MCU_NAME "ESP32S2" + +#define AUTORESET_DELAY_MS 500 + +// Doesn't work with this on. +// #define MICROPY_HW_APA102_MOSI (&pin_GPIO44) +// #define MICROPY_HW_APA102_SCK (&pin_GPIO45) diff --git a/ports/esp32s2/boards/unexpectedmaker_feathers2/mpconfigboard.mk b/ports/esp32s2/boards/unexpectedmaker_feathers2/mpconfigboard.mk new file mode 100644 index 0000000000..ea3484d2fa --- /dev/null +++ b/ports/esp32s2/boards/unexpectedmaker_feathers2/mpconfigboard.mk @@ -0,0 +1,21 @@ +USB_VID = 0x239A +USB_PID = 0x80AC +USB_PRODUCT = "FeatherS2" +USB_MANUFACTURER = "UnexpectedMaker" +USB_DEVICES = "CDC,MSC,HID" + + +INTERNAL_FLASH_FILESYSTEM = 1 +LONGINT_IMPL = MPZ + +# The default queue depth of 16 overflows on release builds, +# so increase it to 32. +CFLAGS += -DCFG_TUD_TASK_QUEUE_SZ=32 + +CIRCUITPY_NEOPIXEL_WRITE = 0 + +CIRCUITPY_ESP_FLASH_MODE=qio +CIRCUITPY_ESP_FLASH_FREQ=40m +CIRCUITPY_ESP_FLASH_SIZE=16MB + +CIRCUITPY_BITBANG_APA102 = 1 diff --git a/ports/esp32s2/boards/unexpectedmaker_feathers2/pins.c b/ports/esp32s2/boards/unexpectedmaker_feathers2/pins.c new file mode 100644 index 0000000000..e8dd2edf6a --- /dev/null +++ b/ports/esp32s2/boards/unexpectedmaker_feathers2/pins.c @@ -0,0 +1,57 @@ +#include "shared-bindings/board/__init__.h" + +STATIC const mp_rom_map_elem_t board_global_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_D14), MP_ROM_PTR(&pin_GPIO17) }, + + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_D15), MP_ROM_PTR(&pin_GPIO18) }, + + { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_D16), MP_ROM_PTR(&pin_GPIO14) }, + + { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_D17), MP_ROM_PTR(&pin_GPIO12) }, + + { MP_ROM_QSTR(MP_QSTR_A4), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_D18), MP_ROM_PTR(&pin_GPIO6) }, + + { MP_ROM_QSTR(MP_QSTR_A5), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_D19), MP_ROM_PTR(&pin_GPIO5) }, + + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_GPIO36) }, + { MP_ROM_QSTR(MP_QSTR_D25), MP_ROM_PTR(&pin_GPIO36) }, + + { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_GPIO35) }, + { MP_ROM_QSTR(MP_QSTR_D24), MP_ROM_PTR(&pin_GPIO35) }, + + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_GPIO37) }, + { MP_ROM_QSTR(MP_QSTR_D23), MP_ROM_PTR(&pin_GPIO37) }, + + { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_GPIO44) }, + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO44) }, + + { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_GPIO43) }, + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO43) }, + + // Moving to 9 and 8 + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO38) }, + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO33) }, + { MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_D6), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_D11), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_D12), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_D13), MP_ROM_PTR(&pin_GPIO11) }, + + { MP_ROM_QSTR(MP_QSTR_APA102_MOSI), MP_ROM_PTR(&pin_GPIO44) }, // MTDO + { MP_ROM_QSTR(MP_QSTR_APA102_SCK), MP_ROM_PTR(&pin_GPIO45) }, + + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_GPIO13) }, + + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, + { MP_ROM_QSTR(MP_QSTR_SPI), MP_ROM_PTR(&board_spi_obj) }, + { MP_ROM_QSTR(MP_QSTR_UART), MP_ROM_PTR(&board_uart_obj) }, +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_global_dict_table); diff --git a/ports/esp32s2/boards/unexpectedmaker_feathers2/sdkconfig b/ports/esp32s2/boards/unexpectedmaker_feathers2/sdkconfig new file mode 100644 index 0000000000..e69de29bb2 diff --git a/ports/esp32s2/common-hal/busio/I2C.c b/ports/esp32s2/common-hal/busio/I2C.c index fd983619ff..51817c95e2 100644 --- a/ports/esp32s2/common-hal/busio/I2C.c +++ b/ports/esp32s2/common-hal/busio/I2C.c @@ -143,8 +143,8 @@ void common_hal_busio_i2c_deinit(busio_i2c_obj_t *self) { i2c_driver_delete(self->i2c_num); i2c_status[self->i2c_num] = STATUS_FREE; - reset_pin(self->sda_pin); - reset_pin(self->scl_pin); + common_hal_reset_pin(self->sda_pin); + common_hal_reset_pin(self->scl_pin); self->sda_pin = NULL; self->scl_pin = NULL; } diff --git a/ports/esp32s2/common-hal/busio/SPI.c b/ports/esp32s2/common-hal/busio/SPI.c index e761eb49be..92a3dd4436 100644 --- a/ports/esp32s2/common-hal/busio/SPI.c +++ b/ports/esp32s2/common-hal/busio/SPI.c @@ -32,84 +32,141 @@ #include "common-hal/microcontroller/Pin.h" #include "supervisor/shared/rgb_led_status.h" -void spi_reset(void) { +static bool spi_never_reset[SOC_SPI_PERIPH_NUM]; +void spi_reset(void) { + for (spi_host_device_t host_id = SPI2_HOST; host_id < SOC_SPI_PERIPH_NUM; host_id++) { + if (spi_never_reset[host_id]) { + continue; + } + spi_bus_free(host_id); + } +} + +// This is copied in from the ESP-IDF because it is static. +// Copyright 2015-2019 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +static bool bus_uses_iomux_pins(spi_host_device_t host, const spi_bus_config_t* bus_config) +{ + if (bus_config->sclk_io_num>=0 && + bus_config->sclk_io_num != spi_periph_signal[host].spiclk_iomux_pin) return false; + if (bus_config->quadwp_io_num>=0 && + bus_config->quadwp_io_num != spi_periph_signal[host].spiwp_iomux_pin) return false; + if (bus_config->quadhd_io_num>=0 && + bus_config->quadhd_io_num != spi_periph_signal[host].spihd_iomux_pin) return false; + if (bus_config->mosi_io_num >= 0 && + bus_config->mosi_io_num != spi_periph_signal[host].spid_iomux_pin) return false; + if (bus_config->miso_io_num>=0 && + bus_config->miso_io_num != spi_periph_signal[host].spiq_iomux_pin) return false; + + return true; +} + +// End copied code. + +static bool spi_bus_free(spi_host_device_t host_id) { + return spi_bus_get_attr(host_id) == NULL; } void common_hal_busio_spi_construct(busio_spi_obj_t *self, const mcu_pin_obj_t * clock, const mcu_pin_obj_t * mosi, const mcu_pin_obj_t * miso) { - // uint8_t sercom_index; - // uint32_t clock_pinmux = 0; - // bool mosi_none = mosi == NULL; - // bool miso_none = miso == NULL; - // uint32_t mosi_pinmux = 0; - // uint32_t miso_pinmux = 0; - // uint8_t clock_pad = 0; - // uint8_t mosi_pad = 0; - // uint8_t miso_pad = 0; - // uint8_t dopo = 255; + spi_bus_config_t bus_config; + bus_config.mosi_io_num = mosi != NULL ? mosi->number : -1; + bus_config.miso_io_num = miso != NULL ? miso->number : -1; + bus_config.sclk_io_num = clock != NULL ? clock->number : -1; + bus_config.quadwp_io_num = -1; + bus_config.quadhd_io_num = -1; + bus_config.max_transfer_sz = 0; // Uses the default + bus_config.flags = SPICOMMON_BUSFLAG_MASTER | SPICOMMON_BUSFLAG_SCLK | + mosi != NULL ? SPICOMMON_BUSFLAG_MOSI : 0 | + miso != NULL ? SPICOMMON_BUSFLAG_MISO : 0; + bus_config.intr_flags = 0; - // if (sercom == NULL) { - // mp_raise_ValueError(translate("Invalid pins")); - // } + // RAM and Flash is often on SPI1 and is unsupported by the IDF so use it as + // a flag value. + spi_host_device_t host_id = SPI1_HOST; + self->connected_through_gpio = true; + // Try and save SPI2 for pins that are on the IOMUX + if (bus_uses_iomux_pins(SPI2_HOST, &bus_config) && spi_bus_free(SPI2_HOST)) { + host_id = SPI2_HOST; + self->connected_through_gpio = false; + } else if (spi_bus_free(SPI3_HOST)) { + host_id = SPI3_HOST; + } else if (spi_bus_free(SPI2_HOST)) { + host_id = SPI2_HOST; + } + if (host_id == SPI1_HOST) { + mp_raise_ValueError(translate("All SPI peripherals are in use")); + } - // // Set up SPI clocks on SERCOM. - // samd_peripherals_sercom_clock_init(sercom, sercom_index); + esp_err_t result = spi_bus_initialize(host_id, &bus_config, 0 /* dma channel */); + if (result == ESP_ERR_NO_MEM) { + mp_raise_msg(&mp_type_MemoryError, translate("ESP-IDF memory allocation failed")); + } else if (result = ESP_INVALID_ARG) { + mp_raise_ValueError(translate("Invalid pins")); + } + spi_bus_lock_dev_config_t config = { .flags = 0 }; + result = spi_bus_lock_register_dev(spi_bus_get_attr(host_id)->lock, + spi_bus_lock_dev_config_t *config, + &self->lock); + if (result == ESP_ERR_NO_MEM) { + mp_raise_msg(&mp_type_MemoryError, translate("ESP-IDF memory allocation failed")); + } - #if defined(MICROPY_HW_APA102_SCK) && defined(MICROPY_HW_APA102_MOSI) && !CIRCUITPY_BITBANG_APA102 - // // if we're re-using the dotstar sercom, make sure it is disabled or the init will fail out - // hri_sercomspi_clear_CTRLA_ENABLE_bit(sercom); - #endif - // if (spi_m_sync_init(&self->spi_desc, sercom) != ERR_NONE) { - // mp_raise_OSError(MP_EIO); - // } - // Pads must be set after spi_m_sync_init(), which uses default values from - // the prototypical SERCOM. - // hri_sercomspi_write_CTRLA_DOPO_bf(sercom, dopo); - // hri_sercomspi_write_CTRLA_DIPO_bf(sercom, miso_pad); + err = esp_intr_alloc(spicommon_irqsource_for_host(host_id), + bus_config.intr_flags | ESP_INTR_FLAG_INTRDISABLED, + spi_interrupt_handler, self, &self->intr); + if (result == ESP_ERR_NO_MEM) { + mp_raise_msg(&mp_type_MemoryError, translate("ESP-IDF memory allocation failed")); + } - // Always start at 250khz which is what SD cards need. They are sensitive to - // SPI bus noise before they are put into SPI mode. - // uint8_t baud_value = samd_peripherals_spi_baudrate_to_baud_reg_value(250000); - // if (spi_m_sync_set_baudrate(&self->spi_desc, baud_value) != ERR_NONE) { - // // spi_m_sync_set_baudrate does not check for validity, just whether the device is - // // busy or not - // mp_raise_OSError(MP_EIO); - // } + spi_hal_context_t* hal = &self->hal_context; + hal->hw = NULL; // Set by spi_hal_init + hal->dmadesc_tx = NULL; + hal->dmadesc_rx = NULL; + hal->dmadesc_n = 0; - // gpio_set_pin_direction(clock->number, GPIO_DIRECTION_OUT); - // gpio_set_pin_pull_mode(clock->number, GPIO_PULL_OFF); - // gpio_set_pin_function(clock->number, clock_pinmux); - // claim_pin(clock); - // self->clock_pin = clock->number; + // We don't use native CS. + hal->cs_setup = 0; + hal->cs_hold = 0; + hal->cs_pin_id = -1; + hal->timing_conf = &self->timing_conf; - // if (mosi_none) { - // self->MOSI_pin = NO_PIN; - // } else { - // gpio_set_pin_direction(mosi->number, GPIO_DIRECTION_OUT); - // gpio_set_pin_pull_mode(mosi->number, GPIO_PULL_OFF); - // gpio_set_pin_function(mosi->number, mosi_pinmux); - // self->MOSI_pin = mosi->number; - // claim_pin(mosi); - // } + hal->sio = 1; + hal->half_duplex = 0; + hal->tx_lsbfirst = 0; + hal->rx_lsbfirst = 0; + hal->dma_enabled = 0; + hal->no_compensate = 1; + // Ignore CS bits - // if (miso_none) { - // self->MISO_pin = NO_PIN; - // } else { - // gpio_set_pin_direction(miso->number, GPIO_DIRECTION_IN); - // gpio_set_pin_pull_mode(miso->number, GPIO_PULL_OFF); - // gpio_set_pin_function(miso->number, miso_pinmux); - // self->MISO_pin = miso->number; - // claim_pin(miso); - // } + // We don't use cmd, addr or dummy bits. + hal->cmd = 0; + hal->cmd_bits = 0; + hal->addr_bits = 0; + hal->dummy_bits = 0; + hal->addr = 0; - // spi_m_sync_enable(&self->spi_desc); + hal->io_mode = SPI_LL_IO_MODE_NORMAL; + + spi_hal_init(hal, host_id); } void common_hal_busio_spi_never_reset(busio_spi_obj_t *self) { - // never_reset_sercom(self->spi_desc.dev.prvt); + spi_never_reset[self->host_id] = true; never_reset_pin(self->clock_pin); never_reset_pin(self->MOSI_pin); @@ -124,51 +181,50 @@ void common_hal_busio_spi_deinit(busio_spi_obj_t *self) { if (common_hal_busio_spi_deinited(self)) { return; } - // allow_reset_sercom(self->spi_desc.dev.prvt); + spi_never_reset[self->host_id] = false; + spi_bus_free(self->host_id); - // spi_m_sync_disable(&self->spi_desc); - // spi_m_sync_deinit(&self->spi_desc); - reset_pin(self->clock_pin); - reset_pin(self->MOSI_pin); - reset_pin(self->MISO_pin); + common_hal_reset_pin(self->clock_pin); + common_hal_reset_pin(self->MOSI_pin); + common_hal_reset_pin(self->MISO_pin); self->clock_pin = NULL; } bool common_hal_busio_spi_configure(busio_spi_obj_t *self, uint32_t baudrate, uint8_t polarity, uint8_t phase, uint8_t bits) { - // If the settings are already what we want then don't reset them. - // if (hri_sercomspi_get_CTRLA_CPHA_bit(hw) == phase && - // hri_sercomspi_get_CTRLA_CPOL_bit(hw) == polarity && - // hri_sercomspi_read_CTRLB_CHSIZE_bf(hw) == ((uint32_t)bits - 8) && - // hri_sercomspi_read_BAUD_BAUD_bf(hw) == baud_reg_value) { - // return true; - // } - - // Disable, set values (most or all are enable-protected), and re-enable. - // spi_m_sync_disable(&self->spi_desc); - // hri_sercomspi_wait_for_sync(hw, SERCOM_SPI_SYNCBUSY_MASK); - - // hri_sercomspi_write_CTRLA_CPHA_bit(hw, phase); - // hri_sercomspi_write_CTRLA_CPOL_bit(hw, polarity); - // hri_sercomspi_write_CTRLB_CHSIZE_bf(hw, bits - 8); - // hri_sercomspi_write_BAUD_BAUD_bf(hw, baud_reg_value); - // hri_sercomspi_wait_for_sync(hw, SERCOM_SPI_SYNCBUSY_MASK); - - // spi_m_sync_enable(&self->spi_desc); - // hri_sercomspi_wait_for_sync(hw, SERCOM_SPI_SYNCBUSY_MASK); + if (baudrate == self->target_frequency && + polarity == self->polarity && + phase == self->phase && + bits == self->bits) { + return true; + } + self->hal_context->mode = polarity << 1 | phase; + self->polarity = polarity; + self->phase = phase; + self->bits = bits; + self->target_frequency = baudrate; + esp_err_t result = spi_hal_get_clock_conf(self->hal_context, + self->target_frequency, + 128 /* duty_cycle */, + self->connected_through_gpio, + 0 /* input_delay_ns */, + &self->real_frequency, + &self->timing_conf); + spi_hal_setup_device(&self->hal_context); return true; } bool common_hal_busio_spi_try_lock(busio_spi_obj_t *self) { - bool grabbed_lock = false; - // CRITICAL_SECTION_ENTER() - if (!self->has_lock) { - grabbed_lock = true; - self->has_lock = true; - } - // CRITICAL_SECTION_LEAVE(); - return grabbed_lock; + // If our lock has already been taken then return false because someone else + // may already grabbed it in our call stack. + if (self->has_lock) { + return false; + } + // Wait to grab the lock from another task. + esp_err_t ret = spi_bus_lock_acquire_start(self->lock, portMAX_DELAY); + self->has_lock = true; + return true; } bool common_hal_busio_spi_has_lock(busio_spi_obj_t *self) { @@ -176,6 +232,7 @@ bool common_hal_busio_spi_has_lock(busio_spi_obj_t *self) { } void common_hal_busio_spi_unlock(busio_spi_obj_t *self) { + spi_bus_lock_acquire_end(self->lock); self->has_lock = false; } @@ -218,32 +275,35 @@ bool common_hal_busio_spi_transfer(busio_spi_obj_t *self, uint8_t *data_out, uin if (len == 0) { return true; } - // int32_t status; - if (len >= 16) { - // status = sercom_dma_transfer(self->spi_desc.dev.prvt, data_out, data_in, len); + + spi_hal_context_t* hal = &self->hal_context; + hal->tx_bitlen = len * 8; + hal->rx_bitlen = len * 8; + hal->send_buffer = data_out; + hal->rcv_buffer = data_in; + + spi_hal_setup_trans(hal); + spi_hal_prepare_data(hal); + spi_hal_user_start(hal); + if (len >= 16 && false) { + // Set up the interrupt and wait on the lock. } else { - // struct spi_xfer xfer; - // xfer.txbuf = data_out; - // xfer.rxbuf = data_in; - // xfer.size = len; - // status = spi_m_sync_transfer(&self->spi_desc, &xfer); + while (!spi_hal_usr_is_done(hal)) { + RUN_BACKGROUND_TASKS(); + } } - return false; // Status is number of chars read or an error code < 0. + + return false; } uint32_t common_hal_busio_spi_get_frequency(busio_spi_obj_t* self) { - // return samd_peripherals_spi_baud_reg_value_to_baudrate(hri_sercomspi_read_BAUD_reg(self->spi_desc.dev.prvt)); - return 0; + return self->real_frequency; } uint8_t common_hal_busio_spi_get_phase(busio_spi_obj_t* self) { - // void * hw = self->spi_desc.dev.prvt; - // return hri_sercomspi_get_CTRLA_CPHA_bit(hw); - return 0; + return self->phase; } uint8_t common_hal_busio_spi_get_polarity(busio_spi_obj_t* self) { - // void * hw = self->spi_desc.dev.prvt; - // return hri_sercomspi_get_CTRLA_CPOL_bit(hw); - return 0; + return self->polarity; } diff --git a/ports/esp32s2/common-hal/busio/SPI.h b/ports/esp32s2/common-hal/busio/SPI.h index 0ff1a4f7ea..0c2f286078 100644 --- a/ports/esp32s2/common-hal/busio/SPI.h +++ b/ports/esp32s2/common-hal/busio/SPI.h @@ -33,10 +33,20 @@ typedef struct { mp_obj_base_t base; - bool has_lock; const mcu_pin_obj_t* clock_pin; const mcu_pin_obj_t* MOSI_pin; const mcu_pin_obj_t* MISO_pin; + spi_host_device_t host_id; + spi_bus_lock_dev_handle_t lock; + spi_hal_context_t hal_context; + spi_hal_timing_conf_t timing_conf; + uint32_t target_frequency; + uint32_t real_frequency; + uint8_t polarity; + uint8_t phase; + uint8_t bits; + bool has_lock; + bool connected_through_gpio; } busio_spi_obj_t; void spi_reset(void); diff --git a/ports/esp32s2/common-hal/busio/UART.c b/ports/esp32s2/common-hal/busio/UART.c index d52e50cade..f73f5c993d 100644 --- a/ports/esp32s2/common-hal/busio/UART.c +++ b/ports/esp32s2/common-hal/busio/UART.c @@ -222,10 +222,10 @@ void common_hal_busio_uart_deinit(busio_uart_obj_t *self) { } uart_driver_delete(self->uart_num); - reset_pin(self->rx_pin); - reset_pin(self->tx_pin); - reset_pin(self->rts_pin); - reset_pin(self->cts_pin); + common_hal_reset_pin(self->rx_pin); + common_hal_reset_pin(self->tx_pin); + common_hal_reset_pin(self->rts_pin); + common_hal_reset_pin(self->cts_pin); self->rx_pin = NULL; self->tx_pin = NULL; self->cts_pin = NULL; diff --git a/ports/esp32s2/common-hal/microcontroller/Pin.c b/ports/esp32s2/common-hal/microcontroller/Pin.c index fd815518d5..075f80abc6 100644 --- a/ports/esp32s2/common-hal/microcontroller/Pin.c +++ b/ports/esp32s2/common-hal/microcontroller/Pin.c @@ -35,6 +35,9 @@ STATIC uint32_t never_reset_pins[2]; STATIC uint32_t in_use[2]; +bool apa102_mosi_in_use; +bool apa102_sck_in_use; + void never_reset_pin_number(gpio_num_t pin_number) { never_reset_pins[pin_number / 32] |= 1 << pin_number % 32; } @@ -49,7 +52,7 @@ void reset_pin_number(gpio_num_t pin_number) { in_use[pin_number / 32] &= ~(1 << pin_number % 32); } -void reset_pin(const mcu_pin_obj_t* pin) { +void common_hal_reset_pin(const mcu_pin_obj_t* pin) { reset_pin_number(pin->number); } diff --git a/ports/esp32s2/common-hal/microcontroller/Pin.h b/ports/esp32s2/common-hal/microcontroller/Pin.h index 573eec392b..ab06b388f8 100644 --- a/ports/esp32s2/common-hal/microcontroller/Pin.h +++ b/ports/esp32s2/common-hal/microcontroller/Pin.h @@ -31,11 +31,14 @@ #include "peripherals/pins.h" +extern bool apa102_mosi_in_use; +extern bool apa102_sck_in_use; + void reset_all_pins(void); // reset_pin_number takes the pin number instead of the pointer so that objects don't // need to store a full pointer. void reset_pin_number(gpio_num_t pin_number); -void reset_pin(const mcu_pin_obj_t* pin); +void common_hal_reset_pin(const mcu_pin_obj_t* pin); void claim_pin(const mcu_pin_obj_t* pin); bool pin_number_is_free(gpio_num_t pin_number); void never_reset_pin_number(gpio_num_t pin_number); From c5fa9730a87b47f569a2bc4a7599e67b198826e6 Mon Sep 17 00:00:00 2001 From: Scott Shawcroft Date: Tue, 23 Jun 2020 12:58:01 -0700 Subject: [PATCH 08/22] Compiles! --- ports/atmel-samd/common-hal/busio/SPI.c | 4 +- .../espressif_saola_1_wrover/mpconfigboard.mk | 2 - ports/esp32s2/common-hal/busio/SPI.c | 82 ++++++++----------- ports/esp32s2/common-hal/busio/SPI.h | 6 +- ports/esp32s2/esp-idf | 2 +- ports/mimxrt10xx/common-hal/busio/SPI.c | 4 +- ports/nrf/common-hal/busio/SPI.c | 6 +- ports/stm/common-hal/busio/SPI.c | 4 +- shared-bindings/busio/SPI.h | 2 +- 9 files changed, 48 insertions(+), 64 deletions(-) diff --git a/ports/atmel-samd/common-hal/busio/SPI.c b/ports/atmel-samd/common-hal/busio/SPI.c index 1dc389027d..921713d690 100644 --- a/ports/atmel-samd/common-hal/busio/SPI.c +++ b/ports/atmel-samd/common-hal/busio/SPI.c @@ -341,7 +341,7 @@ bool common_hal_busio_spi_read(busio_spi_obj_t *self, return status >= 0; // Status is number of chars read or an error code < 0. } -bool common_hal_busio_spi_transfer(busio_spi_obj_t *self, uint8_t *data_out, uint8_t *data_in, size_t len) { +bool common_hal_busio_spi_transfer(busio_spi_obj_t *self, const uint8_t *data_out, uint8_t *data_in, size_t len) { if (len == 0) { return true; } @@ -350,7 +350,7 @@ bool common_hal_busio_spi_transfer(busio_spi_obj_t *self, uint8_t *data_out, uin status = sercom_dma_transfer(self->spi_desc.dev.prvt, data_out, data_in, len); } else { struct spi_xfer xfer; - xfer.txbuf = data_out; + xfer.txbuf = (uint8_t*) data_out; xfer.rxbuf = data_in; xfer.size = len; status = spi_m_sync_transfer(&self->spi_desc, &xfer); diff --git a/ports/esp32s2/boards/espressif_saola_1_wrover/mpconfigboard.mk b/ports/esp32s2/boards/espressif_saola_1_wrover/mpconfigboard.mk index 0b847de943..08f2770f58 100644 --- a/ports/esp32s2/boards/espressif_saola_1_wrover/mpconfigboard.mk +++ b/ports/esp32s2/boards/espressif_saola_1_wrover/mpconfigboard.mk @@ -12,8 +12,6 @@ LONGINT_IMPL = MPZ CFLAGS += -DCFG_TUD_TASK_QUEUE_SZ=32 CIRCUITPY_NEOPIXEL_WRITE = 0 -CIRCUITPY_DIGITALIO = 0 -CIRCUITPY_MICROCONTROLLER = 0 CIRCUITPY_ESP_FLASH_MODE=dio CIRCUITPY_ESP_FLASH_FREQ=40m diff --git a/ports/esp32s2/common-hal/busio/SPI.c b/ports/esp32s2/common-hal/busio/SPI.c index 92a3dd4436..db28dee661 100644 --- a/ports/esp32s2/common-hal/busio/SPI.c +++ b/ports/esp32s2/common-hal/busio/SPI.c @@ -75,10 +75,14 @@ static bool bus_uses_iomux_pins(spi_host_device_t host, const spi_bus_config_t* // End copied code. -static bool spi_bus_free(spi_host_device_t host_id) { +static bool _spi_bus_free(spi_host_device_t host_id) { return spi_bus_get_attr(host_id) == NULL; } +static void spi_interrupt_handler(void *arg) { + +} + void common_hal_busio_spi_construct(busio_spi_obj_t *self, const mcu_pin_obj_t * clock, const mcu_pin_obj_t * mosi, const mcu_pin_obj_t * miso) { @@ -90,8 +94,8 @@ void common_hal_busio_spi_construct(busio_spi_obj_t *self, bus_config.quadhd_io_num = -1; bus_config.max_transfer_sz = 0; // Uses the default bus_config.flags = SPICOMMON_BUSFLAG_MASTER | SPICOMMON_BUSFLAG_SCLK | - mosi != NULL ? SPICOMMON_BUSFLAG_MOSI : 0 | - miso != NULL ? SPICOMMON_BUSFLAG_MISO : 0; + (mosi != NULL ? SPICOMMON_BUSFLAG_MOSI : 0) | + (miso != NULL ? SPICOMMON_BUSFLAG_MISO : 0); bus_config.intr_flags = 0; // RAM and Flash is often on SPI1 and is unsupported by the IDF so use it as @@ -99,12 +103,12 @@ void common_hal_busio_spi_construct(busio_spi_obj_t *self, spi_host_device_t host_id = SPI1_HOST; self->connected_through_gpio = true; // Try and save SPI2 for pins that are on the IOMUX - if (bus_uses_iomux_pins(SPI2_HOST, &bus_config) && spi_bus_free(SPI2_HOST)) { + if (bus_uses_iomux_pins(SPI2_HOST, &bus_config) && _spi_bus_free(SPI2_HOST)) { host_id = SPI2_HOST; self->connected_through_gpio = false; - } else if (spi_bus_free(SPI3_HOST)) { + } else if (_spi_bus_free(SPI3_HOST)) { host_id = SPI3_HOST; - } else if (spi_bus_free(SPI2_HOST)) { + } else if (_spi_bus_free(SPI2_HOST)) { host_id = SPI2_HOST; } if (host_id == SPI1_HOST) { @@ -114,21 +118,21 @@ void common_hal_busio_spi_construct(busio_spi_obj_t *self, esp_err_t result = spi_bus_initialize(host_id, &bus_config, 0 /* dma channel */); if (result == ESP_ERR_NO_MEM) { mp_raise_msg(&mp_type_MemoryError, translate("ESP-IDF memory allocation failed")); - } else if (result = ESP_INVALID_ARG) { + } else if (result == ESP_ERR_INVALID_ARG) { mp_raise_ValueError(translate("Invalid pins")); } spi_bus_lock_dev_config_t config = { .flags = 0 }; result = spi_bus_lock_register_dev(spi_bus_get_attr(host_id)->lock, - spi_bus_lock_dev_config_t *config, + &config, &self->lock); if (result == ESP_ERR_NO_MEM) { mp_raise_msg(&mp_type_MemoryError, translate("ESP-IDF memory allocation failed")); } - err = esp_intr_alloc(spicommon_irqsource_for_host(host_id), - bus_config.intr_flags | ESP_INTR_FLAG_INTRDISABLED, - spi_interrupt_handler, self, &self->intr); + result = esp_intr_alloc(spicommon_irqsource_for_host(host_id), + bus_config.intr_flags | ESP_INTR_FLAG_INTRDISABLED, + spi_interrupt_handler, self, &self->interrupt); if (result == ESP_ERR_NO_MEM) { mp_raise_msg(&mp_type_MemoryError, translate("ESP-IDF memory allocation failed")); } @@ -198,18 +202,21 @@ bool common_hal_busio_spi_configure(busio_spi_obj_t *self, bits == self->bits) { return true; } - self->hal_context->mode = polarity << 1 | phase; + self->hal_context.mode = polarity << 1 | phase; self->polarity = polarity; self->phase = phase; self->bits = bits; self->target_frequency = baudrate; - esp_err_t result = spi_hal_get_clock_conf(self->hal_context, + esp_err_t result = spi_hal_get_clock_conf(&self->hal_context, self->target_frequency, 128 /* duty_cycle */, self->connected_through_gpio, 0 /* input_delay_ns */, &self->real_frequency, &self->timing_conf); + if (result != ESP_OK) { + return false; + } spi_hal_setup_device(&self->hal_context); return true; @@ -222,9 +229,9 @@ bool common_hal_busio_spi_try_lock(busio_spi_obj_t *self) { return false; } // Wait to grab the lock from another task. - esp_err_t ret = spi_bus_lock_acquire_start(self->lock, portMAX_DELAY); - self->has_lock = true; - return true; + esp_err_t result = spi_bus_lock_acquire_start(self->lock, portMAX_DELAY); + self->has_lock = result == ESP_OK; + return self->has_lock; } bool common_hal_busio_spi_has_lock(busio_spi_obj_t *self) { @@ -238,62 +245,37 @@ void common_hal_busio_spi_unlock(busio_spi_obj_t *self) { bool common_hal_busio_spi_write(busio_spi_obj_t *self, const uint8_t *data, size_t len) { - if (len == 0) { - return true; - } - // int32_t status; - if (len >= 16) { - // status = sercom_dma_write(self->spi_desc.dev.prvt, data, len); - } else { - // struct io_descriptor *spi_io; - // spi_m_sync_get_io_descriptor(&self->spi_desc, &spi_io); - // status = spi_io->write(spi_io, data, len); - } - return false; // Status is number of chars read or an error code < 0. + return common_hal_busio_spi_transfer(self, data, NULL, len); } bool common_hal_busio_spi_read(busio_spi_obj_t *self, uint8_t *data, size_t len, uint8_t write_value) { - if (len == 0) { - return true; - } - // int32_t status; - if (len >= 16) { - // status = sercom_dma_read(self->spi_desc.dev.prvt, data, len, write_value); - } else { - // self->spi_desc.dev.dummy_byte = write_value; - - // struct io_descriptor *spi_io; - // spi_m_sync_get_io_descriptor(&self->spi_desc, &spi_io); - - // status = spi_io->read(spi_io, data, len); - } - return false; // Status is number of chars read or an error code < 0. + return common_hal_busio_spi_transfer(self, NULL, data, len); } -bool common_hal_busio_spi_transfer(busio_spi_obj_t *self, uint8_t *data_out, uint8_t *data_in, size_t len) { +bool common_hal_busio_spi_transfer(busio_spi_obj_t *self, const uint8_t *data_out, uint8_t *data_in, size_t len) { if (len == 0) { return true; } spi_hal_context_t* hal = &self->hal_context; - hal->tx_bitlen = len * 8; - hal->rx_bitlen = len * 8; - hal->send_buffer = data_out; + hal->tx_bitlen = len * self->bits; + hal->rx_bitlen = len * self->bits; + hal->send_buffer = (uint8_t*) data_out; hal->rcv_buffer = data_in; spi_hal_setup_trans(hal); spi_hal_prepare_data(hal); spi_hal_user_start(hal); - if (len >= 16 && false) { + if (len >= SOC_SPI_MAXIMUM_BUFFER_SIZE && false) { // Set up the interrupt and wait on the lock. } else { while (!spi_hal_usr_is_done(hal)) { - RUN_BACKGROUND_TASKS(); + RUN_BACKGROUND_TASKS; } } - return false; + return true; } uint32_t common_hal_busio_spi_get_frequency(busio_spi_obj_t* self) { diff --git a/ports/esp32s2/common-hal/busio/SPI.h b/ports/esp32s2/common-hal/busio/SPI.h index 0c2f286078..38fbe42ffc 100644 --- a/ports/esp32s2/common-hal/busio/SPI.h +++ b/ports/esp32s2/common-hal/busio/SPI.h @@ -29,6 +29,9 @@ #include "common-hal/microcontroller/Pin.h" +#include "esp-idf/components/driver/include/driver/spi_common_internal.h" +#include "esp-idf/components/soc/include/hal/spi_hal.h" +#include "esp-idf/components/soc/include/hal/spi_types.h" #include "py/obj.h" typedef struct { @@ -40,8 +43,9 @@ typedef struct { spi_bus_lock_dev_handle_t lock; spi_hal_context_t hal_context; spi_hal_timing_conf_t timing_conf; + intr_handle_t interrupt; uint32_t target_frequency; - uint32_t real_frequency; + int32_t real_frequency; uint8_t polarity; uint8_t phase; uint8_t bits; diff --git a/ports/esp32s2/esp-idf b/ports/esp32s2/esp-idf index 648f959037..160ba4924d 160000 --- a/ports/esp32s2/esp-idf +++ b/ports/esp32s2/esp-idf @@ -1 +1 @@ -Subproject commit 648f959037896cff887a05b67105748790bfe63a +Subproject commit 160ba4924d8b588e718f76e3a0d0e92c11052fa3 diff --git a/ports/mimxrt10xx/common-hal/busio/SPI.c b/ports/mimxrt10xx/common-hal/busio/SPI.c index c51aef4daa..8fe1b799d6 100644 --- a/ports/mimxrt10xx/common-hal/busio/SPI.c +++ b/ports/mimxrt10xx/common-hal/busio/SPI.c @@ -321,7 +321,7 @@ bool common_hal_busio_spi_read(busio_spi_obj_t *self, return (status == kStatus_Success); } -bool common_hal_busio_spi_transfer(busio_spi_obj_t *self, uint8_t *data_out, uint8_t *data_in, size_t len) { +bool common_hal_busio_spi_transfer(busio_spi_obj_t *self, const uint8_t *data_out, uint8_t *data_in, size_t len) { if (len == 0) { return true; } @@ -332,7 +332,7 @@ bool common_hal_busio_spi_transfer(busio_spi_obj_t *self, uint8_t *data_out, uin LPSPI_SetDummyData(self->spi, 0xFF); lpspi_transfer_t xfer = { 0 }; - xfer.txData = data_out; + xfer.txData = (uint8_t *)data_out; xfer.rxData = data_in; xfer.dataSize = len; diff --git a/ports/nrf/common-hal/busio/SPI.c b/ports/nrf/common-hal/busio/SPI.c index 3f205e7782..f27f0e267b 100644 --- a/ports/nrf/common-hal/busio/SPI.c +++ b/ports/nrf/common-hal/busio/SPI.c @@ -271,13 +271,13 @@ bool common_hal_busio_spi_read(busio_spi_obj_t *self, uint8_t *data, size_t len, return true; } -bool common_hal_busio_spi_transfer(busio_spi_obj_t *self, uint8_t *data_out, uint8_t *data_in, size_t len) { +bool common_hal_busio_spi_transfer(busio_spi_obj_t *self, const uint8_t *data_out, uint8_t *data_in, size_t len) { const bool is_spim3 = self->spim_peripheral->spim.p_reg == NRF_SPIM3; - uint8_t *next_chunk_out = data_out; + const uint8_t *next_chunk_out = data_out; uint8_t *next_chunk_in = data_in; while (len > 0) { - uint8_t *chunk_out = next_chunk_out; + const uint8_t *chunk_out = next_chunk_out; size_t chunk_size = MIN(len, self->spim_peripheral->max_xfer_size); if (is_spim3) { // If SPIM3, copy into unused RAM block, and do DMA from there. diff --git a/ports/stm/common-hal/busio/SPI.c b/ports/stm/common-hal/busio/SPI.c index 65eeb8ebcf..c76705cd85 100644 --- a/ports/stm/common-hal/busio/SPI.c +++ b/ports/stm/common-hal/busio/SPI.c @@ -380,12 +380,12 @@ bool common_hal_busio_spi_read(busio_spi_obj_t *self, } bool common_hal_busio_spi_transfer(busio_spi_obj_t *self, - uint8_t *data_out, uint8_t *data_in, size_t len) { + const uint8_t *data_out, uint8_t *data_in, size_t len) { if (self->miso == NULL || self->mosi == NULL) { mp_raise_ValueError(translate("Missing MISO or MOSI Pin")); } HAL_StatusTypeDef result = HAL_SPI_TransmitReceive (&self->handle, - data_out, data_in, (uint16_t)len,HAL_MAX_DELAY); + (uint8_t *) data_out, data_in, (uint16_t)len,HAL_MAX_DELAY); return result == HAL_OK; } diff --git a/shared-bindings/busio/SPI.h b/shared-bindings/busio/SPI.h index b7b0715d13..f1a3b041ff 100644 --- a/shared-bindings/busio/SPI.h +++ b/shared-bindings/busio/SPI.h @@ -56,7 +56,7 @@ extern bool common_hal_busio_spi_write(busio_spi_obj_t *self, const uint8_t *dat extern bool common_hal_busio_spi_read(busio_spi_obj_t *self, uint8_t *data, size_t len, uint8_t write_value); // Reads and write len bytes simultaneously. -extern bool common_hal_busio_spi_transfer(busio_spi_obj_t *self, uint8_t *data_out, uint8_t *data_in, size_t len); +extern bool common_hal_busio_spi_transfer(busio_spi_obj_t *self, const uint8_t *data_out, uint8_t *data_in, size_t len); // Return actual SPI bus frequency. uint32_t common_hal_busio_spi_get_frequency(busio_spi_obj_t* self); From 496e16d99b2277a09ab8a518ee94450653e63317 Mon Sep 17 00:00:00 2001 From: Scott Shawcroft Date: Tue, 23 Jun 2020 17:02:16 -0700 Subject: [PATCH 09/22] Handle memory (hopefully). Short TX works --- ports/esp32s2/Makefile | 3 ++ ports/esp32s2/common-hal/busio/SPI.c | 79 +++++++++++++++++++++++++--- 2 files changed, 74 insertions(+), 8 deletions(-) diff --git a/ports/esp32s2/Makefile b/ports/esp32s2/Makefile index 29504065e9..ee1e8107a6 100644 --- a/ports/esp32s2/Makefile +++ b/ports/esp32s2/Makefile @@ -281,6 +281,9 @@ $(BUILD)/firmware.uf2: $(BUILD)/circuitpython-firmware.bin flash: $(BUILD)/firmware.bin esptool.py --chip esp32s2 -p $(PORT) --no-stub -b 460800 --before=default_reset --after=hard_reset write_flash $(FLASH_FLAGS) 0x0000 $^ +flash-circuitpython-only: $(BUILD)/circuitpython-firmware.bin + esptool.py --chip esp32s2 -p $(PORT) --no-stub -b 460800 --before=default_reset --after=hard_reset write_flash $(FLASH_FLAGS) 0x10000 $^ + include $(TOP)/py/mkrules.mk # Print out the value of a make variable. diff --git a/ports/esp32s2/common-hal/busio/SPI.c b/ports/esp32s2/common-hal/busio/SPI.c index db28dee661..9790c516ff 100644 --- a/ports/esp32s2/common-hal/busio/SPI.c +++ b/ports/esp32s2/common-hal/busio/SPI.c @@ -32,14 +32,35 @@ #include "common-hal/microcontroller/Pin.h" #include "supervisor/shared/rgb_led_status.h" +#include "esp_log.h" + +static const char* TAG = "CircuitPython SPI"; + static bool spi_never_reset[SOC_SPI_PERIPH_NUM]; +// Store one lock handle per device so that we can free it. +static spi_bus_lock_dev_handle_t lock_dev_handle[SOC_SPI_PERIPH_NUM]; +static intr_handle_t intr_handle[SOC_SPI_PERIPH_NUM]; + void spi_reset(void) { for (spi_host_device_t host_id = SPI2_HOST; host_id < SOC_SPI_PERIPH_NUM; host_id++) { if (spi_never_reset[host_id]) { continue; } - spi_bus_free(host_id); + bool in_use = false; + if (lock_dev_handle[host_id] != NULL) { + spi_bus_lock_unregister_dev(lock_dev_handle[host_id]); + lock_dev_handle[host_id] = NULL; + in_use = true; + } + if (intr_handle[host_id] != NULL) { + esp_intr_free(intr_handle[host_id]); + intr_handle[host_id] = NULL; + in_use = true; + } + if (in_use) { + spi_bus_free(host_id); + } } } @@ -75,12 +96,24 @@ static bool bus_uses_iomux_pins(spi_host_device_t host, const spi_bus_config_t* // End copied code. -static bool _spi_bus_free(spi_host_device_t host_id) { +static bool spi_bus_is_free(spi_host_device_t host_id) { return spi_bus_get_attr(host_id) == NULL; } static void spi_interrupt_handler(void *arg) { + // busio_spi_obj_t *self = arg; +} +// The interrupt may get invoked by the bus lock. +static void spi_bus_intr_enable(void *self) +{ + esp_intr_enable(((busio_spi_obj_t *)self)->interrupt); +} + +// The interrupt is always disabled by the ISR itself, not exposed +static void spi_bus_intr_disable(void *self) +{ + esp_intr_disable(((busio_spi_obj_t *)self)->interrupt); } void common_hal_busio_spi_construct(busio_spi_obj_t *self, @@ -103,12 +136,12 @@ void common_hal_busio_spi_construct(busio_spi_obj_t *self, spi_host_device_t host_id = SPI1_HOST; self->connected_through_gpio = true; // Try and save SPI2 for pins that are on the IOMUX - if (bus_uses_iomux_pins(SPI2_HOST, &bus_config) && _spi_bus_free(SPI2_HOST)) { + if (bus_uses_iomux_pins(SPI2_HOST, &bus_config) && spi_bus_is_free(SPI2_HOST)) { host_id = SPI2_HOST; self->connected_through_gpio = false; - } else if (_spi_bus_free(SPI3_HOST)) { + } else if (spi_bus_is_free(SPI3_HOST)) { host_id = SPI3_HOST; - } else if (_spi_bus_free(SPI2_HOST)) { + } else if (spi_bus_is_free(SPI2_HOST)) { host_id = SPI2_HOST; } if (host_id == SPI1_HOST) { @@ -121,21 +154,33 @@ void common_hal_busio_spi_construct(busio_spi_obj_t *self, } else if (result == ESP_ERR_INVALID_ARG) { mp_raise_ValueError(translate("Invalid pins")); } + + // After this point, we need to deinit to free IDF memory so fill out self's pins. + self->clock_pin = clock; + self->MOSI_pin = mosi; + self->MISO_pin = miso; + spi_bus_lock_dev_config_t config = { .flags = 0 }; + // The returned lock is stored in the bus lock but must be freed separately with + // spi_bus_lock_unregister_dev. result = spi_bus_lock_register_dev(spi_bus_get_attr(host_id)->lock, &config, &self->lock); if (result == ESP_ERR_NO_MEM) { + common_hal_busio_spi_deinit(self); mp_raise_msg(&mp_type_MemoryError, translate("ESP-IDF memory allocation failed")); } - + lock_dev_handle[host_id] = self->lock; result = esp_intr_alloc(spicommon_irqsource_for_host(host_id), bus_config.intr_flags | ESP_INTR_FLAG_INTRDISABLED, spi_interrupt_handler, self, &self->interrupt); if (result == ESP_ERR_NO_MEM) { + common_hal_busio_spi_deinit(self); mp_raise_msg(&mp_type_MemoryError, translate("ESP-IDF memory allocation failed")); } + intr_handle[host_id] = self->interrupt; + spi_bus_lock_set_bg_control(spi_bus_get_attr(host_id)->lock, spi_bus_intr_enable, spi_bus_intr_disable, self); spi_hal_context_t* hal = &self->hal_context; hal->hw = NULL; // Set by spi_hal_init @@ -146,8 +191,7 @@ void common_hal_busio_spi_construct(busio_spi_obj_t *self, // We don't use native CS. hal->cs_setup = 0; hal->cs_hold = 0; - hal->cs_pin_id = -1; - hal->timing_conf = &self->timing_conf; + hal->cs_pin_id = 0; hal->sio = 1; hal->half_duplex = 0; @@ -167,6 +211,13 @@ void common_hal_busio_spi_construct(busio_spi_obj_t *self, hal->io_mode = SPI_LL_IO_MODE_NORMAL; spi_hal_init(hal, host_id); + // This must be set after spi_hal_init. + hal->timing_conf = &self->timing_conf; + if (hal->hw == NULL) { + ESP_LOGE(TAG, "SPI error %p", hal->hw); + } + + common_hal_busio_spi_configure(self, 250000, 0, 0, 8); } void common_hal_busio_spi_never_reset(busio_spi_obj_t *self) { @@ -186,6 +237,14 @@ void common_hal_busio_spi_deinit(busio_spi_obj_t *self) { return; } spi_never_reset[self->host_id] = false; + if (self->lock != NULL) { + spi_bus_lock_unregister_dev(self->lock); + lock_dev_handle[self->host_id] = NULL; + } + if (self->interrupt != NULL) { + esp_intr_free(self->interrupt); + intr_handle[self->host_id] = NULL; + } spi_bus_free(self->host_id); common_hal_reset_pin(self->clock_pin); @@ -218,7 +277,11 @@ bool common_hal_busio_spi_configure(busio_spi_obj_t *self, return false; } + ESP_LOGI(TAG, "configure"); + ESP_LOGI(TAG, "real frequency %d", self->real_frequency); + ESP_LOGI(TAG, "timing_conf %p", self->hal_context.timing_conf); spi_hal_setup_device(&self->hal_context); + ESP_LOGI(TAG, "setup done"); return true; } From ed6e81d688469138b555f3579b1083f521485382 Mon Sep 17 00:00:00 2001 From: Scott Shawcroft Date: Wed, 24 Jun 2020 12:46:36 -0700 Subject: [PATCH 10/22] Switch SPI to polling DMA and enable displayio --- ports/esp32s2/background.c | 6 +- .../boards/espressif_saola_1_wrover/board.c | 8 +- ports/esp32s2/common-hal/busio/I2C.c | 5 +- ports/esp32s2/common-hal/busio/SPI.c | 80 +++++++++++-------- ports/esp32s2/common-hal/busio/SPI.h | 4 + .../common-hal/displayio/ParallelBus.c | 66 +++++++++++++++ .../common-hal/displayio/ParallelBus.h | 36 +++++++++ .../esp32s2/common-hal/microcontroller/Pin.c | 2 +- .../esp32s2/common-hal/microcontroller/Pin.h | 1 - ports/esp32s2/modules/wroom.c | 12 +-- ports/esp32s2/modules/wrover.c | 14 ++-- ports/esp32s2/mpconfigport.mk | 2 +- shared-module/displayio/Display.h | 4 + shared-module/displayio/EPaperDisplay.h | 1 - 14 files changed, 182 insertions(+), 59 deletions(-) create mode 100644 ports/esp32s2/common-hal/displayio/ParallelBus.c create mode 100644 ports/esp32s2/common-hal/displayio/ParallelBus.h diff --git a/ports/esp32s2/background.c b/ports/esp32s2/background.c index e22cf4aacc..e979d78311 100644 --- a/ports/esp32s2/background.c +++ b/ports/esp32s2/background.c @@ -54,9 +54,9 @@ void run_background_tasks(void) { running_background_tasks = true; filesystem_background(); - // #if CIRCUITPY_DISPLAYIO - // displayio_background(); - // #endif + #if CIRCUITPY_DISPLAYIO + displayio_background(); + #endif running_background_tasks = false; assert_heap_ok(); diff --git a/ports/esp32s2/boards/espressif_saola_1_wrover/board.c b/ports/esp32s2/boards/espressif_saola_1_wrover/board.c index b7b2c4ef5b..9f708874bf 100644 --- a/ports/esp32s2/boards/espressif_saola_1_wrover/board.c +++ b/ports/esp32s2/boards/espressif_saola_1_wrover/board.c @@ -30,12 +30,12 @@ void board_init(void) { // USB - never_reset_pin(&pin_GPIO19); - never_reset_pin(&pin_GPIO20); + common_hal_never_reset_pin(&pin_GPIO19); + common_hal_never_reset_pin(&pin_GPIO20); // Debug UART - never_reset_pin(&pin_GPIO43); - never_reset_pin(&pin_GPIO44); + common_hal_never_reset_pin(&pin_GPIO43); + common_hal_never_reset_pin(&pin_GPIO44); } bool board_requests_safe_mode(void) { diff --git a/ports/esp32s2/common-hal/busio/I2C.c b/ports/esp32s2/common-hal/busio/I2C.c index 51817c95e2..391d7323c5 100644 --- a/ports/esp32s2/common-hal/busio/I2C.c +++ b/ports/esp32s2/common-hal/busio/I2C.c @@ -31,6 +31,7 @@ #include "driver/i2c.h" #include "shared-bindings/microcontroller/__init__.h" +#include "shared-bindings/microcontroller/Pin.h" #include "supervisor/shared/translate.h" typedef enum { @@ -217,6 +218,6 @@ uint8_t common_hal_busio_i2c_read(busio_i2c_obj_t *self, uint16_t addr, void common_hal_busio_i2c_never_reset(busio_i2c_obj_t *self) { never_reset_i2c(self->i2c_num); - never_reset_pin(self->scl_pin); - never_reset_pin(self->sda_pin); + common_hal_never_reset_pin(self->scl_pin); + common_hal_never_reset_pin(self->sda_pin); } diff --git a/ports/esp32s2/common-hal/busio/SPI.c b/ports/esp32s2/common-hal/busio/SPI.c index 9790c516ff..686f44cbc2 100644 --- a/ports/esp32s2/common-hal/busio/SPI.c +++ b/ports/esp32s2/common-hal/busio/SPI.c @@ -29,7 +29,7 @@ #include "py/runtime.h" #include "boards/board.h" -#include "common-hal/microcontroller/Pin.h" +#include "shared-bindings/microcontroller/Pin.h" #include "supervisor/shared/rgb_led_status.h" #include "esp_log.h" @@ -101,7 +101,8 @@ static bool spi_bus_is_free(spi_host_device_t host_id) { } static void spi_interrupt_handler(void *arg) { - // busio_spi_obj_t *self = arg; + busio_spi_obj_t *self = arg; + ESP_LOGE(TAG, "SPI interrupt %p", self); } // The interrupt may get invoked by the bus lock. @@ -148,7 +149,7 @@ void common_hal_busio_spi_construct(busio_spi_obj_t *self, mp_raise_ValueError(translate("All SPI peripherals are in use")); } - esp_err_t result = spi_bus_initialize(host_id, &bus_config, 0 /* dma channel */); + esp_err_t result = spi_bus_initialize(host_id, &bus_config, host_id /* dma channel */); if (result == ESP_ERR_NO_MEM) { mp_raise_msg(&mp_type_MemoryError, translate("ESP-IDF memory allocation failed")); } else if (result == ESP_ERR_INVALID_ARG) { @@ -183,34 +184,35 @@ void common_hal_busio_spi_construct(busio_spi_obj_t *self, spi_bus_lock_set_bg_control(spi_bus_get_attr(host_id)->lock, spi_bus_intr_enable, spi_bus_intr_disable, self); spi_hal_context_t* hal = &self->hal_context; - hal->hw = NULL; // Set by spi_hal_init - hal->dmadesc_tx = NULL; - hal->dmadesc_rx = NULL; - hal->dmadesc_n = 0; + + // spi_hal_init clears the given hal context so set everything after. + spi_hal_init(hal, host_id); + hal->dmadesc_tx = &self->tx_dma; + hal->dmadesc_rx = &self->rx_dma; + hal->dmadesc_n = 1; // We don't use native CS. - hal->cs_setup = 0; - hal->cs_hold = 0; - hal->cs_pin_id = 0; + // hal->cs_setup = 0; + // hal->cs_hold = 0; + // hal->cs_pin_id = 0; hal->sio = 1; - hal->half_duplex = 0; - hal->tx_lsbfirst = 0; - hal->rx_lsbfirst = 0; - hal->dma_enabled = 0; + // hal->half_duplex = 0; + // hal->tx_lsbfirst = 0; + // hal->rx_lsbfirst = 0; + hal->dma_enabled = 1; hal->no_compensate = 1; // Ignore CS bits // We don't use cmd, addr or dummy bits. - hal->cmd = 0; - hal->cmd_bits = 0; - hal->addr_bits = 0; - hal->dummy_bits = 0; - hal->addr = 0; + // hal->cmd = 0; + // hal->cmd_bits = 0; + // hal->addr_bits = 0; + // hal->dummy_bits = 0; + // hal->addr = 0; hal->io_mode = SPI_LL_IO_MODE_NORMAL; - spi_hal_init(hal, host_id); // This must be set after spi_hal_init. hal->timing_conf = &self->timing_conf; if (hal->hw == NULL) { @@ -223,9 +225,9 @@ void common_hal_busio_spi_construct(busio_spi_obj_t *self, void common_hal_busio_spi_never_reset(busio_spi_obj_t *self) { spi_never_reset[self->host_id] = true; - never_reset_pin(self->clock_pin); - never_reset_pin(self->MOSI_pin); - never_reset_pin(self->MISO_pin); + common_hal_never_reset_pin(self->clock_pin); + common_hal_never_reset_pin(self->MOSI_pin); + common_hal_never_reset_pin(self->MISO_pin); } bool common_hal_busio_spi_deinited(busio_spi_obj_t *self) { @@ -322,17 +324,29 @@ bool common_hal_busio_spi_transfer(busio_spi_obj_t *self, const uint8_t *data_ou } spi_hal_context_t* hal = &self->hal_context; - hal->tx_bitlen = len * self->bits; - hal->rx_bitlen = len * self->bits; - hal->send_buffer = (uint8_t*) data_out; - hal->rcv_buffer = data_in; + hal->send_buffer = NULL; + hal->rcv_buffer = NULL; + // This rounds up. + size_t dma_count = (len + LLDESC_MAX_NUM_PER_DESC - 1) / LLDESC_MAX_NUM_PER_DESC; + for (size_t i = 0; i < dma_count; i++) { + size_t offset = LLDESC_MAX_NUM_PER_DESC * i; + size_t dma_len = len - offset; + if (dma_len > LLDESC_MAX_NUM_PER_DESC) { + dma_len = LLDESC_MAX_NUM_PER_DESC; + } + hal->tx_bitlen = dma_len * self->bits; + hal->rx_bitlen = dma_len * self->bits; + if (data_out != NULL) { + hal->send_buffer = (uint8_t*) data_out + offset; + } + if (data_in != NULL) { + hal->rcv_buffer = data_in + offset; + } - spi_hal_setup_trans(hal); - spi_hal_prepare_data(hal); - spi_hal_user_start(hal); - if (len >= SOC_SPI_MAXIMUM_BUFFER_SIZE && false) { - // Set up the interrupt and wait on the lock. - } else { + spi_hal_setup_trans(hal); + spi_hal_prepare_data(hal); + spi_hal_user_start(hal); + // TODO: Switch to waiting on a lock that is given by an interrupt. while (!spi_hal_usr_is_done(hal)) { RUN_BACKGROUND_TASKS; } diff --git a/ports/esp32s2/common-hal/busio/SPI.h b/ports/esp32s2/common-hal/busio/SPI.h index 38fbe42ffc..6d82038317 100644 --- a/ports/esp32s2/common-hal/busio/SPI.h +++ b/ports/esp32s2/common-hal/busio/SPI.h @@ -44,6 +44,10 @@ typedef struct { spi_hal_context_t hal_context; spi_hal_timing_conf_t timing_conf; intr_handle_t interrupt; + // IDF allocates these in DMA accessible memory so they may need to move when + // we use external RAM for CircuitPython. + lldesc_t tx_dma; + lldesc_t rx_dma; uint32_t target_frequency; int32_t real_frequency; uint8_t polarity; diff --git a/ports/esp32s2/common-hal/displayio/ParallelBus.c b/ports/esp32s2/common-hal/displayio/ParallelBus.c new file mode 100644 index 0000000000..314b72ff73 --- /dev/null +++ b/ports/esp32s2/common-hal/displayio/ParallelBus.c @@ -0,0 +1,66 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2019 Lucian Copeland for Adafruit Industries + * + * 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. + */ + +#include "shared-bindings/displayio/ParallelBus.h" + +#include + +#include "common-hal/microcontroller/Pin.h" +#include "py/runtime.h" +#include "shared-bindings/digitalio/DigitalInOut.h" +#include "shared-bindings/microcontroller/__init__.h" + +void common_hal_displayio_parallelbus_construct(displayio_parallelbus_obj_t* self, + const mcu_pin_obj_t* data0, const mcu_pin_obj_t* command, const mcu_pin_obj_t* chip_select, + const mcu_pin_obj_t* write, const mcu_pin_obj_t* read, const mcu_pin_obj_t* reset) { + + mp_raise_NotImplementedError(translate("ParallelBus not yet supported")); +} + +void common_hal_displayio_parallelbus_deinit(displayio_parallelbus_obj_t* self) { + +} + +bool common_hal_displayio_parallelbus_reset(mp_obj_t obj) { + return false; +} + +bool common_hal_displayio_parallelbus_bus_free(mp_obj_t obj) { + return false; +} + +bool common_hal_displayio_parallelbus_begin_transaction(mp_obj_t obj) { + + return false; +} + +void common_hal_displayio_parallelbus_send(mp_obj_t obj, display_byte_type_t byte_type, display_chip_select_behavior_t chip_select, uint8_t *data, uint32_t data_length) { + +} + +void common_hal_displayio_parallelbus_end_transaction(mp_obj_t obj) { + +} diff --git a/ports/esp32s2/common-hal/displayio/ParallelBus.h b/ports/esp32s2/common-hal/displayio/ParallelBus.h new file mode 100644 index 0000000000..cd636921d9 --- /dev/null +++ b/ports/esp32s2/common-hal/displayio/ParallelBus.h @@ -0,0 +1,36 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2019 Lucian Copeland for Adafruit Industries + * + * 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. + */ + +#ifndef MICROPY_INCLUDED_ESP32S2_COMMON_HAL_DISPLAYIO_PARALLELBUS_H +#define MICROPY_INCLUDED_ESP32S2_COMMON_HAL_DISPLAYIO_PARALLELBUS_H + +#include "common-hal/digitalio/DigitalInOut.h" + +typedef struct { + mp_obj_base_t base; +} displayio_parallelbus_obj_t; + +#endif // MICROPY_INCLUDED_ESP32S2_COMMON_HAL_DISPLAYIO_PARALLELBUS_H diff --git a/ports/esp32s2/common-hal/microcontroller/Pin.c b/ports/esp32s2/common-hal/microcontroller/Pin.c index 075f80abc6..5a059f0bbc 100644 --- a/ports/esp32s2/common-hal/microcontroller/Pin.c +++ b/ports/esp32s2/common-hal/microcontroller/Pin.c @@ -42,7 +42,7 @@ void never_reset_pin_number(gpio_num_t pin_number) { never_reset_pins[pin_number / 32] |= 1 << pin_number % 32; } -void never_reset_pin(const mcu_pin_obj_t* pin) { +void common_hal_never_reset_pin(const mcu_pin_obj_t* pin) { never_reset_pin_number(pin->number); } diff --git a/ports/esp32s2/common-hal/microcontroller/Pin.h b/ports/esp32s2/common-hal/microcontroller/Pin.h index ab06b388f8..19985bda6f 100644 --- a/ports/esp32s2/common-hal/microcontroller/Pin.h +++ b/ports/esp32s2/common-hal/microcontroller/Pin.h @@ -42,6 +42,5 @@ void common_hal_reset_pin(const mcu_pin_obj_t* pin); void claim_pin(const mcu_pin_obj_t* pin); bool pin_number_is_free(gpio_num_t pin_number); void never_reset_pin_number(gpio_num_t pin_number); -void never_reset_pin(const mcu_pin_obj_t* pin); #endif // MICROPY_INCLUDED_ESP32S2_COMMON_HAL_MICROCONTROLLER_PIN_H diff --git a/ports/esp32s2/modules/wroom.c b/ports/esp32s2/modules/wroom.c index 16c5861187..5e530701bf 100644 --- a/ports/esp32s2/modules/wroom.c +++ b/ports/esp32s2/modules/wroom.c @@ -28,10 +28,10 @@ void never_reset_module_internal_pins(void) { // SPI Flash - never_reset_pin(&pin_GPIO27); - never_reset_pin(&pin_GPIO28); - never_reset_pin(&pin_GPIO29); - never_reset_pin(&pin_GPIO30); - never_reset_pin(&pin_GPIO31); - never_reset_pin(&pin_GPIO32); + common_hal_never_reset_pin(&pin_GPIO27); + common_hal_never_reset_pin(&pin_GPIO28); + common_hal_never_reset_pin(&pin_GPIO29); + common_hal_never_reset_pin(&pin_GPIO30); + common_hal_never_reset_pin(&pin_GPIO31); + common_hal_never_reset_pin(&pin_GPIO32); } diff --git a/ports/esp32s2/modules/wrover.c b/ports/esp32s2/modules/wrover.c index d589a8fd4d..23fa7ee5ca 100644 --- a/ports/esp32s2/modules/wrover.c +++ b/ports/esp32s2/modules/wrover.c @@ -28,11 +28,11 @@ void never_reset_module_internal_pins(void) { // SPI Flash and RAM - never_reset_pin(&pin_GPIO26); - never_reset_pin(&pin_GPIO27); - never_reset_pin(&pin_GPIO28); - never_reset_pin(&pin_GPIO29); - never_reset_pin(&pin_GPIO30); - never_reset_pin(&pin_GPIO31); - never_reset_pin(&pin_GPIO32); + common_hal_never_reset_pin(&pin_GPIO26); + common_hal_never_reset_pin(&pin_GPIO27); + common_hal_never_reset_pin(&pin_GPIO28); + common_hal_never_reset_pin(&pin_GPIO29); + common_hal_never_reset_pin(&pin_GPIO30); + common_hal_never_reset_pin(&pin_GPIO31); + common_hal_never_reset_pin(&pin_GPIO32); } diff --git a/ports/esp32s2/mpconfigport.mk b/ports/esp32s2/mpconfigport.mk index 9f59c1b467..8e2745a8c6 100644 --- a/ports/esp32s2/mpconfigport.mk +++ b/ports/esp32s2/mpconfigport.mk @@ -20,7 +20,7 @@ CIRCUITPY_BITBANGIO = 1 CIRCUITPY_BOARD = 1 CIRCUITPY_DIGITALIO = 1 CIRCUITPY_BUSIO = 1 -CIRCUITPY_DISPLAYIO = 0 +CIRCUITPY_DISPLAYIO = 1 CIRCUITPY_FREQUENCYIO = 0 CIRCUITPY_I2CSLAVE = 0 CIRCUITPY_MICROCONTROLLER = 1 diff --git a/shared-module/displayio/Display.h b/shared-module/displayio/Display.h index 8adaf597f9..861a38fd7c 100644 --- a/shared-module/displayio/Display.h +++ b/shared-module/displayio/Display.h @@ -29,7 +29,9 @@ #include "shared-bindings/digitalio/DigitalInOut.h" #include "shared-bindings/displayio/Group.h" +#if CIRCUITPY_PULSEIO #include "shared-bindings/pulseio/PWMOut.h" +#endif #include "shared-module/displayio/area.h" #include "shared-module/displayio/display_core.h" @@ -39,7 +41,9 @@ typedef struct { displayio_display_core_t core; union { digitalio_digitalinout_obj_t backlight_inout; + #if CIRCUITPY_PULSEIO pulseio_pwmout_obj_t backlight_pwm; + #endif }; uint64_t last_backlight_refresh; uint64_t last_refresh_call; diff --git a/shared-module/displayio/EPaperDisplay.h b/shared-module/displayio/EPaperDisplay.h index d08bed5462..3b9f6e3680 100644 --- a/shared-module/displayio/EPaperDisplay.h +++ b/shared-module/displayio/EPaperDisplay.h @@ -29,7 +29,6 @@ #include "shared-bindings/digitalio/DigitalInOut.h" #include "shared-bindings/displayio/Group.h" -#include "shared-bindings/pulseio/PWMOut.h" #include "shared-module/displayio/area.h" #include "shared-module/displayio/display_core.h" From 03e5043af4de14bd8115a4eeb608a2726ab59c6e Mon Sep 17 00:00:00 2001 From: Scott Shawcroft Date: Wed, 24 Jun 2020 13:10:31 -0700 Subject: [PATCH 11/22] Turn off Idle WDT and speed up CPU --- ports/esp32s2/background.c | 6 ++---- ports/esp32s2/sdkconfig.defaults | 28 ++++++++++++++++------------ ports/esp32s2/supervisor/port.c | 3 +++ 3 files changed, 21 insertions(+), 16 deletions(-) diff --git a/ports/esp32s2/background.c b/ports/esp32s2/background.c index e979d78311..a90fa7d0aa 100644 --- a/ports/esp32s2/background.c +++ b/ports/esp32s2/background.c @@ -47,10 +47,8 @@ void run_background_tasks(void) { return; } - // Delay for 1 tick so that we don't starve the idle task. - // TODO: 1 tick is 10ms which is a long time! Can we delegate to idle for a minimal amount of - // time? - vTaskDelay(1); + // Zero delay in case FreeRTOS wants to switch to something else. + vTaskDelay(0); running_background_tasks = true; filesystem_background(); diff --git a/ports/esp32s2/sdkconfig.defaults b/ports/esp32s2/sdkconfig.defaults index 958e1852ea..729ebac889 100644 --- a/ports/esp32s2/sdkconfig.defaults +++ b/ports/esp32s2/sdkconfig.defaults @@ -190,9 +190,9 @@ CONFIG_EFUSE_MAX_BLK_LEN=256 # ESP32S2-specific # # CONFIG_ESP32S2_DEFAULT_CPU_FREQ_80 is not set -CONFIG_ESP32S2_DEFAULT_CPU_FREQ_160=y -# CONFIG_ESP32S2_DEFAULT_CPU_FREQ_240 is not set -CONFIG_ESP32S2_DEFAULT_CPU_FREQ_MHZ=160 +# CONFIG_ESP32S2_DEFAULT_CPU_FREQ_160 is not set +CONFIG_ESP32S2_DEFAULT_CPU_FREQ_240=y +CONFIG_ESP32S2_DEFAULT_CPU_FREQ_MHZ=240 # # Memory protection @@ -271,10 +271,7 @@ CONFIG_ESP_CONSOLE_UART_RX_GPIO=3 CONFIG_ESP_CONSOLE_UART_BAUDRATE=115200 CONFIG_ESP_INT_WDT=y CONFIG_ESP_INT_WDT_TIMEOUT_MS=300 -CONFIG_ESP_TASK_WDT=y -# CONFIG_ESP_TASK_WDT_PANIC is not set -CONFIG_ESP_TASK_WDT_TIMEOUT_S=5 -CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU0=y +# CONFIG_ESP_TASK_WDT is not set CONFIG_ESP_MAC_ADDR_UNIVERSE_WIFI_STA=y CONFIG_ESP_MAC_ADDR_UNIVERSE_WIFI_AP=y # end of Common ESP-related @@ -528,6 +525,7 @@ CONFIG_MBEDTLS_INTERNAL_MEM_ALLOC=y CONFIG_MBEDTLS_ASYMMETRIC_CONTENT_LEN=y CONFIG_MBEDTLS_SSL_IN_CONTENT_LEN=16384 CONFIG_MBEDTLS_SSL_OUT_CONTENT_LEN=4096 +# CONFIG_MBEDTLS_DYNAMIC_BUFFER is not set # CONFIG_MBEDTLS_DEBUG is not set # @@ -547,8 +545,12 @@ CONFIG_MBEDTLS_AES_USE_INTERRUPT=y CONFIG_MBEDTLS_HARDWARE_GCM=y CONFIG_MBEDTLS_HARDWARE_MPI=y CONFIG_MBEDTLS_HARDWARE_SHA=y +# CONFIG_MBEDTLS_ATCA_HW_ECDSA_SIGN is not set +# CONFIG_MBEDTLS_ATCA_HW_ECDSA_VERIFY is not set CONFIG_MBEDTLS_HAVE_TIME=y # CONFIG_MBEDTLS_HAVE_TIME_DATE is not set +CONFIG_MBEDTLS_ECDSA_DETERMINISTIC=y +CONFIG_MBEDTLS_SHA512_C=y CONFIG_MBEDTLS_TLS_SERVER_AND_CLIENT=y # CONFIG_MBEDTLS_TLS_SERVER_ONLY is not set # CONFIG_MBEDTLS_TLS_CLIENT_ONLY is not set @@ -627,6 +629,10 @@ CONFIG_MBEDTLS_ECP_DP_BP384R1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_BP512R1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_CURVE25519_ENABLED=y CONFIG_MBEDTLS_ECP_NIST_OPTIM=y +# CONFIG_MBEDTLS_POLY1305_C is not set +# CONFIG_MBEDTLS_CHACHA20_C is not set +# CONFIG_MBEDTLS_HKDF_C is not set +# CONFIG_MBEDTLS_THREADING_C is not set # CONFIG_MBEDTLS_SECURITY_RISKS is not set # end of mbedTLS @@ -705,6 +711,7 @@ CONFIG_WPA_MBEDTLS_CRYPTO=y # CONFIG_WPA_DEBUG_PRINT is not set # CONFIG_WPA_TESTING_OPTIONS is not set # CONFIG_WPA_TLS_V12 is not set +# CONFIG_WPA_WPS_WARS is not set # end of Supplicant # end of Component config @@ -756,7 +763,7 @@ CONFIG_ESP32_APPTRACE_LOCK_ENABLE=y CONFIG_ADC2_DISABLE_DAC=y CONFIG_SYSTEM_EVENT_QUEUE_SIZE=32 CONFIG_SYSTEM_EVENT_TASK_STACK_SIZE=2304 -CONFIG_MAIN_TASK_STACK_SIZE=3584 +CONFIG_MAIN_TASK_STACK_SIZE=8192 CONFIG_IPC_TASK_STACK_SIZE=1024 CONFIG_CONSOLE_UART_DEFAULT=y # CONFIG_CONSOLE_UART_CUSTOM is not set @@ -767,10 +774,7 @@ CONFIG_CONSOLE_UART_RX_GPIO=3 CONFIG_CONSOLE_UART_BAUDRATE=115200 CONFIG_INT_WDT=y CONFIG_INT_WDT_TIMEOUT_MS=300 -CONFIG_TASK_WDT=y -# CONFIG_TASK_WDT_PANIC is not set -CONFIG_TASK_WDT_TIMEOUT_S=5 -CONFIG_TASK_WDT_CHECK_IDLE_TASK_CPU0=y +# CONFIG_TASK_WDT is not set # CONFIG_EVENT_LOOP_PROFILING is not set CONFIG_POST_EVENTS_FROM_ISR=y CONFIG_POST_EVENTS_FROM_IRAM_ISR=y diff --git a/ports/esp32s2/supervisor/port.c b/ports/esp32s2/supervisor/port.c index fbfbc9f2eb..ebf0020399 100644 --- a/ports/esp32s2/supervisor/port.c +++ b/ports/esp32s2/supervisor/port.c @@ -69,6 +69,9 @@ safe_mode_t port_init(void) { void reset_port(void) { reset_all_pins(); + // A larger delay so the idle task can run and do any IDF cleanup needed. + vTaskDelay(4); + #if CIRCUITPY_BUSIO i2c_reset(); spi_reset(); From a9f257bcd645b342bdc473e0ab2804a3c099126c Mon Sep 17 00:00:00 2001 From: Scott Shawcroft Date: Fri, 26 Jun 2020 12:32:56 -0700 Subject: [PATCH 12/22] Store host_id so that never reset works --- ports/esp32s2/common-hal/busio/SPI.c | 1 + 1 file changed, 1 insertion(+) diff --git a/ports/esp32s2/common-hal/busio/SPI.c b/ports/esp32s2/common-hal/busio/SPI.c index 686f44cbc2..60514df389 100644 --- a/ports/esp32s2/common-hal/busio/SPI.c +++ b/ports/esp32s2/common-hal/busio/SPI.c @@ -160,6 +160,7 @@ void common_hal_busio_spi_construct(busio_spi_obj_t *self, self->clock_pin = clock; self->MOSI_pin = mosi; self->MISO_pin = miso; + self->host_id = host_id; spi_bus_lock_dev_config_t config = { .flags = 0 }; // The returned lock is stored in the bus lock but must be freed separately with From 2d579cc9953a3ba965973c6d5139c007b3c1b38d Mon Sep 17 00:00:00 2001 From: Scott Shawcroft Date: Fri, 26 Jun 2020 12:33:50 -0700 Subject: [PATCH 13/22] Use NULL for deinited DigitalInOut This fixes a Display issue where no backlight pin is given but it's still deinitialized. --- ports/esp32s2/common-hal/digitalio/DigitalInOut.c | 4 ++-- ports/litex/common-hal/digitalio/DigitalInOut.c | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/ports/esp32s2/common-hal/digitalio/DigitalInOut.c b/ports/esp32s2/common-hal/digitalio/DigitalInOut.c index 7745a9c0a3..fb3ee10ad7 100644 --- a/ports/esp32s2/common-hal/digitalio/DigitalInOut.c +++ b/ports/esp32s2/common-hal/digitalio/DigitalInOut.c @@ -46,7 +46,7 @@ digitalinout_result_t common_hal_digitalio_digitalinout_construct( } bool common_hal_digitalio_digitalinout_deinited(digitalio_digitalinout_obj_t *self) { - return self->pin == mp_const_none; + return self->pin == NULL; } void common_hal_digitalio_digitalinout_deinit(digitalio_digitalinout_obj_t *self) { @@ -55,7 +55,7 @@ void common_hal_digitalio_digitalinout_deinit(digitalio_digitalinout_obj_t *self } reset_pin_number(self->pin->number); - self->pin = mp_const_none; + self->pin = NULL; } void common_hal_digitalio_digitalinout_switch_to_input( diff --git a/ports/litex/common-hal/digitalio/DigitalInOut.c b/ports/litex/common-hal/digitalio/DigitalInOut.c index 26f79f16df..53df637c43 100644 --- a/ports/litex/common-hal/digitalio/DigitalInOut.c +++ b/ports/litex/common-hal/digitalio/DigitalInOut.c @@ -46,7 +46,7 @@ digitalinout_result_t common_hal_digitalio_digitalinout_construct( } bool common_hal_digitalio_digitalinout_deinited(digitalio_digitalinout_obj_t *self) { - return self->pin == mp_const_none; + return self->pin == NULL; } void common_hal_digitalio_digitalinout_deinit(digitalio_digitalinout_obj_t *self) { @@ -55,7 +55,7 @@ void common_hal_digitalio_digitalinout_deinit(digitalio_digitalinout_obj_t *self } // reset_pin_number(0, self->pin->number); - self->pin = mp_const_none; + self->pin = NULL; } void common_hal_digitalio_digitalinout_switch_to_input( From 08749630a28527f45a01cbfa3c1db417030feacf Mon Sep 17 00:00:00 2001 From: Scott Shawcroft Date: Fri, 26 Jun 2020 16:30:24 -0700 Subject: [PATCH 14/22] Fix SPI RX and remove debug prints --- ports/esp32s2/common-hal/busio/SPI.c | 19 ++++--------------- 1 file changed, 4 insertions(+), 15 deletions(-) diff --git a/ports/esp32s2/common-hal/busio/SPI.c b/ports/esp32s2/common-hal/busio/SPI.c index 60514df389..73d7d0595e 100644 --- a/ports/esp32s2/common-hal/busio/SPI.c +++ b/ports/esp32s2/common-hal/busio/SPI.c @@ -32,10 +32,6 @@ #include "shared-bindings/microcontroller/Pin.h" #include "supervisor/shared/rgb_led_status.h" -#include "esp_log.h" - -static const char* TAG = "CircuitPython SPI"; - static bool spi_never_reset[SOC_SPI_PERIPH_NUM]; // Store one lock handle per device so that we can free it. @@ -101,8 +97,7 @@ static bool spi_bus_is_free(spi_host_device_t host_id) { } static void spi_interrupt_handler(void *arg) { - busio_spi_obj_t *self = arg; - ESP_LOGE(TAG, "SPI interrupt %p", self); + // busio_spi_obj_t *self = arg; } // The interrupt may get invoked by the bus lock. @@ -197,8 +192,8 @@ void common_hal_busio_spi_construct(busio_spi_obj_t *self, // hal->cs_hold = 0; // hal->cs_pin_id = 0; - hal->sio = 1; - // hal->half_duplex = 0; + hal->sio = 0; + hal->half_duplex = 0; // hal->tx_lsbfirst = 0; // hal->rx_lsbfirst = 0; hal->dma_enabled = 1; @@ -216,9 +211,6 @@ void common_hal_busio_spi_construct(busio_spi_obj_t *self, // This must be set after spi_hal_init. hal->timing_conf = &self->timing_conf; - if (hal->hw == NULL) { - ESP_LOGE(TAG, "SPI error %p", hal->hw); - } common_hal_busio_spi_configure(self, 250000, 0, 0, 8); } @@ -280,11 +272,7 @@ bool common_hal_busio_spi_configure(busio_spi_obj_t *self, return false; } - ESP_LOGI(TAG, "configure"); - ESP_LOGI(TAG, "real frequency %d", self->real_frequency); - ESP_LOGI(TAG, "timing_conf %p", self->hal_context.timing_conf); spi_hal_setup_device(&self->hal_context); - ESP_LOGI(TAG, "setup done"); return true; } @@ -351,6 +339,7 @@ bool common_hal_busio_spi_transfer(busio_spi_obj_t *self, const uint8_t *data_ou while (!spi_hal_usr_is_done(hal)) { RUN_BACKGROUND_TASKS; } + spi_hal_fetch_result(hal); } return true; From 7f6bef3251d295120fe8f89e666b277dc2f596b1 Mon Sep 17 00:00:00 2001 From: Scott Shawcroft Date: Fri, 26 Jun 2020 16:56:17 -0700 Subject: [PATCH 15/22] Remove debug prints --- ports/esp32s2/supervisor/internal_flash.c | 36 ++++++++--------------- ports/esp32s2/supervisor/port.c | 24 ++------------- 2 files changed, 15 insertions(+), 45 deletions(-) diff --git a/ports/esp32s2/supervisor/internal_flash.c b/ports/esp32s2/supervisor/internal_flash.c index a8d3fa485c..5cf77c8010 100644 --- a/ports/esp32s2/supervisor/internal_flash.c +++ b/ports/esp32s2/supervisor/internal_flash.c @@ -39,11 +39,6 @@ #include "esp-idf/components/spi_flash/include/esp_partition.h" -#include "esp_log.h" - - -static const char* TAG = "CircuitPython Internal Flash"; - #include "supervisor/usb.h" STATIC const esp_partition_t * _partition; @@ -52,8 +47,6 @@ void supervisor_flash_init(void) { _partition = esp_partition_find_first(ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_FAT, NULL); - - ESP_EARLY_LOGW(TAG, "fatfs partition %p", _partition); } uint32_t supervisor_flash_get_block_size(void) { @@ -74,11 +67,10 @@ STATIC uint8_t _cache[SECTOR_SIZE]; STATIC uint32_t _cache_lba; mp_uint_t supervisor_flash_read_blocks(uint8_t *dest, uint32_t block, uint32_t num_blocks) { - esp_err_t ok = esp_partition_read(_partition, - block * FILESYSTEM_BLOCK_SIZE, - dest, - num_blocks * FILESYSTEM_BLOCK_SIZE); - ESP_EARLY_LOGW(TAG, "read %d", ok); + esp_partition_read(_partition, + block * FILESYSTEM_BLOCK_SIZE, + dest, + num_blocks * FILESYSTEM_BLOCK_SIZE); return 0; } @@ -90,13 +82,11 @@ mp_uint_t supervisor_flash_write_blocks(const uint8_t *src, uint32_t lba, uint32 uint32_t sector_offset = block_address / blocks_per_sector * SECTOR_SIZE; uint8_t block_offset = block_address % blocks_per_sector; - esp_err_t result; if (_cache_lba != block_address) { - result = esp_partition_read(_partition, - sector_offset, - _cache, - SECTOR_SIZE); - ESP_EARLY_LOGW(TAG, "flash read before write %d", result); + esp_partition_read(_partition, + sector_offset, + _cache, + SECTOR_SIZE); _cache_lba = sector_offset; } for (uint8_t b = block_offset; b < blocks_per_sector; b++) { @@ -109,11 +99,11 @@ mp_uint_t supervisor_flash_write_blocks(const uint8_t *src, uint32_t lba, uint32 FILESYSTEM_BLOCK_SIZE); block++; } - result = esp_partition_erase_range(_partition, sector_offset, SECTOR_SIZE); - result = esp_partition_write(_partition, - sector_offset, - _cache, - SECTOR_SIZE); + esp_partition_erase_range(_partition, sector_offset, SECTOR_SIZE); + esp_partition_write(_partition, + sector_offset, + _cache, + SECTOR_SIZE); } return 0; // success diff --git a/ports/esp32s2/supervisor/port.c b/ports/esp32s2/supervisor/port.c index ebf0020399..a80550b309 100644 --- a/ports/esp32s2/supervisor/port.c +++ b/ports/esp32s2/supervisor/port.c @@ -41,10 +41,6 @@ #include "supervisor/memory.h" #include "supervisor/shared/tick.h" -#include "esp_log.h" - -static const char* TAG = "CircuitPython"; - STATIC esp_timer_handle_t _tick_timer; void tick_timer_cb(void* arg) { @@ -57,12 +53,8 @@ safe_mode_t port_init(void) { args.arg = NULL; args.dispatch_method = ESP_TIMER_TASK; args.name = "CircuitPython Tick"; - esp_err_t result = esp_timer_create(&args, &_tick_timer); - if (result != ESP_OK) { - ESP_EARLY_LOGE(TAG, "Unable to create tick timer."); - } + esp_timer_create(&args, &_tick_timer); never_reset_module_internal_pins(); - ESP_EARLY_LOGW(TAG, "port init done"); return NO_SAFE_MODE; } @@ -109,12 +101,8 @@ uint32_t *port_stack_get_top(void) { supervisor_allocation _fixed_stack; supervisor_allocation* port_fixed_stack(void) { - - ESP_EARLY_LOGW(TAG, "port fixed stack"); _fixed_stack.ptr = port_stack_get_limit(); - ESP_EARLY_LOGW(TAG, "got limit %p", _fixed_stack.ptr); _fixed_stack.length = (port_stack_get_top() - port_stack_get_limit()) * sizeof(uint32_t); - ESP_EARLY_LOGW(TAG, "got length %d", _fixed_stack.length); return &_fixed_stack; } @@ -139,10 +127,7 @@ uint64_t port_get_raw_ticks(uint8_t* subticks) { // Enable 1/1024 second tick. void port_enable_tick(void) { - esp_err_t result = esp_timer_start_periodic(_tick_timer, 1000000 / 1024); - if (result != ESP_OK) { - ESP_EARLY_LOGE(TAG, "Unable to start tick timer."); - } + esp_timer_start_periodic(_tick_timer, 1000000 / 1024); } // Disable 1/1024 second tick. @@ -153,14 +138,12 @@ void port_disable_tick(void) { TickType_t sleep_time_set; TickType_t sleep_time_duration; void port_interrupt_after_ticks(uint32_t ticks) { - // ESP_EARLY_LOGW(TAG, "after ticks"); sleep_time_set = xTaskGetTickCount(); sleep_time_duration = ticks / portTICK_PERIOD_MS; // esp_sleep_enable_timer_wakeup(uint64_t time_in_us) } void port_sleep_until_interrupt(void) { - // ESP_EARLY_LOGW(TAG, "sleep until"); // FreeRTOS delay here maybe. // Light sleep shuts down BLE and wifi. // esp_light_sleep_start() @@ -174,8 +157,5 @@ void port_sleep_until_interrupt(void) { // Wrap main in app_main that the IDF expects. extern void main(void); void app_main(void) { - ESP_EARLY_LOGW(TAG, "Hello from CircuitPython"); - // ESP_LOGW(TAG, "Hello from CircuitPython"); - main(); } From ceb2efcbc3b4b5e34fda51abed7bd1bfb4d5a6db Mon Sep 17 00:00:00 2001 From: Scott Shawcroft Date: Mon, 29 Jun 2020 16:34:37 -0700 Subject: [PATCH 16/22] Add new UnexpectedMaker FeatherS2 to CI. --- .github/workflows/build.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 00454cc2da..80cbc9b748 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -371,6 +371,7 @@ jobs: board: - "espressif_saola_1_wroom" - "espressif_saola_1_wrover" + - "unexpectedmaker_feathers2" steps: - name: Set up Python 3.8 From 1a0c10c328842300aca8ed5113815cfb5bf95d26 Mon Sep 17 00:00:00 2001 From: Scott Shawcroft Date: Mon, 29 Jun 2020 17:15:01 -0700 Subject: [PATCH 17/22] Fix debug UART call --- supervisor/shared/serial.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/supervisor/shared/serial.c b/supervisor/shared/serial.c index 513022667a..8eb78a90e5 100644 --- a/supervisor/shared/serial.c +++ b/supervisor/shared/serial.c @@ -55,7 +55,7 @@ void serial_early_init(void) { const mcu_pin_obj_t* tx = MP_OBJ_TO_PTR(DEBUG_UART_TX); common_hal_busio_uart_construct(&debug_uart, tx, rx, NULL, NULL, NULL, - false, 115200, 8, PARITY_NONE, 1, 1.0f, 64, + false, 115200, 8, UART_PARITY_NONE, 1, 1.0f, 64, buf_array, true); common_hal_busio_uart_never_reset(&debug_uart); #endif From 965a40b6a19a9eb35ecc4256aa850d41c88a0137 Mon Sep 17 00:00:00 2001 From: Scott Shawcroft Date: Mon, 29 Jun 2020 17:17:46 -0700 Subject: [PATCH 18/22] Fix cxd56 function signature --- ports/cxd56/common-hal/busio/SPI.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ports/cxd56/common-hal/busio/SPI.c b/ports/cxd56/common-hal/busio/SPI.c index 718a8ff16e..2d365d4826 100644 --- a/ports/cxd56/common-hal/busio/SPI.c +++ b/ports/cxd56/common-hal/busio/SPI.c @@ -130,7 +130,7 @@ bool common_hal_busio_spi_read(busio_spi_obj_t *self, uint8_t *data, size_t len, return true; } -bool common_hal_busio_spi_transfer(busio_spi_obj_t *self, uint8_t *data_out, uint8_t *data_in, size_t len) { +bool common_hal_busio_spi_transfer(busio_spi_obj_t *self, const uint8_t *data_out, uint8_t *data_in, size_t len) { SPI_EXCHANGE(self->spi_dev, data_out, data_in, len); return true; From 69b3d475647b14a87891e38fe00a525b916c5d8a Mon Sep 17 00:00:00 2001 From: Scott Shawcroft Date: Mon, 29 Jun 2020 18:21:53 -0700 Subject: [PATCH 19/22] Fix other esp builds --- .../boards/espressif_saola_1_wroom/board.c | 8 +++---- .../boards/unexpectedmaker_feathers2/board.c | 22 +++++++++---------- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/ports/esp32s2/boards/espressif_saola_1_wroom/board.c b/ports/esp32s2/boards/espressif_saola_1_wroom/board.c index b7b2c4ef5b..9f708874bf 100644 --- a/ports/esp32s2/boards/espressif_saola_1_wroom/board.c +++ b/ports/esp32s2/boards/espressif_saola_1_wroom/board.c @@ -30,12 +30,12 @@ void board_init(void) { // USB - never_reset_pin(&pin_GPIO19); - never_reset_pin(&pin_GPIO20); + common_hal_never_reset_pin(&pin_GPIO19); + common_hal_never_reset_pin(&pin_GPIO20); // Debug UART - never_reset_pin(&pin_GPIO43); - never_reset_pin(&pin_GPIO44); + common_hal_never_reset_pin(&pin_GPIO43); + common_hal_never_reset_pin(&pin_GPIO44); } bool board_requests_safe_mode(void) { diff --git a/ports/esp32s2/boards/unexpectedmaker_feathers2/board.c b/ports/esp32s2/boards/unexpectedmaker_feathers2/board.c index 8890ec4c16..1dc30b5af8 100644 --- a/ports/esp32s2/boards/unexpectedmaker_feathers2/board.c +++ b/ports/esp32s2/boards/unexpectedmaker_feathers2/board.c @@ -30,21 +30,21 @@ void board_init(void) { // USB - never_reset_pin(&pin_GPIO19); - never_reset_pin(&pin_GPIO20); + common_hal_never_reset_pin(&pin_GPIO19); + common_hal_never_reset_pin(&pin_GPIO20); // Debug UART - never_reset_pin(&pin_GPIO43); - never_reset_pin(&pin_GPIO44); + common_hal_never_reset_pin(&pin_GPIO43); + common_hal_never_reset_pin(&pin_GPIO44); // SPI Flash and RAM - never_reset_pin(&pin_GPIO26); - never_reset_pin(&pin_GPIO27); - never_reset_pin(&pin_GPIO28); - never_reset_pin(&pin_GPIO29); - never_reset_pin(&pin_GPIO30); - never_reset_pin(&pin_GPIO31); - never_reset_pin(&pin_GPIO32); + common_hal_never_reset_pin(&pin_GPIO26); + common_hal_never_reset_pin(&pin_GPIO27); + common_hal_never_reset_pin(&pin_GPIO28); + common_hal_never_reset_pin(&pin_GPIO29); + common_hal_never_reset_pin(&pin_GPIO30); + common_hal_never_reset_pin(&pin_GPIO31); + common_hal_never_reset_pin(&pin_GPIO32); } bool board_requests_safe_mode(void) { From 5028804878addc988548b91d173b5fb88380435f Mon Sep 17 00:00:00 2001 From: Scott Shawcroft Date: Tue, 30 Jun 2020 15:29:42 -0700 Subject: [PATCH 20/22] Remove fixed pointers and check UART return --- ports/esp32s2/common-hal/busio/I2C.c | 10 ++++++---- ports/esp32s2/common-hal/busio/I2C.h | 1 - ports/esp32s2/common-hal/busio/SPI.c | 6 +++--- ports/esp32s2/common-hal/busio/UART.c | 3 +++ 4 files changed, 12 insertions(+), 8 deletions(-) diff --git a/ports/esp32s2/common-hal/busio/I2C.c b/ports/esp32s2/common-hal/busio/I2C.c index 391d7323c5..74b3896fc2 100644 --- a/ports/esp32s2/common-hal/busio/I2C.c +++ b/ports/esp32s2/common-hal/busio/I2C.c @@ -90,8 +90,10 @@ void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, #endif - self->semaphore_handle = xSemaphoreCreateBinaryStatic(&self->semaphore); - xSemaphoreGive(self->semaphore_handle); + if (xSemaphoreCreateBinaryStatic(&self->semaphore) != &self->semaphore) { + mp_raise_RuntimeError(translate("Unable to create lock")); + } + xSemaphoreGive(&self->semaphore); self->sda_pin = sda; self->scl_pin = scl; self->i2c_num = I2C_NUM_MAX; @@ -161,7 +163,7 @@ bool common_hal_busio_i2c_probe(busio_i2c_obj_t *self, uint8_t addr) { } bool common_hal_busio_i2c_try_lock(busio_i2c_obj_t *self) { - self->has_lock = xSemaphoreTake(self->semaphore_handle, 0) == pdTRUE; + self->has_lock = xSemaphoreTake(&self->semaphore, 0) == pdTRUE; return self->has_lock; } @@ -170,7 +172,7 @@ bool common_hal_busio_i2c_has_lock(busio_i2c_obj_t *self) { } void common_hal_busio_i2c_unlock(busio_i2c_obj_t *self) { - xSemaphoreGive(self->semaphore_handle); + xSemaphoreGive(&self->semaphore); self->has_lock = false; } diff --git a/ports/esp32s2/common-hal/busio/I2C.h b/ports/esp32s2/common-hal/busio/I2C.h index d90fb2713a..24a3fd4951 100644 --- a/ports/esp32s2/common-hal/busio/I2C.h +++ b/ports/esp32s2/common-hal/busio/I2C.h @@ -40,7 +40,6 @@ typedef struct { const mcu_pin_obj_t* sda_pin; i2c_port_t i2c_num; StaticSemaphore_t semaphore; - SemaphoreHandle_t semaphore_handle; bool has_lock; } busio_i2c_obj_t; diff --git a/ports/esp32s2/common-hal/busio/SPI.c b/ports/esp32s2/common-hal/busio/SPI.c index 73d7d0595e..a22075cd59 100644 --- a/ports/esp32s2/common-hal/busio/SPI.c +++ b/ports/esp32s2/common-hal/busio/SPI.c @@ -209,9 +209,6 @@ void common_hal_busio_spi_construct(busio_spi_obj_t *self, hal->io_mode = SPI_LL_IO_MODE_NORMAL; - // This must be set after spi_hal_init. - hal->timing_conf = &self->timing_conf; - common_hal_busio_spi_configure(self, 250000, 0, 0, 8); } @@ -261,6 +258,7 @@ bool common_hal_busio_spi_configure(busio_spi_obj_t *self, self->phase = phase; self->bits = bits; self->target_frequency = baudrate; + self->hal_context.timing_conf = &self->timing_conf; esp_err_t result = spi_hal_get_clock_conf(&self->hal_context, self->target_frequency, 128 /* duty_cycle */, @@ -315,6 +313,8 @@ bool common_hal_busio_spi_transfer(busio_spi_obj_t *self, const uint8_t *data_ou spi_hal_context_t* hal = &self->hal_context; hal->send_buffer = NULL; hal->rcv_buffer = NULL; + // Reset timing_conf in case we've moved since the last time we used it. + hal->timing_conf = &self->timing_conf; // This rounds up. size_t dma_count = (len + LLDESC_MAX_NUM_PER_DESC - 1) / LLDESC_MAX_NUM_PER_DESC; for (size_t i = 0; i < dma_count; i++) { diff --git a/ports/esp32s2/common-hal/busio/UART.c b/ports/esp32s2/common-hal/busio/UART.c index f73f5c993d..b0162adba9 100644 --- a/ports/esp32s2/common-hal/busio/UART.c +++ b/ports/esp32s2/common-hal/busio/UART.c @@ -249,6 +249,9 @@ size_t common_hal_busio_uart_read(busio_uart_obj_t *self, uint8_t *data, size_t while (supervisor_ticks_ms64() - start_ticks <= self->timeout_ms) { // Read as many chars as we can right now, up to len. size_t num_read = uart_read_bytes(self->uart_num, data, len, 0); + if (num_read < 0) { + break; + } // Advance pointer in data buffer, and decrease how many chars left to read. data += num_read; From c3d1256d765a7de12d787c2641017de25dbde7d0 Mon Sep 17 00:00:00 2001 From: Scott Shawcroft Date: Tue, 30 Jun 2020 15:30:07 -0700 Subject: [PATCH 21/22] Add one-of-each build target at the top level. --- Makefile | 53 +++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 45 insertions(+), 8 deletions(-) diff --git a/Makefile b/Makefile index 0df1950938..d45dae8b90 100644 --- a/Makefile +++ b/Makefile @@ -244,11 +244,48 @@ update-frozen-libraries: @echo "Updating all frozen libraries to latest tagged version." cd frozen; for library in *; do cd $$library; ../../tools/git-checkout-latest-tag.sh; cd ..; done -one-of-each: all-source - make -C ports/atmel-samd BOARD=trinket_m0 - make -C ports/atmel-samd BOARD=feather_m4_express - make -C ports/esp32s2 BOARD=espressif_saola_1_wroom - make -C ports/litex BOARD=fomu - make -C ports/mimxrt10xx BOARD=feather_mimxrt1011 - make -C ports/nrf BOARD=feather_nrf52840_express - make -C ports/stm BOARD=feather_stm32f405_express +one-of-each: samd21 samd51 esp32s2 litex mimxrt10xx nrf stm + +samd21: + $(MAKE) -C ports/atmel-samd BOARD=trinket_m0 + +samd51: + $(MAKE) -C ports/atmel-samd BOARD=feather_m4_express + +esp32s2: + $(MAKE) -C ports/esp32s2 BOARD=espressif_saola_1_wroom + +litex: + $(MAKE) -C ports/litex BOARD=fomu + +mimxrt10xx: + $(MAKE) -C ports/mimxrt10xx BOARD=feather_mimxrt1011 + +nrf: + $(MAKE) -C ports/nrf BOARD=feather_nrf52840_express + +stm: + $(MAKE) -C ports/stm BOARD=feather_stm32f405_express + +clean-one-of-each: clean-samd21 clean-samd51 clean-esp32s2 clean-litex clean-mimxrt10xx clean-nrf clean-stm + +clean-samd21: + $(MAKE) -C ports/atmel-samd BOARD=trinket_m0 clean + +clean-samd51: + $(MAKE) -C ports/atmel-samd BOARD=feather_m4_express clean + +clean-esp32s2: + $(MAKE) -C ports/esp32s2 BOARD=espressif_saola_1_wroom clean + +clean-litex: + $(MAKE) -C ports/litex BOARD=fomu clean + +clean-mimxrt10xx: + $(MAKE) -C ports/mimxrt10xx BOARD=feather_mimxrt1011 clean + +clean-nrf: + $(MAKE) -C ports/nrf BOARD=feather_nrf52840_express clean + +clean-stm: + $(MAKE) -C ports/stm BOARD=feather_stm32f405_express clean From 367d3800fc501bfe3ec05b4b517ed195cf8d07c4 Mon Sep 17 00:00:00 2001 From: Scott Shawcroft Date: Wed, 1 Jul 2020 14:35:25 -0700 Subject: [PATCH 22/22] Return false if we already have the lock --- ports/esp32s2/common-hal/busio/I2C.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/ports/esp32s2/common-hal/busio/I2C.c b/ports/esp32s2/common-hal/busio/I2C.c index 74b3896fc2..57270372f1 100644 --- a/ports/esp32s2/common-hal/busio/I2C.c +++ b/ports/esp32s2/common-hal/busio/I2C.c @@ -163,6 +163,9 @@ bool common_hal_busio_i2c_probe(busio_i2c_obj_t *self, uint8_t addr) { } bool common_hal_busio_i2c_try_lock(busio_i2c_obj_t *self) { + if (self->has_lock) { + return false; + } self->has_lock = xSemaphoreTake(&self->semaphore, 0) == pdTRUE; return self->has_lock; }