diff --git a/.github/workflows/upload-idf-component.yml b/.github/workflows/upload-idf-component.yml new file mode 100644 index 00000000000..d9e4032df08 --- /dev/null +++ b/.github/workflows/upload-idf-component.yml @@ -0,0 +1,19 @@ +name: Push components to https://components.espressif.com +on: + push: + tags: + - v* +jobs: + upload_components: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + with: + submodules: "recursive" + + - name: Upload components to the component registry + uses: espressif/github-actions/upload_components@master + with: + name: arduino-esp32 + namespace: espressif + api_token: ${{ secrets.IDF_COMPONENT_API_TOKEN }} diff --git a/CMakeLists.txt b/CMakeLists.txt index ae3f956bee7..629ac58345d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -86,6 +86,7 @@ set(LIBRARY_SRCS libraries/HTTPClient/src/HTTPClient.cpp libraries/HTTPUpdate/src/HTTPUpdate.cpp libraries/LittleFS/src/LittleFS.cpp + libraries/I2S/src/I2S.cpp libraries/NetBIOS/src/NetBIOS.cpp libraries/Preferences/src/Preferences.cpp libraries/RainMaker/src/RMaker.cpp @@ -162,7 +163,6 @@ set(BLE_SRCS libraries/BLE/src/GeneralUtils.cpp ) - set(includedirs variants/${IDF_TARGET}/ cores/esp32/ @@ -179,6 +179,7 @@ set(includedirs libraries/HTTPClient/src libraries/HTTPUpdate/src libraries/LittleFS/src + libraries/I2S/src libraries/NetBIOS/src libraries/Preferences/src libraries/RainMaker/src @@ -234,6 +235,8 @@ function(maybe_add_component component_name) endif() endfunction() +maybe_add_component(esp-dsp) + if(IDF_TARGET MATCHES "esp32" AND CONFIG_ESP_RMAKER_TASK_STACK) maybe_add_component(esp_rainmaker) maybe_add_component(qrcode) diff --git a/boards.txt b/boards.txt index cb46b3fbc3a..db5eb8378b7 100755 --- a/boards.txt +++ b/boards.txt @@ -5943,6 +5943,284 @@ adafruit_qtpy_esp32s2.menu.DebugLevel.debug.build.code_debug=4 adafruit_qtpy_esp32s2.menu.DebugLevel.verbose=Verbose adafruit_qtpy_esp32s2.menu.DebugLevel.verbose.build.code_debug=5 +############################################################## + +adafruit_qtpy_esp32c3.name=Adafruit QT Py ESP32-C3 +adafruit_qtpy_esp32c3.vid.0=0x303a +adafruit_qtpy_esp32c3.pid.0=0x1001 + +adafruit_qtpy_esp32c3.upload.tool=esptool_py +adafruit_qtpy_esp32c3.upload.maximum_size=1310720 +adafruit_qtpy_esp32c3.upload.maximum_data_size=327680 +adafruit_qtpy_esp32c3.upload.flags= +adafruit_qtpy_esp32c3.upload.extra_flags= +adafruit_qtpy_esp32c3.upload.use_1200bps_touch=false +adafruit_qtpy_esp32c3.upload.wait_for_upload_port=false + +adafruit_qtpy_esp32c3.serial.disableDTR=false +adafruit_qtpy_esp32c3.serial.disableRTS=false + +adafruit_qtpy_esp32c3.build.tarch=riscv32 +adafruit_qtpy_esp32c3.build.target=esp +adafruit_qtpy_esp32c3.build.mcu=esp32c3 +adafruit_qtpy_esp32c3.build.core=esp32 +adafruit_qtpy_esp32c3.build.variant=adafruit_qtpy_esp32c3 +adafruit_qtpy_esp32c3.build.board=ADAFRUIT_QTPY_ESP32C3 +adafruit_qtpy_esp32c3.build.bootloader_addr=0x0 + +adafruit_qtpy_esp32c3.build.cdc_on_boot=0 +adafruit_qtpy_esp32c3.build.f_cpu=160000000L +adafruit_qtpy_esp32c3.build.flash_size=4MB +adafruit_qtpy_esp32c3.build.flash_freq=80m +adafruit_qtpy_esp32c3.build.flash_mode=dout +adafruit_qtpy_esp32c3.build.boot=dout +adafruit_qtpy_esp32c3.build.partitions=default +adafruit_qtpy_esp32c3.build.defines= + +adafruit_qtpy_esp32c3.menu.CDCOnBoot.cdc=Enabled +adafruit_qtpy_esp32c3.menu.CDCOnBoot.cdc.build.cdc_on_boot=1 +adafruit_qtpy_esp32c3.menu.CDCOnBoot.default=Disabled +adafruit_qtpy_esp32c3.menu.CDCOnBoot.default.build.cdc_on_boot=0 + +adafruit_qtpy_esp32c3.menu.PartitionScheme.default=Default 4MB with spiffs (1.2MB APP/1.5MB SPIFFS) +adafruit_qtpy_esp32c3.menu.PartitionScheme.default.build.partitions=default +adafruit_qtpy_esp32c3.menu.PartitionScheme.defaultffat=Default 4MB with ffat (1.2MB APP/1.5MB FATFS) +adafruit_qtpy_esp32c3.menu.PartitionScheme.defaultffat.build.partitions=default_ffat +adafruit_qtpy_esp32c3.menu.PartitionScheme.minimal=Minimal (1.3MB APP/700KB SPIFFS) +adafruit_qtpy_esp32c3.menu.PartitionScheme.minimal.build.partitions=minimal +adafruit_qtpy_esp32c3.menu.PartitionScheme.no_ota=No OTA (2MB APP/2MB SPIFFS) +adafruit_qtpy_esp32c3.menu.PartitionScheme.no_ota.build.partitions=no_ota +adafruit_qtpy_esp32c3.menu.PartitionScheme.no_ota.upload.maximum_size=2097152 +adafruit_qtpy_esp32c3.menu.PartitionScheme.noota_3g=No OTA (1MB APP/3MB SPIFFS) +adafruit_qtpy_esp32c3.menu.PartitionScheme.noota_3g.build.partitions=noota_3g +adafruit_qtpy_esp32c3.menu.PartitionScheme.noota_3g.upload.maximum_size=1048576 +adafruit_qtpy_esp32c3.menu.PartitionScheme.noota_ffat=No OTA (2MB APP/2MB FATFS) +adafruit_qtpy_esp32c3.menu.PartitionScheme.noota_ffat.build.partitions=noota_ffat +adafruit_qtpy_esp32c3.menu.PartitionScheme.noota_ffat.upload.maximum_size=2097152 +adafruit_qtpy_esp32c3.menu.PartitionScheme.noota_3gffat=No OTA (1MB APP/3MB FATFS) +adafruit_qtpy_esp32c3.menu.PartitionScheme.noota_3gffat.build.partitions=noota_3gffat +adafruit_qtpy_esp32c3.menu.PartitionScheme.noota_3gffat.upload.maximum_size=1048576 +adafruit_qtpy_esp32c3.menu.PartitionScheme.huge_app=Huge APP (3MB No OTA/1MB SPIFFS) +adafruit_qtpy_esp32c3.menu.PartitionScheme.huge_app.build.partitions=huge_app +adafruit_qtpy_esp32c3.menu.PartitionScheme.huge_app.upload.maximum_size=3145728 +adafruit_qtpy_esp32c3.menu.PartitionScheme.min_spiffs=Minimal SPIFFS (1.9MB APP with OTA/190KB SPIFFS) +adafruit_qtpy_esp32c3.menu.PartitionScheme.min_spiffs.build.partitions=min_spiffs +adafruit_qtpy_esp32c3.menu.PartitionScheme.min_spiffs.upload.maximum_size=1966080 + +adafruit_qtpy_esp32c3.menu.CPUFreq.160=160MHz (WiFi) +adafruit_qtpy_esp32c3.menu.CPUFreq.160.build.f_cpu=160000000L +adafruit_qtpy_esp32c3.menu.CPUFreq.80=80MHz (WiFi) +adafruit_qtpy_esp32c3.menu.CPUFreq.80.build.f_cpu=80000000L +adafruit_qtpy_esp32c3.menu.CPUFreq.40=40MHz +adafruit_qtpy_esp32c3.menu.CPUFreq.40.build.f_cpu=40000000L +adafruit_qtpy_esp32c3.menu.CPUFreq.20=20MHz +adafruit_qtpy_esp32c3.menu.CPUFreq.20.build.f_cpu=20000000L +adafruit_qtpy_esp32c3.menu.CPUFreq.10=10MHz +adafruit_qtpy_esp32c3.menu.CPUFreq.10.build.f_cpu=10000000L + +adafruit_qtpy_esp32c3.menu.FlashMode.dout=DOUT +adafruit_qtpy_esp32c3.menu.FlashMode.dout.build.flash_mode=dout +adafruit_qtpy_esp32c3.menu.FlashMode.dout.build.boot=dout +adafruit_qtpy_esp32c3.menu.FlashMode.qio=QIO +adafruit_qtpy_esp32c3.menu.FlashMode.qio.build.flash_mode=dio +adafruit_qtpy_esp32c3.menu.FlashMode.qio.build.boot=qio +adafruit_qtpy_esp32c3.menu.FlashMode.dio=DIO +adafruit_qtpy_esp32c3.menu.FlashMode.dio.build.flash_mode=dio +adafruit_qtpy_esp32c3.menu.FlashMode.dio.build.boot=dio +adafruit_qtpy_esp32c3.menu.FlashMode.qout=QOUT +adafruit_qtpy_esp32c3.menu.FlashMode.qout.build.flash_mode=dout +adafruit_qtpy_esp32c3.menu.FlashMode.qout.build.boot=qout + +adafruit_qtpy_esp32c3.menu.FlashFreq.80=80MHz +adafruit_qtpy_esp32c3.menu.FlashFreq.80.build.flash_freq=80m +adafruit_qtpy_esp32c3.menu.FlashFreq.40=40MHz +adafruit_qtpy_esp32c3.menu.FlashFreq.40.build.flash_freq=40m + +adafruit_qtpy_esp32c3.menu.FlashSize.4M=4MB (32Mb) +adafruit_qtpy_esp32c3.menu.FlashSize.4M.build.flash_size=4MB +adafruit_qtpy_esp32c3.menu.FlashSize.2M=2MB (16Mb) +adafruit_qtpy_esp32c3.menu.FlashSize.2M.build.flash_size=2MB +adafruit_qtpy_esp32c3.menu.FlashSize.2M.build.partitions=minimal + +adafruit_qtpy_esp32c3.menu.UploadSpeed.115200=115200 +adafruit_qtpy_esp32c3.menu.UploadSpeed.115200.upload.speed=115200 +adafruit_qtpy_esp32c3.menu.UploadSpeed.921600=921600 +adafruit_qtpy_esp32c3.menu.UploadSpeed.921600.upload.speed=921600 +adafruit_qtpy_esp32c3.menu.UploadSpeed.921600=921600 +adafruit_qtpy_esp32c3.menu.UploadSpeed.921600.upload.speed=921600 +adafruit_qtpy_esp32c3.menu.UploadSpeed.115200=115200 +adafruit_qtpy_esp32c3.menu.UploadSpeed.115200.upload.speed=115200 +adafruit_qtpy_esp32c3.menu.UploadSpeed.256000.windows=256000 +adafruit_qtpy_esp32c3.menu.UploadSpeed.256000.upload.speed=256000 +adafruit_qtpy_esp32c3.menu.UploadSpeed.230400.windows.upload.speed=256000 +adafruit_qtpy_esp32c3.menu.UploadSpeed.230400=230400 +adafruit_qtpy_esp32c3.menu.UploadSpeed.230400.upload.speed=230400 +adafruit_qtpy_esp32c3.menu.UploadSpeed.460800.linux=460800 +adafruit_qtpy_esp32c3.menu.UploadSpeed.460800.macosx=460800 +adafruit_qtpy_esp32c3.menu.UploadSpeed.460800.upload.speed=460800 +adafruit_qtpy_esp32c3.menu.UploadSpeed.512000.windows=512000 +adafruit_qtpy_esp32c3.menu.UploadSpeed.512000.upload.speed=512000 + +adafruit_qtpy_esp32c3.menu.DebugLevel.none=None +adafruit_qtpy_esp32c3.menu.DebugLevel.none.build.code_debug=0 +adafruit_qtpy_esp32c3.menu.DebugLevel.error=Error +adafruit_qtpy_esp32c3.menu.DebugLevel.error.build.code_debug=1 +adafruit_qtpy_esp32c3.menu.DebugLevel.warn=Warn +adafruit_qtpy_esp32c3.menu.DebugLevel.warn.build.code_debug=2 +adafruit_qtpy_esp32c3.menu.DebugLevel.info=Info +adafruit_qtpy_esp32c3.menu.DebugLevel.info.build.code_debug=3 +adafruit_qtpy_esp32c3.menu.DebugLevel.debug=Debug +adafruit_qtpy_esp32c3.menu.DebugLevel.debug.build.code_debug=4 +adafruit_qtpy_esp32c3.menu.DebugLevel.verbose=Verbose +adafruit_qtpy_esp32c3.menu.DebugLevel.verbose.build.code_debug=5 + + +adafruit_qtpy_esp32_pico.name=Adafruit QT Py ESP32 Pico + +adafruit_qtpy_esp32_pico.upload.tool=esptool_py +adafruit_qtpy_esp32_pico.upload.maximum_size=1310720 +adafruit_qtpy_esp32_pico.upload.maximum_data_size=327680 +adafruit_qtpy_esp32_pico.upload.flags= +adafruit_qtpy_esp32_pico.upload.extra_flags= + +adafruit_qtpy_esp32_pico.serial.disableDTR=true +adafruit_qtpy_esp32_pico.serial.disableRTS=true + +adafruit_qtpy_esp32_pico.build.tarch=xtensa +adafruit_qtpy_esp32_pico.build.bootloader_addr=0x1000 +adafruit_qtpy_esp32_pico.build.target=esp32 +adafruit_qtpy_esp32_pico.build.mcu=esp32 +adafruit_qtpy_esp32_pico.build.core=esp32 +adafruit_qtpy_esp32_pico.build.variant=adafruit_qtpy_esp32 +adafruit_qtpy_esp32_pico.build.board=ADAFRUIT_QTPY_ESP32_PICO + +adafruit_qtpy_esp32_pico.build.f_cpu=240000000L +adafruit_qtpy_esp32_pico.build.flash_size=8MB +adafruit_qtpy_esp32_pico.build.flash_freq=80m +adafruit_qtpy_esp32_pico.build.flash_mode=dio +adafruit_qtpy_esp32_pico.build.boot=dio +adafruit_qtpy_esp32_pico.build.partitions=default +adafruit_qtpy_esp32_pico.build.defines= + +adafruit_qtpy_esp32_pico.menu.PartitionScheme.default=Default +adafruit_qtpy_esp32_pico.menu.PartitionScheme.default.build.partitions=default +adafruit_qtpy_esp32_pico.menu.PartitionScheme.no_ota=No OTA (Large APP) +adafruit_qtpy_esp32_pico.menu.PartitionScheme.no_ota.build.partitions=no_ota +adafruit_qtpy_esp32_pico.menu.PartitionScheme.no_ota.upload.maximum_size=2097152 +adafruit_qtpy_esp32_pico.menu.PartitionScheme.min_spiffs=Minimal SPIFFS (Large APPS with OTA) +adafruit_qtpy_esp32_pico.menu.PartitionScheme.min_spiffs.build.partitions=min_spiffs +adafruit_qtpy_esp32_pico.menu.PartitionScheme.min_spiffs.upload.maximum_size=1966080 + +adafruit_qtpy_esp32_pico.menu.UploadSpeed.921600=921600 +adafruit_qtpy_esp32_pico.menu.UploadSpeed.921600.upload.speed=921600 +adafruit_qtpy_esp32_pico.menu.UploadSpeed.115200=115200 +adafruit_qtpy_esp32_pico.menu.UploadSpeed.115200.upload.speed=115200 +adafruit_qtpy_esp32_pico.menu.UploadSpeed.256000.windows=256000 +adafruit_qtpy_esp32_pico.menu.UploadSpeed.256000.upload.speed=256000 +adafruit_qtpy_esp32_pico.menu.UploadSpeed.230400.windows.upload.speed=256000 +adafruit_qtpy_esp32_pico.menu.UploadSpeed.230400=230400 +adafruit_qtpy_esp32_pico.menu.UploadSpeed.230400.upload.speed=230400 +adafruit_qtpy_esp32_pico.menu.UploadSpeed.460800.linux=460800 +adafruit_qtpy_esp32_pico.menu.UploadSpeed.460800.macosx=460800 +adafruit_qtpy_esp32_pico.menu.UploadSpeed.460800.upload.speed=460800 +adafruit_qtpy_esp32_pico.menu.UploadSpeed.512000.windows=512000 +adafruit_qtpy_esp32_pico.menu.UploadSpeed.512000.upload.speed=512000 + +adafruit_qtpy_esp32_pico.menu.PSRAM.enabled=Enabled +adafruit_qtpy_esp32_pico.menu.PSRAM.enabled.build.defines=-DBOARD_HAS_PSRAM -mfix-esp32-psram-cache-issue -mfix-esp32-psram-cache-strategy=memw +adafruit_qtpy_esp32_pico.menu.PSRAM.enabled.build.extra_libs= +adafruit_qtpy_esp32_pico.menu.PSRAM.disabled=Disabled +adafruit_qtpy_esp32_pico.menu.PSRAM.disabled.build.defines= +adafruit_qtpy_esp32_pico.menu.PSRAM.disabled.build.extra_libs= + +adafruit_qtpy_esp32_pico.menu.DebugLevel.none=None +adafruit_qtpy_esp32_pico.menu.DebugLevel.none.build.code_debug=0 +adafruit_qtpy_esp32_pico.menu.DebugLevel.error=Error +adafruit_qtpy_esp32_pico.menu.DebugLevel.error.build.code_debug=1 +adafruit_qtpy_esp32_pico.menu.DebugLevel.warn=Warn +adafruit_qtpy_esp32_pico.menu.DebugLevel.warn.build.code_debug=2 +adafruit_qtpy_esp32_pico.menu.DebugLevel.info=Info +adafruit_qtpy_esp32_pico.menu.DebugLevel.info.build.code_debug=3 +adafruit_qtpy_esp32_pico.menu.DebugLevel.debug=Debug +adafruit_qtpy_esp32_pico.menu.DebugLevel.debug.build.code_debug=4 +adafruit_qtpy_esp32_pico.menu.DebugLevel.verbose=Verbose +adafruit_qtpy_esp32_pico.menu.DebugLevel.verbose.build.code_debug=5 + + + +adafruit_feather_esp32_v2.name=Adafruit Feather ESP32 V2 + +adafruit_feather_esp32_v2.upload.tool=esptool_py +adafruit_feather_esp32_v2.upload.maximum_size=1310720 +adafruit_feather_esp32_v2.upload.maximum_data_size=327680 +adafruit_feather_esp32_v2.upload.flags= +adafruit_feather_esp32_v2.upload.extra_flags= + +adafruit_feather_esp32_v2.serial.disableDTR=true +adafruit_feather_esp32_v2.serial.disableRTS=true + +adafruit_feather_esp32_v2.build.tarch=xtensa +adafruit_feather_esp32_v2.build.bootloader_addr=0x1000 +adafruit_feather_esp32_v2.build.target=esp32 +adafruit_feather_esp32_v2.build.mcu=esp32 +adafruit_feather_esp32_v2.build.core=esp32 +adafruit_feather_esp32_v2.build.variant=adafruit_feather_esp32_v2 +adafruit_feather_esp32_v2.build.board=ADAFRUIT_FEATHER_ESP32_V2 + +adafruit_feather_esp32_v2.build.f_cpu=240000000L +adafruit_feather_esp32_v2.build.flash_size=8MB +adafruit_feather_esp32_v2.build.flash_freq=80m +adafruit_feather_esp32_v2.build.flash_mode=dio +adafruit_feather_esp32_v2.build.boot=dio +adafruit_feather_esp32_v2.build.partitions=default +adafruit_feather_esp32_v2.build.defines= + +adafruit_feather_esp32_v2.menu.PartitionScheme.default=Default +adafruit_feather_esp32_v2.menu.PartitionScheme.default.build.partitions=default +adafruit_feather_esp32_v2.menu.PartitionScheme.no_ota=No OTA (Large APP) +adafruit_feather_esp32_v2.menu.PartitionScheme.no_ota.build.partitions=no_ota +adafruit_feather_esp32_v2.menu.PartitionScheme.no_ota.upload.maximum_size=2097152 +adafruit_feather_esp32_v2.menu.PartitionScheme.min_spiffs=Minimal SPIFFS (Large APPS with OTA) +adafruit_feather_esp32_v2.menu.PartitionScheme.min_spiffs.build.partitions=min_spiffs +adafruit_feather_esp32_v2.menu.PartitionScheme.min_spiffs.upload.maximum_size=1966080 + +adafruit_feather_esp32_v2.menu.UploadSpeed.921600=921600 +adafruit_feather_esp32_v2.menu.UploadSpeed.921600.upload.speed=921600 +adafruit_feather_esp32_v2.menu.UploadSpeed.115200=115200 +adafruit_feather_esp32_v2.menu.UploadSpeed.115200.upload.speed=115200 +adafruit_feather_esp32_v2.menu.UploadSpeed.256000.windows=256000 +adafruit_feather_esp32_v2.menu.UploadSpeed.256000.upload.speed=256000 +adafruit_feather_esp32_v2.menu.UploadSpeed.230400.windows.upload.speed=256000 +adafruit_feather_esp32_v2.menu.UploadSpeed.230400=230400 +adafruit_feather_esp32_v2.menu.UploadSpeed.230400.upload.speed=230400 +adafruit_feather_esp32_v2.menu.UploadSpeed.460800.linux=460800 +adafruit_feather_esp32_v2.menu.UploadSpeed.460800.macosx=460800 +adafruit_feather_esp32_v2.menu.UploadSpeed.460800.upload.speed=460800 +adafruit_feather_esp32_v2.menu.UploadSpeed.512000.windows=512000 +adafruit_feather_esp32_v2.menu.UploadSpeed.512000.upload.speed=512000 + +adafruit_feather_esp32_v2.menu.PSRAM.enabled=Enabled +adafruit_feather_esp32_v2.menu.PSRAM.enabled.build.defines=-DBOARD_HAS_PSRAM -mfix-esp32-psram-cache-issue -mfix-esp32-psram-cache-strategy=memw +adafruit_feather_esp32_v2.menu.PSRAM.enabled.build.extra_libs= +adafruit_feather_esp32_v2.menu.PSRAM.disabled=Disabled +adafruit_feather_esp32_v2.menu.PSRAM.disabled.build.defines= +adafruit_feather_esp32_v2.menu.PSRAM.disabled.build.extra_libs= + +adafruit_feather_esp32_v2.menu.DebugLevel.none=None +adafruit_feather_esp32_v2.menu.DebugLevel.none.build.code_debug=0 +adafruit_feather_esp32_v2.menu.DebugLevel.error=Error +adafruit_feather_esp32_v2.menu.DebugLevel.error.build.code_debug=1 +adafruit_feather_esp32_v2.menu.DebugLevel.warn=Warn +adafruit_feather_esp32_v2.menu.DebugLevel.warn.build.code_debug=2 +adafruit_feather_esp32_v2.menu.DebugLevel.info=Info +adafruit_feather_esp32_v2.menu.DebugLevel.info.build.code_debug=3 +adafruit_feather_esp32_v2.menu.DebugLevel.debug=Debug +adafruit_feather_esp32_v2.menu.DebugLevel.debug.build.code_debug=4 +adafruit_feather_esp32_v2.menu.DebugLevel.verbose=Verbose +adafruit_feather_esp32_v2.menu.DebugLevel.verbose.build.code_debug=5 + + + ############################################################## nodemcu-32s.name=NodeMCU-32S diff --git a/cores/esp32/WString.cpp b/cores/esp32/WString.cpp index 4badf63d0fe..f69302a253f 100644 --- a/cores/esp32/WString.cpp +++ b/cores/esp32/WString.cpp @@ -774,9 +774,10 @@ void String::replace(const String& find, const String& replace) { } if(size == len()) return; - if(size > capacity() && !changeBuffer(size)) + if(size > capacity() && !changeBuffer(size)) { log_w("String.Replace() Insufficient space to replace string"); return; + } int index = len() - 1; while(index >= 0 && (index = lastIndexOf(find, index)) >= 0) { readFrom = wbuffer() + index + find.len(); diff --git a/docs/source/api/i2s.rst b/docs/source/api/i2s.rst new file mode 100644 index 00000000000..02539fb3f2b --- /dev/null +++ b/docs/source/api/i2s.rst @@ -0,0 +1,566 @@ +### +I2S +### + +About +----- + +I2S - Inter-IC Sound, correctly written I²S pronounced "eye-squared-ess", alternative notation is IIS. I²S is an electrical serial bus interface standard used for connecting digital audio devices together. + +It is used to communicate PCM (Pulse-Code Modulation) audio data between integrated circuits in an electronic device. The I²S bus separates clock and serial data signals, resulting in simpler receivers than those required for asynchronous communications systems that need to recover the clock from the data stream. + +Despite the similar name, I²S is unrelated and incompatible with the bidirectional I²C (IIC) bus. + +The I²S bus consists of at least three lines: + +.. note:: All lines can be attached to almost any pin and this change can occur even during operation. + +* **Bit clock line** + + * Officially "continuous serial clock (SCK)". Typically written "bit clock (BCLK)". + * In this library function parameter ``sckPin`` or constant ``PIN_I2S_SCK``. + +* **Word clock line** + + * Officially "word select (WS)". Typically called "left-right clock (LRCLK)" or "frame sync (FS)". + * 0 = Left channel, 1 = Right channel + * In this library function parameter ``fsPin`` or constant ``PIN_I2S_FS``. + +* **Data line** + + * Officially "serial data (SD)", but can be called SDATA, SDIN, SDOUT, DACDAT, ADCDAT, etc. + * Unlike Arduino I2S with single data pin switching between input and output, in ESP core driver use separate data line for input and output. + * For backward compatibility, the shared data pin is ``sdPin`` or constant ``PIN_I2S_SD`` when using simplex mode. + + * When using in duplex mode, there are two data lines: + + * Output data line is called ``outSdPin`` for function parameter, or constant ``PIN_I2S_SD_OUT`` + * Input data line is called ``inSdPin`` for function parameter, or constant ``PIN_I2S_SD_IN`` + +I2S Modes +--------- + +The I2S can be set up in three groups of modes: + +* Master (default) or Slave. +* Simplex (default) or Duplex. +* Operation modes (Philips standard, ADC/DAC, PDM) + + * Most of them are dual-channel, some can be single channel + +.. note:: Officially supported operation mode is only ``I2S_PHILIPS_MODE``. Other modes are implemented, but we cannot guarantee flawless execution and behavior. + +Master / Slave Mode +******************* + +In **Master mode** (default) the device is generating clock signal ``sckPin`` and word select signal on ``fsPin``. + +In **Slave mode** the device listens on attached pins for the clock signal and word select - i.e. unless externally driven the pins will remain LOW. + +How to enter either mode is described in the function section. + +Operation Modes +*************** + +Setting the operation mode is done with function ``begin`` (see API section) + +* ``I2S_PHILIPS_MODE`` + * Currently the only official* ``PIN_I2S_SCK`` +* ``PIN_I2S_FS`` +* ``PIN_I2S_SD`` +* ``PIN_I2S_SD_OUT`` only need to send one channel data but the data will be copied for another channel automatically, then both channels will transmit same data. + +* ``ADC_DAC_MODE`` + The output will be an analog signal on pins ``25`` (L or R?) and ``26`` (L or R?). + Input will be received on pin ``_inSdPin``. + The data are sampled in 12 bits and stored in a 16 bits, with the 4 most significant bits set to zero. + +* ``PDM_STEREO_MODE`` + Pulse-density-modulation is similar to PWM, but instead, the pulses have constant width. The signal is modulated with the number of ones or zeroes in sequence. + +* ``PDM_MONO_MODE`` + Single-channel version of PDM mode described above. + +Simplex / Duplex Mode +********************* + +The **Simplex** mode is the default after driver initialization. Simplex mode uses the shared data pin ``sdPin`` or constant ``PIN_I2S_SD`` for both output and input, but can only read or write. This is the same behavior as in original Arduino library. + +The **Duplex** mode uses two separate data pins: + +* Output pin ``outSdPin`` for function parameter, or constant ``PIN_I2S_SD_OUT`` +* Input pin ``inSdPin`` for function parameter, or constant ``PIN_I2S_SD_IN`` + +In this mode, the driver is able to read and write simultaneously on each line and is suitable for applications like walkie-talkie or phone. + +Switching between these modes is performed simply by calling setDuplex() or setSimplex() (see APi section for details and more functions). + +Arduino-ESP32 I2S API +--------------------- + +The ESP32 I2S library is based on the Arduino I2S Library and implements a few more APIs, described in this `documentation `_. + +Initialization and deinitialization +*********************************** + +Before initialization, choose which pins you want to use. In DAC mode you can use only pins `25` and `26` for the output. + +begin (Master Mode) +^^^^^^^^^^^^^^^^^^^ + +Before usage choose which pins you want to use. In DAC mode you can use only pins 25 and 26 as output. + +.. code-block:: arduino + + int begin(int mode, int sampleRate, int bitsPerSample) + +Parameters: + +* [in] ``mode`` one of above mentioned operation mode, for example ``I2S_PHILIPS_MODE``. + +* [in] ``sampleRate`` is the sampling rate in Hz. Currently officially supported value is only 16000 - other than this value will print warning, but continue to operate, however the resulting audio quality may suffer and the app may crash. + +* [in] ``bitsPerSample`` is the number of bits in a channel sample. + +Currently, the supported value is only 16 - other than this value will print a warning, but continues to operate, however, the resulting audio quality may suffer and the application may crash. + +For ``ADC_DAC_MODE`` the only possible value will remain 16. + +This function will return ``true`` on success or ``fail`` in case of failure. + +When failed, an error message will be printed if subscribed. + +begin (Slave Mode) +^^^^^^^^^^^^^^^^^^ + +Performs initialization before use - creates buffers, task handling underlying driver messages, configuring and starting the driver operation. + +This version initializes I2S in SLAVE mode (see previous entry for MASTER mode). + +.. code-block:: arduino + + int begin(int mode, int bitsPerSample) + +Parameters: + +* [in] ``mode`` one of above mentioned modes for example ``I2S_PHILIPS_MODE``. + +* [in] ``bitsPerSample`` is the umber of bits in a channel sample. Currently, the only supported value is only 16 - other than this value will print warning, but continue to operate, however the resulting audio quality may suffer and the app may crash. + +For ``ADC_DAC_MODE`` the only possible value will remain 16. + +This function will return ``true`` on success or ``fail`` in case of failure. + +When failed, an error message will be printed if subscribed. + +end +^^^ + +Performs safe deinitialization - free buffers, destroy task, end driver operation, etc. + +.. code-block:: arduino + + void end() + +Pin setup +********* + +Pins can be changed in two ways- 1st constants, 2nd functions. + +.. note:: Shared data pin can be equal to any other data pin, but must not be equal to clock pin nor frame sync pin! Input and Output pins must not be equal, but one of them can be equal to shared data pin! + +.. code-block:: arduino + + sckPin != fsPin != outSdPin != inSdPin + +.. code-block:: arduino + + sckPin != fsPin != sdPin + +By default, the pin numbers are defined in constants in the header file. You can redefine any of those constants before including ``I2S.h``. This way the driver will use these new default values and you will not need to specify pins in your code. The constants and their default values are: + +* ``PIN_I2S_SCK`` 14 +* ``PIN_I2S_FS`` 25 +* ``PIN_I2S_SD`` 26 +* ``PIN_I2S_SD_OUT`` 26 +* ``PIN_I2S_SD_IN`` 35 + +The second option to change pins is using the following functions. These functions can be called on either on initialized or uninitialized object. + +If called on the initialized object (after calling ``begin``) the pins will change during operation. +If called on the uninitialized object (before calling ``begin``, or after calling ``end``) the new pin setup will be used on next initialization. + +setSckPin +^^^^^^^^^ + +Set and apply clock pin. + +.. code-block:: arduino + + int setSckPin(int sckPin) + +This function will return ``true`` on success or ``fail`` in case of failure. + +setFsPin +^^^^^^^^ + +Set and apply frame sync pin. + +.. code-block:: arduino + + int setFsPin(int fsPin) + +This function will return ``true`` on success or ``fail`` in case of failure. + +setDataPin +^^^^^^^^^^ + +Set and apply shared data pin used in simplex mode. + +.. code-block:: arduino + + int setDataPin(int sdPin) + +This function will return ``true`` on success or ``fail`` in case of failure. + +setDataInPin +^^^^^^^^^^^^ + +Set and apply data input pin. + +.. code-block:: arduino + + int setDataInPin(int inSdPin) + +This function will return ``true`` on success or ``fail`` in case of failure. + +setDataOutPin +^^^^^^^^^^^^^ + +Set and apply data output pin. + +.. code-block:: arduino + + int setDataOutPin(int outSdPin) + +This function will return ``true`` on success or ``fail`` in case of failure. + +setAllPins +^^^^^^^^^^ + +Set all pins using given values in parameters. This is simply a wrapper of four functions mentioned above. + +.. code-block:: arduino + + int setAllPins(int sckPin, int fsPin, int sdPin, int outSdPin, int inSdPin) + +Set all pins to default i.e. take values from constants mentioned above. This simply calls the the function with the following constants. + +* ``PIN_I2S_SCK`` 14 +* ``PIN_I2S_FS`` 25 +* ``PIN_I2S_SD`` 26 +* ``PIN_I2S_SD_OUT`` 26 +* ``PIN_I2S_SD_IN`` 35 + +.. code-block:: arduino + + int setAllPins() + +getSckPin +^^^^^^^^^ + +Get the current value of the clock pin. + +.. code-block:: arduino + + int getSckPin() + +getFsPin +^^^^^^^^ + +Get the current value of frame sync pin. + +.. code-block:: arduino + + int getFsPin() + +getDataPin +^^^^^^^^^^ + +Get the current value of shared data pin. + +.. code-block:: arduino + + int getDataPin() + +getDataInPin +^^^^^^^^^^^^ + +Get the current value of data input pin. + +.. code-block:: arduino + + int getDataInPin() + +getDataOutPin +^^^^^^^^^^^^^ + +Get the current value of data output pin. + +.. code-block:: arduino + + int getDataOutPin() + +onTransmit +^^^^^^^^^^ + +Register the function to be called on each successful transmit event. + +.. code-block:: arduino + + void onTransmit(void(*)(void)) + +onReceive +^^^^^^^^^ + +Register the function to be called on each successful receives event. + +.. code-block:: arduino + + void onReceive(void(*)(void)) + +setBufferSize +^^^^^^^^^^^^^ + +Set the size of buffer. + +.. code-block:: arduino + + int setBufferSize(int bufferSize) + +This function can be called on both the initialized or uninitialized driver. + +If called on initialized, it will change internal values for buffer size and re-initialize driver with new value. +If called on uninitialized, it will only change the internal values which will be used for next initialization. + +Parameter ``bufferSize`` must be in range from 8 to 1024 and the unit is sample words. The default value is 128. + +Example: 16 bit sample, dual channel, buffer size for input: + + ``128 = 2B sample * 2 channels * 128 buffer size * buffer count (default 2) = 1024B`` + +And more ```1024B`` for output buffer in total of ``2kB`` used. + +This function always assumes dual-channel, keeping the same size even for MONO modes. + +This function will return ``true`` on success or ``fail`` in case of failure. + +When failed, an error message will be printed. + +getBufferSize +^^^^^^^^^^^^^ + +Get current buffer sizes in sample words (see description for ``setBufferSize``). + +.. code-block:: arduino + + int getBufferSize() + +Duplex vs Simplex +***************** + +Original Arduino I2S library supports only *simplex* mode (only transmit or only receive at a time). For compatibility, we kept this behavior, but ESP natively supports *duplex* mode (receive and transmit simultaneously on separate pins). +By default this library is initialized in simplex mode as it would in Arduino, switching input and output on ``sdPin`` (constant ``PIN_I2S_SD`` default pin 26). + +setDuplex +^^^^^^^^^ + +Switch to duplex mode and use separate pins: + +.. code-block:: arduino + + int setDuplex() + +input: inSdPin (constant PIN_I2S_SD_IN, default 35) +output: outSdPin (constant PIN_I2S_SD, default 26) + +setSimplex +^^^^^^^^^^ + +(Default mode) + +Switch to simplex mode using shared data pin sdPin (constant PIN_I2S_SD, default 26). + +.. code-block:: arduino + + int setSimplex() + +isDuplex +^^^^^^^^ + +Returns 1 if current mode is duplex, 0 if current mode is simplex (default). + +.. code-block:: arduino + + int isDuplex() + +Data stream +*********** + +available +^^^^^^^^^ + +Returns number of **bytes** ready to read. + +.. code-block:: arduino + + int available() + +read +^^^^ + +Read ``size`` bytes from internal buffer if possible. + +.. code-block:: arduino + + int read(void* buffer, size_t size) + +This function is non-blocking, i.e. if the requested number of bytes is not available, it will return as much as possible without waiting. + +Hint: use ``available()`` before calling this function. + +Parameters: + +[out] ``void* buffer`` buffer into which will be copied data read from internal buffer. WARNING: this buffer must be allocated before use! + +[in] ``size_t size`` number of bytes required to be read. + +Returns number of successfully bytes read. Returns ``false``` in case of reading error. + +Read one sample. + +.. code-block:: arduino + + int read() + +peek +^^^^ + +Read one sample from the internal buffer and returns it. + +.. code-block:: arduino + + int peek() + +Repeated peeks will be returned in the same sample until ``read`` is called. + +flush +^^^^^ + +Force write internal buffer to driver. + +.. code-block:: arduino + + void flush() + +write +^^^^^ + +Write a single byte. + +.. code-block:: arduino + + size_t write(uint8_t) + +Single-sample writes are blocking - waiting until there is free space in the internal buffer to be written into. + +Returns number of successfully written bytes, in this case, 1. Returns 0 on error. + +Write single sample. + +.. code-block:: arduino + + size_t write(int32_t) + +Single-sample writes are blocking - waiting until there is free space in the internal buffer to be written into. + +Returns number of successfully written bytes. Returns 0 on error. + +Expected return number is ``bitsPerSample/8``. + +Write buffer of supplied size; + +.. code-block:: arduino + + size_t write(const void *buffer, size_t size) + +Parameters: + +[in] ``const void *buffer`` buffer to be written +[in] ``size_t size`` size of buffer in bytes + +Returns number of successfully written bytes. Returns 0 in case of error. +The expected return number is equal to ``size``. + +write +^^^^^ + +This is a wrapper of the previous function performing typecast from `uint8_t*`` to ``void*``. + +.. code-block:: arduino + + size_t write(const uint8_t *buffer, size_t size) + +availableForWrite +^^^^^^^^^^^^^^^^^ + +Returns number of bytes available for write. + +.. code-block:: arduino + + int availableForWrite() + +write_blocking +^^^^^^^^^^^^^^ + +Core function implementing blocking write, i.e. waits until all requested data are written. + +.. code-block:: arduino + + size_t write_blocking(const void *buffer, size_t size) + +WARNING: If too many bytes are requested, this can cause WatchDog Trigger Reset! + +Returns number of successfully written bytes. Returns 0 on error. + +write_nonblocking +^^^^^^^^^^^^^^^^^ + +Core function implementing non-blocking write, i.e. writes as much as possible and exits. + +.. code-block:: arduino + + size_t write_nonblocking(const void *buffer, size_t size) + +Returns number of successfully written bytes. Returns 0 on error. + +Sample code +----------- + +.. code-block:: c + + #include + const int buff_size = 128; + int available, read; + uint8_t buffer[buff_size]; + + I2S.begin(I2S_PHILIPS_MODE, 16000, 16); + I2S.read(); // Switch the driver in simplex mode to receive + available = I2S.available(); + if(available < buff_size){ + read = I2S.read(buffer, available); + }else{ + read = I2S.read(buffer, buff_size); + } + I2S.write(buffer, read); + I2S.end(); diff --git a/docs/source/libraries.rst b/docs/source/libraries.rst index a6f37644dbd..d9febb08a1a 100644 --- a/docs/source/libraries.rst +++ b/docs/source/libraries.rst @@ -28,7 +28,7 @@ Currently, the Arduino ESP32 supports the following peripherals with Arduino API +---------------+---------------+---------------+---------------+-------------------------------+ | I2C | Yes | Yes | Yes | | +---------------+---------------+---------------+---------------+-------------------------------+ -| I2S | No | No | No | WIP | +| I2S | Yes | No | No | WIP | +---------------+---------------+---------------+---------------+-------------------------------+ | LEDC | Yes | Yes | Yes | | +---------------+---------------+---------------+---------------+-------------------------------+ @@ -74,5 +74,5 @@ The Arduino ESP32 offers some unique APIs, described in this section: .. toctree:: :maxdepth: 1 :glob: - + api/* diff --git a/idf_component.yml b/idf_component.yml new file mode 100644 index 00000000000..72e81d7b2a9 --- /dev/null +++ b/idf_component.yml @@ -0,0 +1,20 @@ +description: "Arduino core for ESP32, ESP32-S and ESP32-C series of SoCs" +url: "https://github.com/espressif/arduino-esp32" +targets: + - esp32 + - esp32s2 + - esp32c3 +tags: + - arduino +files: + include: + - "cores/**/*" + - "variants/esp32/**/*" + - "variants/esp32s2/**/*" + - "variants/esp32s3/**/*" + - "variants/esp32c3/**/*" + - "libraries/**/*" + - "CMakeLists.txt" + - "Kconfig.projbuild" + exclude: + - "**/*" \ No newline at end of file diff --git a/libraries/I2S/examples/ADCPlotter/.skip.esp32c3 b/libraries/I2S/examples/ADCPlotter/.skip.esp32c3 new file mode 100644 index 00000000000..e69de29bb2d diff --git a/libraries/I2S/examples/ADCPlotter/ADCPlotter.ino b/libraries/I2S/examples/ADCPlotter/ADCPlotter.ino new file mode 100644 index 00000000000..5f3bd93ca9d --- /dev/null +++ b/libraries/I2S/examples/ADCPlotter/ADCPlotter.ino @@ -0,0 +1,86 @@ +/* + This example is only for ESP devices. + + This example demonstrates usage of integrated Digital to Analog Converter (DAC) + You can display sound wave from audio device, or just measure voltage. + + To display audio prepare circuit found in following link or drafted as ASCII art + https://forum.arduino.cc/index.php?topic=567581.0 + (!) Note that unlike in the link we are connecting the supply line to 3.3V (not 5V) + because ADC can measure only up to around 3V. Anything above 3V will be very inaccurate. + + ^ +3.3V + | + _ + | |10k + |_| + | | |10uF + GPIO34-------------*------------| |----------- line in +(Default ADC pin) | +| | + | + _ + | |10k + |_| + | + | + V GND + +Connect hot wire of your audio to Line in and GNd wire of audio cable to common ground (GND) + +Second option to measure voltage on trimmer / potentiometer has following connection + ^ +3.3V + | + _ + | | + GPIO34----------->| | +(Default ADC pin) |_| + | + | + _ + | | optional resistor + |_| + | + | + V GND + Optional resistor will decrease read value. + + Steps to run: + 1. Select target board: + Tools -> Board -> ESP32 Arduino -> your board + 2. Upload sketch + Press upload button (arrow in top left corner) + When you see in console line like this: "Connecting........_____.....__" + On your board press and hold Boot button and press EN button shortly. Now you can release both buttons. + You should see lines like this: "Writing at 0x00010000... (12 %)" with rising percentage on each line. + If this fails, try the board buttons right after pressing upload button, or reconnect the USB cable. + 3. Open plotter + Tools -> Serial Plotter + Enjoy + +Created by Tomas Pilny +on 17th June 2021 +*/ + +#include + +void setup() { + // Open serial communications and wait for port to open: + // A baud rate of 115200 is used instead of 9600 for a faster data rate + // on non-native USB ports + Serial.begin(115200); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // start I2S at 8 kHz with 32-bits per sample + if (!I2S.begin(ADC_DAC_MODE, 8000, 16)) { + Serial.println("Failed to initialize I2S!"); + while (1); // do nothing + } +} + +void loop() { + // read a sample + int sample = I2S.read(); + Serial.println(sample); +} diff --git a/libraries/I2S/examples/FullDuplex/.skip.esp32c3 b/libraries/I2S/examples/FullDuplex/.skip.esp32c3 new file mode 100644 index 00000000000..e69de29bb2d diff --git a/libraries/I2S/examples/FullDuplex/FullDuplex.ino b/libraries/I2S/examples/FullDuplex/FullDuplex.ino new file mode 100644 index 00000000000..9b3625fbd60 --- /dev/null +++ b/libraries/I2S/examples/FullDuplex/FullDuplex.ino @@ -0,0 +1,59 @@ +/* + This example is only for ESP + This example demonstrates simultaneous usage of microphone and speaker using single I2S module. + The application transfers data from input to output + + Circuit: + * ESP32 + * GND connected GND + * VIN connected 5V + * SCK 5 + * FS 25 + * DIN 35 + * DOUT 26 + * I2S microphone + * I2S decoder + headphones / speaker + + created 8 October 2021 + by Tomas Pilny + */ + +#include +const long sampleRate = 16000; +const int bitsPerSample = 32; +uint8_t *buffer; + +void setup() { + Serial.begin(115200); + //I2S.setAllPins(5, 25, 35, 26); // you can change default pins; order of pins = (CLK, WS, IN, OUT) + if(!I2S.setDuplex()){ + Serial.println("ERROR - could not set duplex"); + while(true){ + vTaskDelay(10); // Cannot continue + } + } + if (!I2S.begin(I2S_PHILIPS_MODE, sampleRate, bitsPerSample)) { + Serial.println("Failed to initialize I2S!"); + while(true){ + vTaskDelay(10); // Cannot continue + } + } + buffer = (uint8_t*) malloc(I2S.getBufferSize() * (bitsPerSample / 8)); + if(buffer == NULL){ + Serial.println("Failed to allocate buffer!"); + while(true){ + vTaskDelay(10); // Cannot continue + } + } + Serial.println("Setup done"); +} + +void loop() { + //I2S.write(I2S.read()); // primitive implementation sample-by-sample + + // Buffer based implementation + I2S.read(buffer, I2S.getBufferSize() * (bitsPerSample / 8)); + I2S.write(buffer, I2S.getBufferSize() * (bitsPerSample / 8)); + + //optimistic_yield(1000); // yield if last yield occurred before CPU clock cycles ago +} diff --git a/libraries/I2S/examples/InputSerialPlotter/.skip.esp32c3 b/libraries/I2S/examples/InputSerialPlotter/.skip.esp32c3 new file mode 100644 index 00000000000..e69de29bb2d diff --git a/libraries/I2S/examples/InputSerialPlotter/InputSerialPlotter.ino b/libraries/I2S/examples/InputSerialPlotter/InputSerialPlotter.ino new file mode 100644 index 00000000000..db9f7d0d4f8 --- /dev/null +++ b/libraries/I2S/examples/InputSerialPlotter/InputSerialPlotter.ino @@ -0,0 +1,44 @@ +/* + This example reads audio data from an Invensense's ICS43432 I2S microphone + breakout board, and prints out the samples to the Serial console. The + Serial Plotter built into the Arduino IDE can be used to plot the audio + data (Tools -> Serial Plotter) + + Circuit: + * Arduino/Genuino Zero, MKR family and Nano 33 IoT + * ICS43432: + * GND connected GND + * 3.3V connected to 3.3V (Zero, Nano, ESP32), VCC (MKR) + * WS connected to pin 0 (Zero) or 3 (MKR), A2 (Nano) or 25 (ESP32) + * CLK connected to pin 1 (Zero) or 2 (MKR), A3 (Nano) or 5 (ESP32) + * SD connected to pin 9 (Zero) or A6 (MKR), 4 (Nano) or 26 (ESP32) + created 17 November 2016 + by Sandeep Mistry + */ + +#include + +void setup() { + // Open serial communications and wait for port to open: + // A baud rate of 115200 is used instead of 9600 for a faster data rate + // on non-native USB ports + Serial.begin(115200); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // start I2S at 8 kHz with 32-bits per sample + if (!I2S.begin(I2S_PHILIPS_MODE, 8000, 32)) { + Serial.println("Failed to initialize I2S!"); + while (1); // do nothing + } +} + +void loop() { + // read a sample + int sample = I2S.read(); + + if (sample && sample != -1 && sample != 1) { + Serial.println(sample); + } +} diff --git a/libraries/I2S/examples/SimpleTone/.skip.esp32c3 b/libraries/I2S/examples/SimpleTone/.skip.esp32c3 new file mode 100644 index 00000000000..e69de29bb2d diff --git a/libraries/I2S/examples/SimpleTone/SimpleTone.ino b/libraries/I2S/examples/SimpleTone/SimpleTone.ino new file mode 100644 index 00000000000..dd312cf8a82 --- /dev/null +++ b/libraries/I2S/examples/SimpleTone/SimpleTone.ino @@ -0,0 +1,79 @@ +/* + This example generates a square wave based tone at a specified frequency + and sample rate. Then outputs the data using the I2S interface to a + MAX08357 I2S Amp Breakout board. + + I2S Circuit: + * Arduino/Genuino Zero, MKR family and Nano 33 IoT + * MAX08357: + * GND connected GND + * VIN connected 5V + * LRC connected to pin 0 (Zero) or 3 (MKR), A2 (Nano) or 25 (ESP32) + * BCLK connected to pin 1 (Zero) or 2 (MKR), A3 (Nano) or 5 (ESP32) + * DIN connected to pin 9 (Zero) or A6 (MKR), 4 (Nano) or 26 (ESP32) + + DAC Circuit: + * ESP32 or ESP32-S2 + * Audio amplifier + - Note: + - ESP32 has DAC on GPIO pins 25 and 26. + - ESP32-S2 has DAC on GPIO pins 17 and 18. + - Connect speaker(s) or headphones. + + created 17 November 2016 + by Sandeep Mistry + For ESP extended + Tomas Pilny + 2nd September 2021 + */ + +#include +const int frequency = 440; // frequency of square wave in Hz +const int amplitude = 500; // amplitude of square wave +const int sampleRate = 8000; // sample rate in Hz +const int bps = 16; + +const int halfWavelength = (sampleRate / frequency); // half wavelength of square wave + +short sample = amplitude; // current sample value +int count = 0; + +i2s_mode_t mode = I2S_PHILIPS_MODE; // I2S decoder is needed +// i2s_mode_t mode = ADC_DAC_MODE; // Audio amplifier is needed + +// Mono channel input +// This is ESP specific implementation - +// samples will be automatically copied to both channels inside I2S driver +// If you want to have true mono output use I2S_PHILIPS_MODE and interlay +// second channel with 0-value samples. +// The order of channels is RIGH followed by LEFT +//i2s_mode_t mode = I2S_RIGHT_JUSTIFIED_MODE; // I2S decoder is needed + +void setup() { + Serial.begin(115200); + Serial.println("I2S simple tone"); + + // start I2S at the sample rate with 16-bits per sample + if (!I2S.begin(mode, sampleRate, bps)) { + Serial.println("Failed to initialize I2S!"); + while (1); // do nothing + } +} + +void loop() { + if (count % halfWavelength == 0 ) { + // invert the sample every half wavelength count multiple to generate square wave + sample = -1 * sample; + } + + if(mode == I2S_PHILIPS_MODE || mode == ADC_DAC_MODE){ // write the same sample twice, once for Right and once for Left channel + I2S.write(sample); // Right channel + I2S.write(sample); // Left channel + }else if(mode == I2S_RIGHT_JUSTIFIED_MODE || mode == I2S_LEFT_JUSTIFIED_MODE){ + // write the same only once - it will be automatically copied to the other channel + I2S.write(sample); + } + + // increment the counter for the next sample + count++; +} diff --git a/libraries/I2S/keywords.txt b/libraries/I2S/keywords.txt new file mode 100644 index 00000000000..ad1b8028d42 --- /dev/null +++ b/libraries/I2S/keywords.txt @@ -0,0 +1,61 @@ +####################################### +# Syntax Coloring Map I2S +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### + +I2S KEYWORD1 + +####################################### +# Methods and Functions (KEYWORD2) +####################################### +I2SClass KEYWORD2 +begin KEYWORD2 +end KEYWORD2 + +onReceive KEYWORD2 +onTransmit KEYWORD2 + +setSckPin KEYWORD2 +setFsPin KEYWORD2 +setDataInPin KEYWORD2 +setDataOutPin KEYWORD2 +setAllPins KEYWORD2 + +getSckPin KEYWORD2 +getFsPin KEYWORD2 +getDataPin KEYWORD2 +getDataInPin KEYWORD2 +getDataOutPin KEYWORD2 + +setDuplex KEYWORD2 +setSimplex KEYWORD2 +isDuplex KEYWORD2 + +setBufferSize KEYWORD2 +getBufferSize KEYWORD2 + +write KEYWORD2 +availableForWrite KEYWORD2 + +read KEYWORD2 +available KEYWORD2 + +gpioToAdcUnit KEYWORD2 +gpioToAdcChannel KEYWORD2 + +####################################### +# Constants (LITERAL1) +####################################### +I2S_PHILIPS_MODE LITERAL1 +I2S_RIGHT_JUSTIFIED_MODE LITERAL1 +I2S_LEFT_JUSTIFIED_MODE LITERAL1 +I2S_ADC_DAC LITERAL1 +I2S_PDM LITERAL1 + +PIN_I2S_SCK LITERAL1 +PIN_I2S_FS LITERAL1 +PIN_I2S_SD LITERAL1 +PIN_I2S_SD_OUT LITERAL1 diff --git a/libraries/I2S/library.properties b/libraries/I2S/library.properties new file mode 100644 index 00000000000..bb77e306158 --- /dev/null +++ b/libraries/I2S/library.properties @@ -0,0 +1,9 @@ +name=I2S +version=1.0 +author=Tomas Pilny +maintainer=Tomas Pilny +sentence=Enables the communication with devices that use the Inter-IC Sound (I2S) Bus. Specific implementation for ESP. +paragraph= +category=Communication +url=http://www.arduino.cc/en/Reference/I2S +architectures=esp32 diff --git a/libraries/I2S/src/I2S.cpp b/libraries/I2S/src/I2S.cpp new file mode 100644 index 00000000000..44d3f7a2b0f --- /dev/null +++ b/libraries/I2S/src/I2S.cpp @@ -0,0 +1,1209 @@ +/* + Copyright (c) 2016 Arduino LLC. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + See the GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include +#include +#include "I2S.h" +#include "freertos/semphr.h" + +#define _I2S_EVENT_QUEUE_LENGTH 16 +#define _I2S_DMA_BUFFER_COUNT 2 // BUFFER COUNT must be between 2 and 128 +#define I2S_INTERFACES_COUNT SOC_I2S_NUM + +#ifndef I2S_DEVICE + #define I2S_DEVICE 0 +#endif + +#ifndef I2S_CLOCK_GENERATOR + #define I2S_CLOCK_GENERATOR 0 // does nothing for ESP +#endif + +I2SClass::I2SClass(uint8_t deviceIndex, uint8_t clockGenerator, uint8_t sdPin, uint8_t sckPin, uint8_t fsPin) : + _deviceIndex(deviceIndex), + _sdPin(sdPin), // shared data pin + _inSdPin(PIN_I2S_SD_IN), // input data pin + _outSdPin(PIN_I2S_SD), // output data pin + _sckPin(sckPin), // clock pin + _fsPin(fsPin), // frame (word) select pin + + _state(I2S_STATE_IDLE), + _bitsPerSample(0), + _sampleRate(0), + _mode(I2S_PHILIPS_MODE), + + _buffer_byte_size(0), + + _driverInstalled(false), + _initialized(false), + _callbackTaskHandle(NULL), + _i2sEventQueue(NULL), + _i2s_general_mutex(NULL), + _input_ring_buffer(NULL), + _output_ring_buffer(NULL), + _i2s_dma_buffer_size(128), // Number of frames in each DMA buffer. Frame size = number of channels * Bytes per sample; Must be between 8 and 1024 + _driveClock(true), + _peek_buff(0), + _peek_buff_valid(false), + _nesting_counter(0), + + _onTransmit(NULL), + _onReceive(NULL) +{ + _i2s_general_mutex = xSemaphoreCreateMutex(); + if(_i2s_general_mutex == NULL){ + log_e("I2S could not create internal mutex!"); + } +} + +int I2SClass::_createCallbackTask(){ + int stack_size = 20000; + if(_callbackTaskHandle != NULL){ + log_e("Callback task already exists!"); + return 0; // ERR + } + + xTaskCreate( + onDmaTransferComplete, // Function to implement the task + "onDmaTransferComplete", // Name of the task + stack_size, // Stack size in words + NULL, // Task input parameter + 2, // Priority of the task + &_callbackTaskHandle // Task handle. + ); + if(_callbackTaskHandle == NULL){ + log_e("Could not create callback task"); + return 0; // ERR + } + return 1; // OK +} + +int I2SClass::_installDriver(){ + if(_driverInstalled){ + log_e("I2S driver is already installed"); + return 0; // ERR + } + + esp_i2s::i2s_mode_t i2s_mode = (esp_i2s::i2s_mode_t)(esp_i2s::I2S_MODE_RX | esp_i2s::I2S_MODE_TX); + + if(_driveClock){ + i2s_mode = (esp_i2s::i2s_mode_t)(i2s_mode | esp_i2s::I2S_MODE_MASTER); + }else{ + i2s_mode = (esp_i2s::i2s_mode_t)(i2s_mode | esp_i2s::I2S_MODE_SLAVE); + } + + if(_mode == ADC_DAC_MODE){ + #if (SOC_I2S_SUPPORTS_ADC && SOC_I2S_SUPPORTS_DAC) + if(_bitsPerSample != 16){ // ADC/DAC can only work in 16-bit sample mode + log_e("ERROR invalid bps for ADC/DAC. Allowed only 16, requested %d", _bitsPerSample); + return 0; // ERR + } + i2s_mode = (esp_i2s::i2s_mode_t)(i2s_mode | esp_i2s::I2S_MODE_DAC_BUILT_IN | esp_i2s::I2S_MODE_ADC_BUILT_IN); + #else + log_e("This chip does not support ADC / DAC mode"); + return 0; // ERR + #endif + }else if(_mode == I2S_PHILIPS_MODE || + _mode == I2S_RIGHT_JUSTIFIED_MODE || + _mode == I2S_LEFT_JUSTIFIED_MODE){ // End of ADC/DAC mode; start of Normal Philips mode + if(_bitsPerSample != 8 && _bitsPerSample != 16 && _bitsPerSample != 24 && _bitsPerSample != 32){ + log_e("Invalid bits per sample for normal mode (requested %d)\nAllowed bps = 8 | 16 | 24 | 32", _bitsPerSample); + return 0; // ERR + } + if(_bitsPerSample == 24){ + log_w("Original Arduino library does not support 24 bits per sample.\nKeep that in mind if you should switch back to Arduino"); + } + }else if(_mode == PDM_STEREO_MODE || _mode == PDM_MONO_MODE){ // end of Normal Philips mode; start of PDM mode + #if (SOC_I2S_SUPPORTS_PDM_TX && SOC_I2S_SUPPORTS_PDM_RX) + i2s_mode = (esp_i2s::i2s_mode_t)(i2s_mode | esp_i2s::I2S_MODE_PDM); + #else + log_e("This chip does not support PDM"); + return 0; // ERR + #endif + } // Mode + esp_i2s::i2s_config_t i2s_config = { + .mode = i2s_mode, + .sample_rate = _sampleRate, + .bits_per_sample = (esp_i2s::i2s_bits_per_sample_t)_bitsPerSample, + .channel_format = esp_i2s::I2S_CHANNEL_FMT_RIGHT_LEFT, + .communication_format = (esp_i2s::i2s_comm_format_t)(esp_i2s::I2S_COMM_FORMAT_STAND_I2S), + .intr_alloc_flags = ESP_INTR_FLAG_LEVEL2, + .dma_buf_count = _I2S_DMA_BUFFER_COUNT, + .dma_buf_len = _i2s_dma_buffer_size, + .use_apll = false + }; + + if(_driveClock == false){ + i2s_config.use_apll = true; + i2s_config.fixed_mclk = 512*_sampleRate; + } + + // Install and start i2s driver + while(ESP_OK != esp_i2s::i2s_driver_install((esp_i2s::i2s_port_t) _deviceIndex, &i2s_config, _I2S_EVENT_QUEUE_LENGTH, &_i2sEventQueue)){ + // increase buffer size + if(2*_i2s_dma_buffer_size <= 1024){ + log_w("WARNING i2s driver install failed.\nTrying to increase I2S DMA buffer size from %d to %d\n", _i2s_dma_buffer_size, 2*_i2s_dma_buffer_size); + setBufferSize(2*_i2s_dma_buffer_size); + }else if(_i2s_dma_buffer_size < 1024){ + log_w("WARNING i2s driver install failed.\nTrying to decrease I2S DMA buffer size from %d to 1024\n", _i2s_dma_buffer_size); + setBufferSize(1024); + }else{ // install failed with max buffer size + log_e("ERROR i2s driver install failed"); + return 0; // ERR + } + } //try installing with increasing size + + if(_mode == I2S_RIGHT_JUSTIFIED_MODE || _mode == I2S_LEFT_JUSTIFIED_MODE || _mode == PDM_MONO_MODE){ // mono/single channel + // Set the clock for MONO. Stereo is not supported yet. + if(ESP_OK != esp_i2s::i2s_set_clk((esp_i2s::i2s_port_t) _deviceIndex, _sampleRate, (esp_i2s::i2s_bits_per_sample_t)_bitsPerSample, esp_i2s::I2S_CHANNEL_MONO)){ + log_e("Setting the I2S Clock has failed!\n"); + return 0; // ERR + } + } // mono channel mode + +#if (SOC_I2S_SUPPORTS_ADC && SOC_I2S_SUPPORTS_DAC) + if(_mode == ADC_DAC_MODE){ + esp_i2s::i2s_set_dac_mode(esp_i2s::I2S_DAC_CHANNEL_BOTH_EN); + esp_i2s::adc_unit_t adc_unit; + if(!_gpioToAdcUnit((gpio_num_t)_inSdPin, &adc_unit)){ + log_e("pin to adc unit conversion failed"); + return 0; // ERR + } + esp_i2s::adc_channel_t adc_channel; + if(!_gpioToAdcChannel((gpio_num_t)_inSdPin, &adc_channel)){ + log_e("pin to adc channel conversion failed"); + return 0; // ERR + } + if(ESP_OK != esp_i2s::i2s_set_adc_mode(adc_unit, (esp_i2s::adc1_channel_t)adc_channel)){ + log_e("i2s_set_adc_mode failed"); + return 0; // ERR + } + if(ESP_OK != esp_i2s::i2s_set_pin((esp_i2s::i2s_port_t) _deviceIndex, NULL)){ + log_e("i2s_set_pin failed"); + return 0; // ERR + } + + if(adc_unit == esp_i2s::ADC_UNIT_1){ + esp_i2s::adc1_config_width(esp_i2s::ADC_WIDTH_BIT_12); + esp_i2s::adc1_config_channel_atten((esp_i2s::adc1_channel_t)adc_channel, esp_i2s::ADC_ATTEN_DB_11); + }else if(adc_unit == esp_i2s::ADC_UNIT_2){ + esp_i2s::adc2_config_channel_atten((esp_i2s::adc2_channel_t)adc_channel, esp_i2s::ADC_ATTEN_DB_11); + } + + esp_i2s::i2s_adc_enable((esp_i2s::i2s_port_t) _deviceIndex); + _driverInstalled = true; + }else // End of ADC/DAC mode +#endif // SOC_I2S_SUPPORTS_ADC_DAC + if(_mode == I2S_PHILIPS_MODE || _mode == I2S_RIGHT_JUSTIFIED_MODE || _mode == I2S_LEFT_JUSTIFIED_MODE || _mode == PDM_STEREO_MODE || _mode == PDM_MONO_MODE){ // if I2S mode + _driverInstalled = true; // IDF I2S driver must be installed before calling _applyPinSetting + if(!_applyPinSetting()){ + log_e("could not apply pin setting during driver install"); + _uninstallDriver(); + return 0; // ERR + } + } // if I2S _mode + return 1; // OK +} + +// Init in MASTER mode: the SCK and FS pins are driven as outputs using the sample rate +int I2SClass::begin(int mode, int sampleRate, int bitsPerSample){ + _take_if_not_holding(); + // master mode (driving clock and frame select pins - output) + int ret = begin(mode, sampleRate, bitsPerSample, true); + _give_if_top_call(); + return ret; +} + +// Init in SLAVE mode: the SCK and FS pins are inputs, other side controls sample rate +int I2SClass::begin(int mode, int bitsPerSample){ + _take_if_not_holding(); + // slave mode (not driving clock and frame select pin - input) + int ret = begin(mode, 96000, bitsPerSample, false); + _give_if_top_call(); + return ret; +} + + +// Core function +int I2SClass::begin(int mode, int sampleRate, int bitsPerSample, bool driveClock){ + _take_if_not_holding(); + if(_initialized){ + log_e("ERROR: Object already initialized! Call I2S.end() to disable"); + _give_if_top_call(); + return 0; // ERR + } + _driveClock = driveClock; + _mode = mode; + _sampleRate = (uint32_t)sampleRate; + _bitsPerSample = bitsPerSample; + + // There is work in progress on this library. + if(_bitsPerSample == 16 && _sampleRate > 16000 && driveClock){ + log_w("This sample rate is not officially supported - audio might be noisy.\nTry using sample rate below or equal to 16000"); + } + if(_bitsPerSample != 16){ + log_w("This bit-per-sample is not officially supported - audio quality might suffer.\nTry using 16bps, with sample rate below or equal 16000"); + } + if(_mode != I2S_PHILIPS_MODE){ + log_w("This mode is not officially supported - audio quality might suffer.\nAt the moment the only supported mode is I2S_PHILIPS_MODE"); + } + + if (_state != I2S_STATE_IDLE && _state != I2S_STATE_DUPLEX) { + log_e("Error: unexpected _state (%d)", _state); + _give_if_top_call(); + return 0; // ERR + } + + switch (mode) { + case I2S_PHILIPS_MODE: + case I2S_RIGHT_JUSTIFIED_MODE: + case I2S_LEFT_JUSTIFIED_MODE: + + #if (SOC_I2S_SUPPORTS_ADC && SOC_I2S_SUPPORTS_DAC) + case ADC_DAC_MODE: + #endif + + case PDM_STEREO_MODE: + case PDM_MONO_MODE: + break; + + default: // invalid mode + log_e("ERROR: unknown mode"); + _give_if_top_call(); + return 0; // ERR + } + + if(!_installDriver()){ + log_e("ERROR: failed to install driver"); + end(); + _give_if_top_call(); + return 0; // ERR + } + + _buffer_byte_size = _i2s_dma_buffer_size * (_bitsPerSample / 8) * _I2S_DMA_BUFFER_COUNT * 2; + _input_ring_buffer = xRingbufferCreate(_buffer_byte_size, RINGBUF_TYPE_BYTEBUF); + _output_ring_buffer = xRingbufferCreate(_buffer_byte_size, RINGBUF_TYPE_BYTEBUF); + if(_input_ring_buffer == NULL || _output_ring_buffer == NULL){ + log_e("ERROR: could not create one or both internal buffers. Requested size = %d\n", _buffer_byte_size); + _give_if_top_call(); + return 0; // ERR + } + + if(!_createCallbackTask()){ + log_e("ERROR: failed to create callback task"); + end(); + _give_if_top_call(); + return 0; // ERR + } + _initialized = true; + _give_if_top_call(); + return 1; // OK +} + +int I2SClass::_applyPinSetting(){ + if(_driverInstalled){ + esp_i2s::i2s_pin_config_t pin_config = { + .bck_io_num = _sckPin, + .ws_io_num = _fsPin, + .data_out_num = I2S_PIN_NO_CHANGE, + .data_in_num = I2S_PIN_NO_CHANGE + }; + if (_state == I2S_STATE_DUPLEX){ // duplex + pin_config.data_out_num = _outSdPin; + pin_config.data_in_num = _inSdPin; + }else{ // simplex + if(_state == I2S_STATE_RECEIVER){ + pin_config.data_out_num = I2S_PIN_NO_CHANGE; + pin_config.data_in_num = _sdPin; + }else if(_state == I2S_STATE_TRANSMITTER){ + pin_config.data_out_num = _sdPin; + pin_config.data_in_num = I2S_PIN_NO_CHANGE; + }else{ + pin_config.data_out_num = I2S_PIN_NO_CHANGE; + pin_config.data_in_num = _sdPin; + } + } + if(ESP_OK != esp_i2s::i2s_set_pin((esp_i2s::i2s_port_t) _deviceIndex, &pin_config)){ + log_e("i2s_set_pin failed; attempted settings: SCK=%d; FS=%d; DIN=%d; DOUT=%d", pin_config.bck_io_num, pin_config.ws_io_num, pin_config.data_in_num, pin_config.data_out_num); + return 0; // ERR + }else{ + return 1; // OK + } + } // if(_driverInstalled) + return 1; // OK +} + +void I2SClass::_setSckPin(int sckPin){ + _take_if_not_holding(); + if(sckPin >= 0){ + _sckPin = sckPin; + }else{ + _sckPin = PIN_I2S_SCK; + } + _give_if_top_call(); +} + +int I2SClass::setSckPin(int sckPin){ + _take_if_not_holding(); + _setSckPin(sckPin); + int ret = _applyPinSetting(); + _applyPinSetting(); + _give_if_top_call(); + return ret; +} + +void I2SClass::_setFsPin(int fsPin){ + if(fsPin >= 0){ + _fsPin = fsPin; + }else{ + _fsPin = PIN_I2S_FS; + } +} + +int I2SClass::setFsPin(int fsPin){ + _take_if_not_holding(); + _setFsPin(fsPin); + int ret = _applyPinSetting(); + _give_if_top_call(); + return ret; +} + +// shared data pin for simplex +void I2SClass::_setDataPin(int sdPin){ + if(sdPin >= 0){ + _sdPin = sdPin; + }else{ + _sdPin = PIN_I2S_SD; + } +} + +// shared data pin for simplex +int I2SClass::setDataPin(int sdPin){ + _take_if_not_holding(); + _setDataPin(sdPin); + int ret = _applyPinSetting(); + _give_if_top_call(); + return ret; +} + +void I2SClass::_setDataInPin(int inSdPin){ + if(inSdPin >= 0){ + _inSdPin = inSdPin; + }else{ + _inSdPin = PIN_I2S_SD_IN; + } +} + +int I2SClass::setDataInPin(int inSdPin){ + _take_if_not_holding(); + _setDataInPin(inSdPin); + int ret = _applyPinSetting(); + _give_if_top_call(); + return ret; +} + +void I2SClass::_setDataOutPin(int outSdPin){ + if(outSdPin >= 0){ + _outSdPin = outSdPin; + }else{ + _outSdPin = PIN_I2S_SD; + } +} + +int I2SClass::setDataOutPin(int outSdPin){ + _take_if_not_holding(); + _setDataOutPin(outSdPin); + int ret = _applyPinSetting(); + _give_if_top_call(); + return ret; +} + +int I2SClass::setAllPins(){ + _take_if_not_holding(); + int ret = setAllPins(PIN_I2S_SCK, PIN_I2S_FS, PIN_I2S_SD, PIN_I2S_SD_OUT, PIN_I2S_SD_IN); + _give_if_top_call(); + return ret; +} + +int I2SClass::setAllPins(int sckPin, int fsPin, int sdPin, int outSdPin, int inSdPin){ + _take_if_not_holding(); + _setSckPin(sckPin); + _setFsPin(fsPin); + _setDataPin(sdPin); + _setDataOutPin(outSdPin); + _setDataInPin(inSdPin); + int ret = _applyPinSetting(); + _give_if_top_call(); + return ret; +} + +int I2SClass::setDuplex(){ + _take_if_not_holding(); + _state = I2S_STATE_DUPLEX; + _give_if_top_call(); + return 1; +} + +int I2SClass::setSimplex(){ + _take_if_not_holding(); + _state = I2S_STATE_IDLE; + _give_if_top_call(); + return 1; +} + +int I2SClass::isDuplex(){ + _take_if_not_holding(); + int ret = (int)(_state == I2S_STATE_DUPLEX); + _give_if_top_call(); + return ret; +} + +int I2SClass::getSckPin(){ + _take_if_not_holding(); + int ret = _sckPin; + _give_if_top_call(); + return ret; +} + +int I2SClass::getFsPin(){ + _take_if_not_holding(); + int ret = _fsPin; + _give_if_top_call(); + return ret; +} + +int I2SClass::getDataPin(){ + _take_if_not_holding(); + int ret = _sdPin; + _give_if_top_call(); + return ret; +} + +int I2SClass::getDataInPin(){ + _take_if_not_holding(); + int ret = _inSdPin; + _give_if_top_call(); + return ret; +} + +int I2SClass::getDataOutPin(){ + _take_if_not_holding(); + int ret = _outSdPin; + _give_if_top_call(); + return ret; +} + +void I2SClass::_uninstallDriver(){ + if(_driverInstalled){ + #if (SOC_I2S_SUPPORTS_ADC && SOC_I2S_SUPPORTS_DAC) + if(_mode == ADC_DAC_MODE){ + esp_i2s::i2s_adc_disable((esp_i2s::i2s_port_t) _deviceIndex); + } + #endif + esp_i2s::i2s_driver_uninstall((esp_i2s::i2s_port_t) _deviceIndex); + + if(_state != I2S_STATE_DUPLEX){ + _state = I2S_STATE_IDLE; + } + _driverInstalled = false; + } // if(_driverInstalled) +} + +void I2SClass::end(){ + _take_if_not_holding(); + if(xTaskGetCurrentTaskHandle() != _callbackTaskHandle){ + if(_callbackTaskHandle){ + vTaskDelete(_callbackTaskHandle); + _callbackTaskHandle = NULL; // prevent secondary termination to non-existing task + } + _uninstallDriver(); + _onTransmit = NULL; + _onReceive = NULL; + if(_input_ring_buffer != NULL){ + vRingbufferDelete(_input_ring_buffer); + _input_ring_buffer = NULL; + } + if(_output_ring_buffer != NULL){ + vRingbufferDelete(_output_ring_buffer); + _output_ring_buffer = NULL; + } + _initialized = false; + }else{ + log_w("WARNING: ending I2SClass from callback task not permitted, but attempted!"); + } + _give_if_top_call(); +} + +// Bytes available to read +int I2SClass::available(){ + _take_if_not_holding(); + int ret = 0; + if(_input_ring_buffer != NULL){ + ret = _buffer_byte_size - (int)xRingbufferGetCurFreeSize(_input_ring_buffer); + } + _give_if_top_call(); + return ret; +} + +union i2s_sample_t { + uint8_t b8; + int16_t b16; + int32_t b32; +}; + +int I2SClass::read(){ + _take_if_not_holding(); + i2s_sample_t sample; + sample.b32 = 0; + if(_initialized){ + read(&sample, _bitsPerSample / 8); + + if (_bitsPerSample == 32) { + _give_if_top_call(); + return sample.b32; + } else if (_bitsPerSample == 16) { + _give_if_top_call(); + return sample.b16; + } else if (_bitsPerSample == 8) { + _give_if_top_call(); + return sample.b8; + } else { + _give_if_top_call(); + return 0; // sample value + } + } // if(_initialized) + _give_if_top_call(); + return 0; // sample value +} + +int I2SClass::read(void* buffer, size_t size){ + _take_if_not_holding(); + size_t requested_size = size; + if(_initialized){ + if(!_enableReceiver()){ + _give_if_top_call(); + return 0; // There was an error switching to receiver + } // _enableReceiver succeeded ? + + size_t item_size = 0; + void *tmp_buffer; + if(_input_ring_buffer != NULL){ + if(_peek_buff_valid){ + memcpy(buffer, &_peek_buff, _bitsPerSample/8); + _peek_buff_valid = false; + requested_size -= _bitsPerSample/8; + } + tmp_buffer = xRingbufferReceiveUpTo(_input_ring_buffer, &item_size, pdMS_TO_TICKS(1000), requested_size); + if(tmp_buffer != NULL){ + memcpy(buffer, tmp_buffer, item_size); + #if (SOC_I2S_SUPPORTS_ADC && SOC_I2S_SUPPORTS_DAC) + if(_mode == ADC_DAC_MODE){ + for(size_t i = 0; i < item_size / 2; ++i){ + ((uint16_t*)buffer)[i] = ((uint16_t*)buffer)[i] & 0x0FFF; + } + } // ADC/DAC mode + #endif + vRingbufferReturnItem(_input_ring_buffer, tmp_buffer); + _give_if_top_call(); + return item_size; + }else{ + log_w("input buffer is empty - timed out"); + _give_if_top_call(); + return 0; // 0 Bytes read / ERR + } // tmp buffer not NULL ? + } // ring buffer not NULL ? + } // if(_initialized) + _give_if_top_call(); + return 0; // 0 Bytes read / ERR +} + +size_t I2SClass::write(uint8_t data){ + _take_if_not_holding(); + size_t ret = 0; + if(_initialized){ + ret = write_blocking((int32_t*)&data, 1); + } + _give_if_top_call(); + return ret; +} + +size_t I2SClass::write(int32_t sample){ + _take_if_not_holding(); + size_t ret = 0; + if(_initialized){ + ret = write_blocking(&sample, _bitsPerSample/8); + } + _give_if_top_call(); + return ret; +} + +size_t I2SClass::write(const uint8_t *buffer, size_t size){ + _take_if_not_holding(); + size_t ret = 0; + if(_initialized){ + ret = write((const void*)buffer, size); + } + _give_if_top_call(); + return ret; +} + +size_t I2SClass::write(const void *buffer, size_t size){ + _take_if_not_holding(); + size_t ret = 0; + if(_initialized){ + //size_t ret = write_blocking(buffer, size); + ret = write_nonblocking(buffer, size); + } // if(_initialized) + _give_if_top_call(); + return ret; +} + +// blocking version of write +// This version of write will wait indefinitely to write requested samples +// into output buffer +size_t I2SClass::write_blocking(const void *buffer, size_t size){ + _take_if_not_holding(); + if(_initialized){ + if(!_enableTransmitter()){ + _give_if_top_call(); + return 0; // There was an error switching to transmitter + } // _enableTransmitter succeeded ? + + if(_output_ring_buffer != NULL){ + int ret = xRingbufferSend(_output_ring_buffer, buffer, size, portMAX_DELAY); + if(pdTRUE == ret){ + _give_if_top_call(); + return size; + }else{ + log_e("xRingbufferSend() with infinite wait returned with error"); + _give_if_top_call(); + return 0; + } // ring buffer send ok ? + } // ring buffer not NULL ? + } // if(_initialized) + return 0; + log_w("I2S not initialized"); + _give_if_top_call(); + return 0; +} + +// non-blocking version of write +// In case there is not enough space in buffer to write requested size +// this function will try to flush the buffer and write requested data with 0 time-out +size_t I2SClass::write_nonblocking(const void *buffer, size_t size){ + _take_if_not_holding(); + if(_initialized){ + if(_state != I2S_STATE_TRANSMITTER && _state != I2S_STATE_DUPLEX){ + if(!_enableTransmitter()){ + _give_if_top_call(); + return 0; // There was an error switching to transmitter + } + } + if(availableForWrite() < size){ + flush(); + } + if(_output_ring_buffer != NULL){ + if(pdTRUE == xRingbufferSend(_output_ring_buffer, buffer, size, 0)){ + _give_if_top_call(); + return size; + }else{ + log_w("I2S could not write all data into ring buffer!"); + _give_if_top_call(); + return 0; + } + } + } // if(_initialized) + return 0; + _give_if_top_call(); // this should not be needed +} + +/* + Read 1 sample from internal buffer and return it. + Repeated peeks will return the same sample until read is called. +*/ +int I2SClass::peek(){ + _take_if_not_holding(); + int ret = 0; + if(_initialized && _input_ring_buffer != NULL && !_peek_buff_valid){ + size_t item_size = 0; + void *item = NULL; + + item = xRingbufferReceiveUpTo(_input_ring_buffer, &item_size, 0, _bitsPerSample/8); // fetch 1 sample + if (item != NULL && item_size == _bitsPerSample/8){ + _peek_buff = *((int*)item); + vRingbufferReturnItem(_input_ring_buffer, item); + _peek_buff_valid = true; + } + + } // if(_initialized) + if(_peek_buff_valid){ + ret = _peek_buff; + } + _give_if_top_call(); + return ret; +} + +void I2SClass::flush(){ + _take_if_not_holding(); + if(_initialized){ + const size_t single_dma_buf = _i2s_dma_buffer_size*(_bitsPerSample/8)*2; + size_t item_size = 0; + void *item = NULL; + if(_output_ring_buffer != NULL){ + item = xRingbufferReceiveUpTo(_output_ring_buffer, &item_size, 0, single_dma_buf); + if (item != NULL){ + _fix_and_write(item, item_size); + vRingbufferReturnItem(_output_ring_buffer, item); + } + } + } // if(_initialized) + _give_if_top_call(); +} + +// Bytes available to write +int I2SClass::availableForWrite(){ + _take_if_not_holding(); + int ret = 0; + if(_initialized){ + if(_output_ring_buffer != NULL){ + ret = (int)xRingbufferGetCurFreeSize(_output_ring_buffer); + } + } // if(_initialized) + _give_if_top_call(); + return ret; +} + +void I2SClass::onTransmit(void(*function)(void)){ + _take_if_not_holding(); + _onTransmit = function; + _give_if_top_call(); +} + +void I2SClass::onReceive(void(*function)(void)){ + _take_if_not_holding(); + _onReceive = function; + _give_if_top_call(); +} + +int I2SClass::setBufferSize(int bufferSize){ + _take_if_not_holding(); + int ret = 0; + if(bufferSize >= 8 && bufferSize <= 1024){ + _i2s_dma_buffer_size = bufferSize; + }else{ + log_e("setBufferSize: wrong input! Buffer size must be between 8 and 1024. Requested %d", bufferSize); + _give_if_top_call(); + return 0; // ERR + } // check requested buffer size + + if(_initialized){ + _uninstallDriver(); + ret = _installDriver(); + _give_if_top_call(); + return ret; + }else{ // check requested buffer size + _give_if_top_call(); + return 1; // It's ok to change buffer size for uninitialized driver - new size will be used on begin() + } // if(_initialized) + _give_if_top_call(); + return 0; // ERR +} + +int I2SClass::getBufferSize(){ + _take_if_not_holding(); + int ret = _i2s_dma_buffer_size; + _give_if_top_call(); + return ret; +} + +int I2SClass::_enableTransmitter(){ + if(_state != I2S_STATE_DUPLEX && _state != I2S_STATE_TRANSMITTER){ + _state = I2S_STATE_TRANSMITTER; + return _applyPinSetting(); + } + return 1; // Ok +} + +int I2SClass::_enableReceiver(){ + if(_state != I2S_STATE_DUPLEX && _state != I2S_STATE_RECEIVER){ + _state = I2S_STATE_RECEIVER; + return _applyPinSetting(); + } + return 1; // Ok +} + +void I2SClass::_tx_done_routine(uint8_t* prev_item){ + static bool prev_item_valid = false; + const size_t single_dma_buf = _i2s_dma_buffer_size*(_bitsPerSample/8)*2; // *2 for stereo - it has double number of samples for 2 channels + static size_t item_size = 0; + static size_t prev_item_size = 0; + static void *item = NULL; + static int prev_item_offset = 0; + static size_t bytes_written = 0; + + if(prev_item_valid){ // use item from previous round + _fix_and_write(prev_item+prev_item_offset, prev_item_size, &bytes_written); + if(prev_item_size == bytes_written){ + prev_item_valid = false; + } // write size check + prev_item_offset = bytes_written; + prev_item_size -= bytes_written; + } // prev_item_valid + + if(_output_ring_buffer != NULL && (_buffer_byte_size - xRingbufferGetCurFreeSize(_output_ring_buffer) >= single_dma_buf)){ // fill up the I2S DMA buffer + bytes_written = 0; + item_size = 0; + if(_buffer_byte_size - xRingbufferGetCurFreeSize(_output_ring_buffer) >= _i2s_dma_buffer_size*(_bitsPerSample/8)){ // don't read from almost empty buffer + item = xRingbufferReceiveUpTo(_output_ring_buffer, &item_size, pdMS_TO_TICKS(0), single_dma_buf); + if (item != NULL){ + _fix_and_write(item, item_size, &bytes_written); + if(item_size != bytes_written){ // save item that was not written correctly for later + memcpy(prev_item, (void*)&((uint8_t*)item)[bytes_written], item_size-bytes_written); + prev_item_size = item_size - bytes_written; + prev_item_offset = 0; + prev_item_valid = true; + } // save item that was not written correctly for later + vRingbufferReturnItem(_output_ring_buffer, item); + } // Check received item + } // don't read from almost empty buffer + } // fill up the I2S DMA buffer + if(_onTransmit){ + _onTransmit(); + } // user callback +} + +void I2SClass::_rx_done_routine(){ + size_t bytes_read = 0; + const size_t single_dma_buf = _i2s_dma_buffer_size*(_bitsPerSample/8); + + if(_input_ring_buffer != NULL){ + uint8_t *_inputBuffer = (uint8_t*)malloc(_i2s_dma_buffer_size*4); + size_t avail = xRingbufferGetCurFreeSize(_input_ring_buffer); + if(avail > 0){ + esp_err_t ret = esp_i2s::i2s_read((esp_i2s::i2s_port_t) _deviceIndex, _inputBuffer, avail <= single_dma_buf ? avail : single_dma_buf, (size_t*) &bytes_read, 0); + if(ret != ESP_OK){ + log_w("i2s_read returned with error %d", ret); + } + _post_read_data_fix(_inputBuffer, &bytes_read); + } + + if(bytes_read > 0){ // when read more than 0, then send to ring buffer + if(pdTRUE != xRingbufferSend(_input_ring_buffer, _inputBuffer, bytes_read, 0)){ + log_w("I2S failed to send item from DMA to internal buffer\n"); + } // xRingbufferSendComplete + } // if(bytes_read > 0) + free(_inputBuffer); + if (_onReceive && avail < _buffer_byte_size){ // when user callback is registered && and there is some data in ring buffer to read + _onReceive(); + } // user callback + } +} + +void I2SClass::_onTransferComplete(){ + uint8_t prev_item[_i2s_dma_buffer_size*4]; + esp_i2s::i2s_event_t i2s_event; + + while(true){ + xQueueReceive(_i2sEventQueue, &i2s_event, portMAX_DELAY); + if(i2s_event.type == esp_i2s::I2S_EVENT_TX_DONE){ + _tx_done_routine(prev_item); + }else if(i2s_event.type == esp_i2s::I2S_EVENT_RX_DONE){ + _rx_done_routine(); + } // RX Done + } // infinite loop +} + +void I2SClass::onDmaTransferComplete(void*){ + I2S._onTransferComplete(); +} + +void I2SClass::_take_if_not_holding(){ + TaskHandle_t mutex_holder = xSemaphoreGetMutexHolder(_i2s_general_mutex); + if(mutex_holder != NULL && mutex_holder == xTaskGetCurrentTaskHandle()){ + ++_nesting_counter; + return; // we are already holding this mutex - no need to take it + } + + // we are not holding the mutex - wait for it and take it + if(xSemaphoreTake(_i2s_general_mutex, portMAX_DELAY) != pdTRUE ){ + log_e("I2S internal mutex take returned with error"); + } + //_give_if_top_call(); // call after this function +} + +void I2SClass::_give_if_top_call(){ + if(_nesting_counter){ + --_nesting_counter; + }else{ + if(xSemaphoreGive(_i2s_general_mutex) != pdTRUE){ + log_e("I2S internal mutex give error"); + } + } +} + + +// Fixes data in-situ received from esp i2s driver. After fixing they reflect what was on the bus. +// input - bytes as received from i2s_read - this serves as input and output buffer +// size - number of bytes (this may be changed during operation) +void I2SClass::_post_read_data_fix(void *input, size_t *size){ + ulong dst_ptr = 0; + switch(_bitsPerSample){ + case 8: + for(int i = 0; i < *size; i+=4){ + ((uint8_t*)input)[dst_ptr++] = ((uint8_t*)input)[i+3]; + ((uint8_t*)input)[dst_ptr++] = ((uint8_t*)input)[i+1]; + } + *size /= 2; + break; + case 16: + uint16_t tmp; + for(int i = 0; i < *size/2; i+=2){ + tmp = ((uint16_t*)input)[i]; + ((uint16_t*)input)[dst_ptr++] = ((uint16_t*)input)[i+1]; + ((uint16_t*)input)[dst_ptr++] = tmp; + } + break; + default: ; // Do nothing + } // switch +} + +// Prepares data and writes them to IDF i2s driver. +// This counters possible bug in ESP IDF I2S driver +// output - bytes to be sent +// size - number of bytes in original buffer +// bytes_written - number of bytes used from original buffer +// actual_bytes_written - number of bytes written by i2s_write after fix +void I2SClass::_fix_and_write(void *output, size_t size, size_t *bytes_written, size_t *actual_bytes_written){ + long start = millis(); + ulong src_ptr = 0; + uint8_t* buff; + size_t buff_size = size; + switch(_bitsPerSample){ + case 8: + buff_size = size *2; + buff = (uint8_t*)calloc(buff_size, sizeof(uint8_t)); + if(buff == NULL){ + log_e("callock error"); + if(bytes_written != NULL){ *bytes_written = 0; } + return; + } + for(int i = 0; i < buff_size ; i+=4){ + ((uint8_t*)buff)[i+3] = (uint16_t)((uint8_t*)output)[src_ptr++]; + ((uint8_t*)buff)[i+1] = (uint16_t)((uint8_t*)output)[src_ptr++]; + } + break; + case 16: + buff = (uint8_t*)malloc(buff_size); + if(buff == NULL){ + log_e("malloc error"); + if(bytes_written != NULL){ *bytes_written = 0; } + return; + } + for(int i = 0; i < size/2; i += 2 ){ + ((uint16_t*)buff)[i] = ((uint16_t*)output)[i+1]; // [1] <- [0] + ((uint16_t*)buff)[i+1] = ((uint16_t*)output)[i]; // [0] <- [1] + } + break; + case 24: + buff = (uint8_t*)output; + break; + case 32: + buff = (uint8_t*)output; + break; + default: ; // Do nothing + } // switch + + size_t _bytes_written; + esp_err_t ret = esp_i2s::i2s_write((esp_i2s::i2s_port_t) _deviceIndex, buff, buff_size, &_bytes_written, 0); // fixed + if(ret != ESP_OK){ + log_e("Error: writing data to i2s - function returned with err code %d", ret); + } + if(ret == ESP_OK && buff_size != _bytes_written){ + log_w("Warning: writing data to i2s - written %d B instead of requested %d B", _bytes_written, buff_size); + } + // free if the buffer was actually allocated + if(_bitsPerSample == 8 || _bitsPerSample == 16){ + free(buff); + } + if(bytes_written != NULL){ + *bytes_written = _bitsPerSample == 8 ? _bytes_written/2 : _bytes_written; + } + if(actual_bytes_written != NULL){ + *actual_bytes_written = _bytes_written; + } +} + + +#if (SOC_I2S_SUPPORTS_ADC && SOC_I2S_SUPPORTS_DAC) +int I2SClass::_gpioToAdcUnit(gpio_num_t gpio_num, esp_i2s::adc_unit_t* adc_unit){ + switch(gpio_num){ +#if CONFIG_IDF_TARGET_ESP32 + // ADC 1 + case GPIO_NUM_36: + case GPIO_NUM_37: + case GPIO_NUM_38: + case GPIO_NUM_39: + case GPIO_NUM_32: + case GPIO_NUM_33: + case GPIO_NUM_34: + case GPIO_NUM_35: + *adc_unit = esp_i2s::ADC_UNIT_1; + return 1; // OK + + // ADC 2 + case GPIO_NUM_0: + log_w("GPIO 0 for ADC should not be used for dev boards due to external auto program circuits."); + case GPIO_NUM_4: + case GPIO_NUM_2: + case GPIO_NUM_15: + case GPIO_NUM_13: + case GPIO_NUM_12: + case GPIO_NUM_14: + case GPIO_NUM_27: + case GPIO_NUM_25: + case GPIO_NUM_26: + *adc_unit = esp_i2s::ADC_UNIT_2; + return 1; // OK +#endif + +#if (CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32S3) + case GPIO_NUM_1: + case GPIO_NUM_2: + case GPIO_NUM_3: + case GPIO_NUM_4: + case GPIO_NUM_5: + case GPIO_NUM_6: + case GPIO_NUM_7: + case GPIO_NUM_8: + case GPIO_NUM_9: + case GPIO_NUM_10: + *adc_unit = esp_i2s::ADC_UNIT_1; + return 1; // OK +#endif + +#if CONFIG_IDF_TARGET_ESP32S2 + case GPIO_NUM_11: + case GPIO_NUM_12: + case GPIO_NUM_13: + case GPIO_NUM_14: + case GPIO_NUM_15: + case GPIO_NUM_16: + case GPIO_NUM_17: + case GPIO_NUM_18: + case GPIO_NUM_19: + case GPIO_NUM_20: + *adc_unit = esp_i2s::ADC_UNIT_2; + return 1; // OK +#endif + +#if (CONFIG_IDF_TARGET_ESP32C3 || CONFIG_IDF_TARGET_ESP32H2) + case GPIO_NUM_0: + case GPIO_NUM_1: + case GPIO_NUM_2: + case GPIO_NUM_3: + case GPIO_NUM_4: + *adc_unit = esp_i2s::ADC_UNIT_1; + return 1; // OK + case GPIO_NUM_5: + *adc_unit = esp_i2s::ADC_UNIT_2; + return 1; // OK +#endif + default: + log_e("GPIO %d not usable for ADC!", gpio_num); + log_i("Please refer to documentation https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/gpio.html"); + return 0; // ERR + } +} + +int I2SClass::_gpioToAdcChannel(gpio_num_t gpio_num, esp_i2s::adc_channel_t* adc_channel){ + switch(gpio_num){ +#if CONFIG_IDF_TARGET_ESP32 + // ADC 1 + case GPIO_NUM_36: *adc_channel = esp_i2s::ADC_CHANNEL_0; return 1; // OK + case GPIO_NUM_37: *adc_channel = esp_i2s::ADC_CHANNEL_1; return 1; // OK + case GPIO_NUM_38: *adc_channel = esp_i2s::ADC_CHANNEL_2; return 1; // OK + case GPIO_NUM_39: *adc_channel = esp_i2s::ADC_CHANNEL_3; return 1; // OK + case GPIO_NUM_32: *adc_channel = esp_i2s::ADC_CHANNEL_4; return 1; // OK + case GPIO_NUM_33: *adc_channel = esp_i2s::ADC_CHANNEL_5; return 1; // OK + case GPIO_NUM_34: *adc_channel = esp_i2s::ADC_CHANNEL_6; return 1; // OK + case GPIO_NUM_35: *adc_channel = esp_i2s::ADC_CHANNEL_7; return 1; // OK + + // ADC 2 + case GPIO_NUM_0: + log_w("GPIO 0 for ADC should not be used for dev boards due to external auto program circuits."); + *adc_channel = esp_i2s::ADC_CHANNEL_1; return 1; // OK + case GPIO_NUM_4: *adc_channel = esp_i2s::ADC_CHANNEL_0; return 1; // OK + case GPIO_NUM_2: *adc_channel = esp_i2s::ADC_CHANNEL_2; return 1; // OK + case GPIO_NUM_15: *adc_channel = esp_i2s::ADC_CHANNEL_3; return 1; // OK + case GPIO_NUM_13: *adc_channel = esp_i2s::ADC_CHANNEL_4; return 1; // OK + case GPIO_NUM_12: *adc_channel = esp_i2s::ADC_CHANNEL_5; return 1; // OK + case GPIO_NUM_14: *adc_channel = esp_i2s::ADC_CHANNEL_6; return 1; // OK + case GPIO_NUM_27: *adc_channel = esp_i2s::ADC_CHANNEL_7; return 1; // OK + case GPIO_NUM_25: *adc_channel = esp_i2s::ADC_CHANNEL_8; return 1; // OK + case GPIO_NUM_26: *adc_channel = esp_i2s::ADC_CHANNEL_9; return 1; // OK +#endif + +#if (CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32S3) + case GPIO_NUM_1: *adc_channel = esp_i2s::ADC_CHANNEL_0; return 1; // OK + case GPIO_NUM_2: *adc_channel = esp_i2s::ADC_CHANNEL_1; return 1; // OK + case GPIO_NUM_3: *adc_channel = esp_i2s::ADC_CHANNEL_2; return 1; // OK + case GPIO_NUM_4: *adc_channel = esp_i2s::ADC_CHANNEL_3; return 1; // OK + case GPIO_NUM_5: *adc_channel = esp_i2s::ADC_CHANNEL_4; return 1; // OK + case GPIO_NUM_6: *adc_channel = esp_i2s::ADC_CHANNEL_5; return 1; // OK + case GPIO_NUM_7: *adc_channel = esp_i2s::ADC_CHANNEL_6; return 1; // OK + case GPIO_NUM_8: *adc_channel = esp_i2s::ADC_CHANNEL_7; return 1; // OK + case GPIO_NUM_9: *adc_channel = esp_i2s::ADC_CHANNEL_8; return 1; // OK + case GPIO_NUM_10: *adc_channel = esp_i2s::ADC_CHANNEL_9; return 1; // OK +#endif + +#if CONFIG_IDF_TARGET_ESP32S2 + case GPIO_NUM_11: *adc_channel = esp_i2s::ADC_CHANNEL_0; return 1; // OK + case GPIO_NUM_12: *adc_channel = esp_i2s::ADC_CHANNEL_1; return 1; // OK + case GPIO_NUM_13: *adc_channel = esp_i2s::ADC_CHANNEL_2; return 1; // OK + case GPIO_NUM_14: *adc_channel = esp_i2s::ADC_CHANNEL_3; return 1; // OK + case GPIO_NUM_15: *adc_channel = esp_i2s::ADC_CHANNEL_4; return 1; // OK + case GPIO_NUM_16: *adc_channel = esp_i2s::ADC_CHANNEL_5; return 1; // OK + case GPIO_NUM_17: *adc_channel = esp_i2s::ADC_CHANNEL_6; return 1; // OK + case GPIO_NUM_18: *adc_channel = esp_i2s::ADC_CHANNEL_7; return 1; // OK + case GPIO_NUM_19: *adc_channel = esp_i2s::ADC_CHANNEL_8; return 1; // OK + case GPIO_NUM_20: *adc_channel = esp_i2s::ADC_CHANNEL_9; return 1; // OK +#endif + +#if (CONFIG_IDF_TARGET_ESP32C3 || CONFIG_IDF_TARGET_ESP32H2) + case GPIO_NUM_0: *adc_channel = esp_i2s::ADC_CHANNEL_0; return 1; // OK + case GPIO_NUM_1: *adc_channel = esp_i2s::ADC_CHANNEL_1; return 1; // OK + case GPIO_NUM_2: *adc_channel = esp_i2s::ADC_CHANNEL_2; return 1; // OK + case GPIO_NUM_3: *adc_channel = esp_i2s::ADC_CHANNEL_3; return 1; // OK + case GPIO_NUM_4: *adc_channel = esp_i2s::ADC_CHANNEL_4; return 1; // OK + case GPIO_NUM_5: *adc_channel = esp_i2s::ADC_CHANNEL_0; return 1; // OK +#endif + default: + log_e("GPIO %d not usable for ADC!", gpio_num); + log_i("Please refer to documentation https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/gpio.html"); + return 0; // ERR + } +} +#endif // SOC_I2S_SUPPORTS_ADC_DAC + +#if I2S_INTERFACES_COUNT > 0 + I2SClass I2S(I2S_DEVICE, I2S_CLOCK_GENERATOR, PIN_I2S_SD, PIN_I2S_SCK, PIN_I2S_FS); // default - half duplex +#endif + +#if I2S_INTERFACES_COUNT > 1 + // TODO set default pins for second module + //I2SClass I2S1(I2S_DEVICE+1, I2S_CLOCK_GENERATOR, PIN_I2S_SD, PIN_I2S_SCK, PIN_I2S_FS); // default - half duplex +#endif diff --git a/libraries/I2S/src/I2S.h b/libraries/I2S/src/I2S.h new file mode 100644 index 00000000000..623fa8917b4 --- /dev/null +++ b/libraries/I2S/src/I2S.h @@ -0,0 +1,195 @@ +/* + Copyright (c) 2016 Arduino LLC. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + See the GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef _I2S_H_INCLUDED +#define _I2S_H_INCLUDED + +#include +#include "freertos/ringbuf.h" + +namespace esp_i2s { + #include "driver/i2s.h" // ESP specific i2s driver +} + +// Default pins +#ifndef PIN_I2S_SCK + #define PIN_I2S_SCK 14 +#endif + +#ifndef PIN_I2S_FS + #if CONFIG_IDF_TARGET_ESP32S2 + #define PIN_I2S_FS 27 + #else + #define PIN_I2S_FS 25 + #endif +#endif + +#ifndef PIN_I2S_SD + #define PIN_I2S_SD 26 +#endif + +#ifndef PIN_I2S_SD_OUT + #define PIN_I2S_SD_OUT 26 +#endif + +#ifndef PIN_I2S_SD_IN + #define PIN_I2S_SD_IN 35 // Pin 35 is only input! +#endif + +typedef enum { + I2S_PHILIPS_MODE, + I2S_RIGHT_JUSTIFIED_MODE, + I2S_LEFT_JUSTIFIED_MODE, + ADC_DAC_MODE, + PDM_STEREO_MODE, + PDM_MONO_MODE +} i2s_mode_t; + +class I2SClass : public Stream +{ +public: + // The device index and pins must map to the "COM" pads in Table 6-1 of the datasheet + I2SClass(uint8_t deviceIndex, uint8_t clockGenerator, uint8_t sdPin, uint8_t sckPin, uint8_t fsPin); + + // Init in MASTER mode: the SCK and FS pins are driven as outputs using the sample rate + int begin(int mode, int sampleRate, int bitsPerSample); + + // Init in SLAVE mode: the SCK and FS pins are inputs, other side controls sample rate + int begin(int mode, int bitsPerSample); + + // change pin setup and mode (default is Half Duplex) + // Can be called only on initialized object (after begin) + int setSckPin(int sckPin); + int setFsPin(int fsPin); + int setDataPin(int sdPin); // shared data pin for simplex + int setDataOutPin(int outSdPin); + int setDataInPin(int inSdPin); + + int setAllPins(); + int setAllPins(int sckPin, int fsPin, int sdPin, int outSdPin, int inSdPin); + + int getSckPin(); + int getFsPin(); + int getDataPin(); + int getDataOutPin(); + int getDataInPin(); + + int setDuplex(); + int setSimplex(); + int isDuplex(); + + void end(); + + // from Stream + virtual int available(); + virtual int read(); + virtual int peek(); + virtual void flush(); + + // from Print + virtual size_t write(uint8_t); + virtual size_t write(const uint8_t *buffer, size_t size); + + virtual int availableForWrite(); + + int read(void* buffer, size_t size); + + //size_t write(int); + size_t write(int32_t); + size_t write(const void *buffer, size_t size); + size_t write_blocking(const void *buffer, size_t size); + size_t write_nonblocking(const void *buffer, size_t size); + + void onTransmit(void(*)(void)); + void onReceive(void(*)(void)); + + int setBufferSize(int bufferSize); + int getBufferSize(); +private: + #if (SOC_I2S_SUPPORTS_ADC && SOC_I2S_SUPPORTS_DAC) + int _gpioToAdcUnit(gpio_num_t gpio_num, esp_i2s::adc_unit_t* adc_unit); + int _gpioToAdcChannel(gpio_num_t gpio_num, esp_i2s::adc_channel_t* adc_channel); + #endif + int begin(int mode, int sampleRate, int bitsPerSample, bool driveClock); + + int _enableTransmitter(); + int _enableReceiver(); + void _onTransferComplete(); + + int _createCallbackTask(); + + static void onDmaTransferComplete(void*); + int _installDriver(); + void _uninstallDriver(); + void _setSckPin(int sckPin); + void _setFsPin(int fsPin); + void _setDataPin(int sdPin); + void _setDataOutPin(int outSdPin); + void _setDataInPin(int inSdPin); + int _applyPinSetting(); + +private: + typedef enum { + I2S_STATE_IDLE, + I2S_STATE_TRANSMITTER, + I2S_STATE_RECEIVER, + I2S_STATE_DUPLEX + } i2s_state_t; + + int _deviceIndex; + int _sdPin; + int _inSdPin; + int _outSdPin; + int _sckPin; + int _fsPin; + + i2s_state_t _state; + int _bitsPerSample; + uint32_t _sampleRate; + int _mode; + + uint16_t _buffer_byte_size; + + bool _driverInstalled; // Is IDF I2S driver installed? + bool _initialized; // Is everything initialized (callback task, I2S driver, ring buffers)? + TaskHandle_t _callbackTaskHandle; + QueueHandle_t _i2sEventQueue; + SemaphoreHandle_t _i2s_general_mutex; + RingbufHandle_t _input_ring_buffer; + RingbufHandle_t _output_ring_buffer; + int _i2s_dma_buffer_size; + bool _driveClock; + uint32_t _peek_buff; + bool _peek_buff_valid; + + void _tx_done_routine(uint8_t* prev_item); + void _rx_done_routine(); + + uint16_t _nesting_counter; + void _take_if_not_holding(); + void _give_if_top_call(); + void _post_read_data_fix(void *input, size_t *size); + void _fix_and_write(void *output, size_t size, size_t *bytes_written = NULL, size_t *actual_bytes_written = NULL); + + void (*_onTransmit)(void); + void (*_onReceive)(void); +}; + +extern I2SClass I2S; + +#endif diff --git a/libraries/WiFi/src/WiFiGeneric.cpp b/libraries/WiFi/src/WiFiGeneric.cpp index 3bcaececc7a..5dfdacdc05d 100644 --- a/libraries/WiFi/src/WiFiGeneric.cpp +++ b/libraries/WiFi/src/WiFiGeneric.cpp @@ -1192,6 +1192,94 @@ bool WiFiGenericClass::initiateFTM(uint8_t frm_count, uint16_t burst_period, uin return true; } +/** + * Configure Dual antenna. + * @param gpio_ant1 Configure the GPIO number for the antenna 1 connected to the RF switch (default GPIO2 on ESP32-WROOM-DA) + * @param gpio_ant2 Configure the GPIO number for the antenna 2 connected to the RF switch (default GPIO25 on ESP32-WROOM-DA) + * @param rx_mode Set the RX antenna mode. See wifi_rx_ant_t for the options. + * @param tx_mode Set the TX antenna mode. See wifi_tx_ant_t for the options. + * @return true on success + */ +bool WiFiGenericClass::setDualAntennaConfig(uint8_t gpio_ant1, uint8_t gpio_ant2, wifi_rx_ant_t rx_mode, wifi_tx_ant_t tx_mode) { + + wifi_ant_gpio_config_t wifi_ant_io; + + if (ESP_OK != esp_wifi_get_ant_gpio(&wifi_ant_io)) { + log_e("Failed to get antenna configuration"); + return false; + } + + wifi_ant_io.gpio_cfg[0].gpio_num = gpio_ant1; + wifi_ant_io.gpio_cfg[0].gpio_select = 1; + wifi_ant_io.gpio_cfg[1].gpio_num = gpio_ant2; + wifi_ant_io.gpio_cfg[1].gpio_select = 1; + + if (ESP_OK != esp_wifi_set_ant_gpio(&wifi_ant_io)) { + log_e("Failed to set antenna GPIO configuration"); + return false; + } + + // Set antenna default configuration + wifi_ant_config_t ant_config = { + .rx_ant_mode = WIFI_ANT_MODE_AUTO, + .tx_ant_mode = WIFI_ANT_MODE_AUTO, + .enabled_ant0 = 0, + .enabled_ant1 = 1, + }; + + switch (rx_mode) + { + case WIFI_RX_ANT0: + ant_config.rx_ant_mode = WIFI_ANT_MODE_ANT0; + break; + case WIFI_RX_ANT1: + ant_config.rx_ant_mode = WIFI_ANT_MODE_ANT1; + break; + case WIFI_RX_ANT_AUTO: + log_i("TX Antenna will be automatically selected"); + ant_config.rx_ant_default = WIFI_ANT_ANT0; + ant_config.rx_ant_mode = WIFI_ANT_MODE_AUTO; + // Force TX for AUTO if RX is AUTO + ant_config.tx_ant_mode = WIFI_ANT_MODE_AUTO; + goto set_ant; + break; + default: + log_e("Invalid default antenna! Falling back to AUTO"); + ant_config.rx_ant_mode = WIFI_ANT_MODE_AUTO; + break; + } + + switch (tx_mode) + { + case WIFI_TX_ANT0: + ant_config.tx_ant_mode = WIFI_ANT_MODE_ANT0; + break; + case WIFI_TX_ANT1: + ant_config.tx_ant_mode = WIFI_ANT_MODE_ANT1; + break; + case WIFI_TX_ANT_AUTO: + log_i("RX Antenna will be automatically selected"); + ant_config.rx_ant_default = WIFI_ANT_ANT0; + ant_config.tx_ant_mode = WIFI_ANT_MODE_AUTO; + // Force RX for AUTO if RX is AUTO + ant_config.rx_ant_mode = WIFI_ANT_MODE_AUTO; + break; + default: + log_e("Invalid default antenna! Falling back to AUTO"); + ant_config.rx_ant_default = WIFI_ANT_ANT0; + ant_config.tx_ant_mode = WIFI_ANT_MODE_AUTO; + break; + } + +set_ant: + if (ESP_OK != esp_wifi_set_ant(&ant_config)) { + log_e("Failed to set antenna configuration"); + return false; + } + + return true; +} + // ----------------------------------------------------------------------------------------------------------------------- // ------------------------------------------------ Generic Network function --------------------------------------------- // ----------------------------------------------------------------------------------------------------------------------- diff --git a/libraries/WiFi/src/WiFiGeneric.h b/libraries/WiFi/src/WiFiGeneric.h index 7079c032993..f8a1bb77d37 100644 --- a/libraries/WiFi/src/WiFiGeneric.h +++ b/libraries/WiFi/src/WiFiGeneric.h @@ -139,6 +139,18 @@ static const int WIFI_SCAN_DONE_BIT= BIT12; static const int WIFI_DNS_IDLE_BIT = BIT13; static const int WIFI_DNS_DONE_BIT = BIT14; +typedef enum { + WIFI_RX_ANT0 = 0, + WIFI_RX_ANT1, + WIFI_RX_ANT_AUTO +} wifi_rx_ant_t; + +typedef enum { + WIFI_TX_ANT0 = 0, + WIFI_TX_ANT1, + WIFI_TX_ANT_AUTO +} wifi_tx_ant_t; + class WiFiGenericClass { public: @@ -174,6 +186,8 @@ class WiFiGenericClass bool initiateFTM(uint8_t frm_count=16, uint16_t burst_period=2, uint8_t channel=1, const uint8_t * mac=NULL); + bool setDualAntennaConfig(uint8_t gpio_ant1, uint8_t gpio_ant2, wifi_rx_ant_t rx_mode, wifi_tx_ant_t tx_mode); + static const char * getHostname(); static bool setHostname(const char * hostname); static bool hostname(const String& aHostname) { return setHostname(aHostname.c_str()); } diff --git a/variants/adafruit_feather_esp32_v2/pins_arduino.h b/variants/adafruit_feather_esp32_v2/pins_arduino.h new file mode 100644 index 00000000000..2bfaf63b7aa --- /dev/null +++ b/variants/adafruit_feather_esp32_v2/pins_arduino.h @@ -0,0 +1,73 @@ +#ifndef Pins_Arduino_h +#define Pins_Arduino_h + +#include + +#define EXTERNAL_NUM_INTERRUPTS 16 +#define NUM_DIGITAL_PINS 40 +#define NUM_ANALOG_INPUTS 16 + +#define analogInputToDigitalPin(p) (((p)<20)?(esp32_adc2gpio[(p)]):-1) +#define digitalPinToInterrupt(p) (((p)<40)?(p):-1) +#define digitalPinHasPWM(p) (p < 34) + +static const uint8_t LED_BUILTIN = 13; +#define BUILTIN_LED LED_BUILTIN // backward compatibility +#define LED_BUILTIN LED_BUILTIN + +static const uint8_t TX = 7; +static const uint8_t RX = 8; +static const uint8_t TX1 = 7; +static const uint8_t RX1 = 8; + +static const uint8_t SDA = 22; +static const uint8_t SCL = 20; + +static const uint8_t SS = 33; +static const uint8_t MOSI = 19; +static const uint8_t MISO = 21; +static const uint8_t SCK = 5; + +// mapping to match other feathers and also in order +static const uint8_t A0 = 26; +static const uint8_t A1 = 25; +static const uint8_t A2 = 34; +static const uint8_t A3 = 39; +static const uint8_t A4 = 36; +static const uint8_t A5 = 4; +static const uint8_t A6 = 14; +static const uint8_t A7 = 32; +static const uint8_t A8 = 15; +static const uint8_t A9 = 33; +static const uint8_t A10 = 27; +static const uint8_t A11 = 12; +static const uint8_t A12 = 13; + +// vbat measure +static const uint8_t BATT_MONITOR = 35; +static const uint8_t A13 = 35; + +// internal switch +static const uint8_t BUTTON = 38; + +// Neopixel +static const uint8_t NEOPIXEL_PIN = 0; + +// Neopixel & I2C power +static const uint8_t NEOPIXEL_I2C_POWER = 2; + +static const uint8_t T0 = 4; +static const uint8_t T1 = 0; +static const uint8_t T2 = 2; +static const uint8_t T3 = 15; +static const uint8_t T4 = 13; +static const uint8_t T5 = 12; +static const uint8_t T6 = 14; +static const uint8_t T7 = 27; +static const uint8_t T8 = 33; +static const uint8_t T9 = 32; + +static const uint8_t DAC1 = 25; +static const uint8_t DAC2 = 26; + +#endif /* Pins_Arduino_h */ diff --git a/variants/adafruit_feather_esp32_v2/variant.cpp b/variants/adafruit_feather_esp32_v2/variant.cpp new file mode 100644 index 00000000000..9345f6058a6 --- /dev/null +++ b/variants/adafruit_feather_esp32_v2/variant.cpp @@ -0,0 +1,40 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2021 Ha Thach (tinyusb.org) 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 "esp32-hal-gpio.h" +#include "pins_arduino.h" + +extern "C" { + +// Initialize variant/board, called before setup() +void initVariant(void) +{ + // This board has a power control pin, and we must set it to output and high + // in order to enable the NeoPixels & I2C + pinMode(NEOPIXEL_I2C_POWER, OUTPUT); + digitalWrite(NEOPIXEL_I2C_POWER, HIGH); +} + +} diff --git a/variants/adafruit_feather_esp32s2/pins_arduino.h b/variants/adafruit_feather_esp32s2/pins_arduino.h index 4e5e13de6e2..bde8d973d8f 100644 --- a/variants/adafruit_feather_esp32s2/pins_arduino.h +++ b/variants/adafruit_feather_esp32s2/pins_arduino.h @@ -26,6 +26,7 @@ #define NEOPIXEL_POWER 21 // power pin #define NEOPIXEL_POWER_ON HIGH // power pin state when on #define I2C_POWER 7 // I2C power pin +#define PIN_I2C_POWER 7 // I2C power pin static const uint8_t SDA = 3; static const uint8_t SCL = 4; diff --git a/variants/adafruit_qtpy_esp32/pins_arduino.h b/variants/adafruit_qtpy_esp32/pins_arduino.h index 72a5606c5d6..091554a08dd 100644 --- a/variants/adafruit_qtpy_esp32/pins_arduino.h +++ b/variants/adafruit_qtpy_esp32/pins_arduino.h @@ -11,14 +11,14 @@ #define digitalPinToInterrupt(p) (((p)<40)?(p):-1) #define digitalPinHasPWM(p) (p < 34) -static const uint8_t NEOPIXEL = 5; +static const uint8_t PIN_NEOPIXEL = 5; static const uint8_t NEOPIXEL_POWER = 8; static const uint8_t TX = 32; static const uint8_t RX = 7; -static const uint8_t TX1 = 32; -static const uint8_t RX1 = 7; +#define TX1 32 +#define RX1 7 static const uint8_t SDA = 25; static const uint8_t SCL = 33; @@ -43,7 +43,7 @@ static const uint8_t A8 = 14; static const uint8_t A9 = 12; static const uint8_t A10 = 13; -static const uint8_t SWITCH = 0; +static const uint8_t BUTTON = 0; static const uint8_t T0 = 4; static const uint8_t T3 = 15; diff --git a/variants/adafruit_qtpy_esp32/variant.cpp b/variants/adafruit_qtpy_esp32/variant.cpp new file mode 100644 index 00000000000..726ec8fa483 --- /dev/null +++ b/variants/adafruit_qtpy_esp32/variant.cpp @@ -0,0 +1,40 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2021 Ha Thach (tinyusb.org) 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 "esp32-hal-gpio.h" +#include "pins_arduino.h" + +extern "C" { + +// Initialize variant/board, called before setup() +void initVariant(void) +{ + // This board has a power control pin, and we must set it to output and high + // in order to enable the NeoPixels. + pinMode(NEOPIXEL_POWER, OUTPUT); + digitalWrite(NEOPIXEL_POWER, HIGH); +} + +} diff --git a/variants/adafruit_qtpy_esp32c3/pins_arduino.h b/variants/adafruit_qtpy_esp32c3/pins_arduino.h new file mode 100644 index 00000000000..61d1f49492b --- /dev/null +++ b/variants/adafruit_qtpy_esp32c3/pins_arduino.h @@ -0,0 +1,34 @@ +#ifndef Pins_Arduino_h +#define Pins_Arduino_h + +#include + +#define EXTERNAL_NUM_INTERRUPTS 22 +#define NUM_DIGITAL_PINS 22 +#define NUM_ANALOG_INPUTS 6 + +#define analogInputToDigitalPin(p) (((p)