diff options
| author | Scott Shawcroft <scott.shawcroft@gmail.com> | 2017-05-24 10:43:32 -0700 |
|---|---|---|
| committer | Scott Shawcroft <scott@chickadee.tech> | 2017-07-28 12:12:38 -0700 |
| commit | 557ceded00de20d2070e1397d3dec322f753d1e6 (patch) | |
| tree | 01535b9ba963fedb782be8041078055c04c9c185 /atmel-samd | |
| parent | 48375ba954b387a1182d8a8bb1676fe2059bd183 (diff) | |
atmel-samd: Introduce audiobusio.PDMIn for recording audio from PDM
microphones.
Diffstat (limited to 'atmel-samd')
| -rw-r--r-- | atmel-samd/Makefile | 4 | ||||
| -rw-r--r-- | atmel-samd/asf/sam0/drivers/i2s/i2s.c | 750 | ||||
| -rw-r--r-- | atmel-samd/asf/sam0/drivers/i2s/i2s.h | 1386 | ||||
| -rw-r--r-- | atmel-samd/asf/sam0/drivers/i2s/i2s_callback.c | 392 | ||||
| -rw-r--r-- | atmel-samd/asf/sam0/drivers/i2s/i2s_callback.h | 234 | ||||
| -rw-r--r-- | atmel-samd/boards/circuitplayground_express/pins.c | 4 | ||||
| -rw-r--r-- | atmel-samd/common-hal/audiobusio/PDMIn.c | 320 | ||||
| -rw-r--r-- | atmel-samd/common-hal/audiobusio/PDMIn.h | 53 | ||||
| -rw-r--r-- | atmel-samd/common-hal/audiobusio/__init__.c | 1 | ||||
| -rw-r--r-- | atmel-samd/common-hal/audioio/AudioOut.c | 103 | ||||
| -rw-r--r-- | atmel-samd/main.c | 10 | ||||
| -rw-r--r-- | atmel-samd/mpconfigport.h | 6 | ||||
| -rw-r--r-- | atmel-samd/shared_dma.c | 99 | ||||
| -rw-r--r-- | atmel-samd/shared_dma.h | 6 | ||||
| -rw-r--r-- | atmel-samd/spi_flash.c | 60 |
15 files changed, 3318 insertions, 110 deletions
diff --git a/atmel-samd/Makefile b/atmel-samd/Makefile index ed5981d09..7111bee09 100644 --- a/atmel-samd/Makefile +++ b/atmel-samd/Makefile @@ -120,6 +120,7 @@ CFLAGS_CORTEX_M0 = \ -DTCC_ASYNC=false \ -DADC_CALLBACK_MODE=false \ -DEVENTS_INTERRUPT_HOOKS_MODE=false \ + -DI2S_CALLBACK_MODE=false \ -DTC_ASYNC=true \ -DUSB_DEVICE_LPM_SUPPORT \ -DCIRCUITPY_CANARY_WORD=0xADAF00 \ @@ -162,6 +163,7 @@ SRC_ASF = $(addprefix asf/sam0/,\ drivers/events/events_sam_d_r/events.c \ drivers/extint/extint_callback.c \ drivers/extint/extint_sam_d_r/extint.c \ + drivers/i2s/i2s.c \ drivers/nvm/nvm.c \ drivers/port/port.c \ drivers/sercom/i2c/i2c_sam0/i2c_master.c \ @@ -233,6 +235,8 @@ SRC_COMMON_HAL = \ analogio/__init__.c \ analogio/AnalogIn.c \ analogio/AnalogOut.c \ + audiobusio/__init__.c \ + audiobusio/PDMIn.c \ audioio/__init__.c \ audioio/AudioOut.c \ board/__init__.c \ diff --git a/atmel-samd/asf/sam0/drivers/i2s/i2s.c b/atmel-samd/asf/sam0/drivers/i2s/i2s.c new file mode 100644 index 000000000..bbf04620b --- /dev/null +++ b/atmel-samd/asf/sam0/drivers/i2s/i2s.c @@ -0,0 +1,750 @@ +/** + * \file + * + * \brief SAM I2S - Inter-IC Sound Controller + * + * Copyright (C) 2014-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit <a href="http://www.atmel.com/design-support/">Atmel Support</a> + */ + +#include "i2s.h" + +/** + * \brief Initializes a hardware I<SUP>2</SUP>S module instance + * + * Enables the clock and initialize the I<SUP>2</SUP>S module. + * + * \param[in,out] module_inst Pointer to the software module instance struct + * \param[in] hw Pointer to the TCC hardware module + * + * \return Status of the initialization procedure. + * + * \retval STATUS_OK The module was initialized successfully + * \retval STATUS_BUSY Hardware module was busy when the + * initialization procedure was attempted + * \retval STATUS_ERR_DENIED Hardware module was already enabled + */ +enum status_code i2s_init( + struct i2s_module *const module_inst, + I2s *hw) +{ + Assert(module_inst); + Assert(hw); + + /* Enable the user interface clock in the PM */ + system_apb_clock_set_mask(SYSTEM_CLOCK_APB_APBC, PM_APBCMASK_I2S); + + /* Status check */ + uint32_t ctrla; + ctrla = module_inst->hw->CTRLA.reg; + if (ctrla & I2S_CTRLA_ENABLE) { + if (ctrla & (I2S_CTRLA_SEREN1 | + I2S_CTRLA_SEREN0 | I2S_CTRLA_CKEN1 | I2S_CTRLA_CKEN0)) { + return STATUS_BUSY; + } else { + return STATUS_ERR_DENIED; + } + } + + /* Initialize module */ + module_inst->hw = hw; + + /* Initialize serializers */ +#if I2S_CALLBACK_MODE == true + int i, j; + for (i = 0; i < 2; i ++) { + for (j = 0; j < I2S_SERIALIZER_CALLBACK_N; j ++) { + module_inst->serializer[i].callback[j] = NULL; + } + module_inst->serializer[i].registered_callback_mask = 0; + module_inst->serializer[i].enabled_callback_mask = 0; + + module_inst->serializer[i].job_buffer = NULL; + module_inst->serializer[i].job_status = STATUS_OK; + module_inst->serializer[i].requested_words = 0; + module_inst->serializer[i].transferred_words = 0; + + module_inst->serializer[i].mode = I2S_SERIALIZER_RECEIVE; + module_inst->serializer[i].data_size = I2S_DATA_SIZE_32BIT; + } + + _i2s_instances[0] = module_inst; + + system_interrupt_enable(SYSTEM_INTERRUPT_MODULE_I2S); +#endif + + return STATUS_OK; +} + + +/** + * \brief Configure specified I<SUP>2</SUP>S clock unit + * + * Enables the clock and initialize the clock unit, based on the given + * configurations. + * + * \param[in,out] module_inst Pointer to the software module instance struct + * \param[in] clock_unit I<SUP>2</SUP>S clock unit to initialize and configure + * \param[in] config Pointer to the I<SUP>2</SUP>S clock unit configuration + * options struct + * + * \return Status of the configuration procedure. + * + * \retval STATUS_OK The module was initialized successfully + * \retval STATUS_BUSY Hardware module was busy when the + * configuration procedure was attempted + * \retval STATUS_ERR_DENIED Hardware module was already enabled + * \retval STATUS_ERR_INVALID_ARG Invalid divider value or + * MCK direction setting conflict + */ +enum status_code i2s_clock_unit_set_config( + struct i2s_module *const module_inst, + const enum i2s_clock_unit clock_unit, + const struct i2s_clock_unit_config *config) +{ + Assert(module_inst); + Assert(module_inst->hw); + Assert(clock_unit < I2S_CLOCK_UNIT_N); + Assert(config); + + /* Status check */ + uint32_t ctrla, syncbusy; + syncbusy = module_inst->hw->SYNCBUSY.reg; + ctrla = module_inst->hw->CTRLA.reg; + + /* Busy ? */ + if (syncbusy & (I2S_SYNCBUSY_CKEN0 << clock_unit)) { + return STATUS_BUSY; + } + /* Already enabled ? */ + if (ctrla & (I2S_CTRLA_CKEN0 << clock_unit)) { + return STATUS_ERR_DENIED; + } + /* Parameter check */ + if (config->clock.mck_src && config->clock.mck_out_enable) { + return STATUS_ERR_INVALID_ARG; + } + + /* Initialize Clock Unit */ + uint32_t clkctrl = + (config->clock.mck_out_invert ? I2S_CLKCTRL_MCKOUTINV : 0) | + (config->clock.sck_out_invert ? I2S_CLKCTRL_SCKOUTINV : 0) | + (config->frame.frame_sync.invert_out ? I2S_CLKCTRL_FSOUTINV : 0) | + (config->clock.mck_out_enable ? I2S_CLKCTRL_MCKEN : 0) | + (config->clock.mck_src ? I2S_CLKCTRL_MCKSEL : 0) | + (config->clock.sck_src ? I2S_CLKCTRL_SCKSEL : 0) | + (config->frame.frame_sync.invert_use ? I2S_CLKCTRL_FSINV : 0) | + (config->frame.frame_sync.source ? I2S_CLKCTRL_FSSEL : 0) | + (config->frame.data_delay ? I2S_CLKCTRL_BITDELAY : 0); + + uint8_t div_val = config->clock.mck_out_div; + if ((div_val > 0x21) || (div_val == 0)) { + return STATUS_ERR_INVALID_ARG; + } else { + div_val --; + } + clkctrl |= I2S_CLKCTRL_MCKOUTDIV(div_val); + + div_val = config->clock.sck_div; + if ((div_val > 0x21) || (div_val == 0)) { + return STATUS_ERR_INVALID_ARG; + } else { + div_val --; + } + clkctrl |= I2S_CLKCTRL_MCKDIV(div_val); + + uint8_t number_slots = config->frame.number_slots; + if (number_slots > 8) { + return STATUS_ERR_INVALID_ARG; + } else if (number_slots > 0) { + number_slots --; + } + clkctrl |= + I2S_CLKCTRL_NBSLOTS(number_slots) | + I2S_CLKCTRL_FSWIDTH(config->frame.frame_sync.width) | + I2S_CLKCTRL_SLOTSIZE(config->frame.slot_size); + + /* Write clock unit configurations */ + module_inst->hw->CLKCTRL[clock_unit].reg = clkctrl; + + /* Select general clock source */ + const uint8_t i2s_gclk_ids[2] = {I2S_GCLK_ID_0, I2S_GCLK_ID_1}; + struct system_gclk_chan_config gclk_chan_config; + system_gclk_chan_get_config_defaults(&gclk_chan_config); + gclk_chan_config.source_generator = config->clock.gclk_src; + system_gclk_chan_set_config(i2s_gclk_ids[clock_unit], &gclk_chan_config); + system_gclk_chan_enable(i2s_gclk_ids[clock_unit]); + + /* Initialize pins */ + struct system_pinmux_config pin_config; + system_pinmux_get_config_defaults(&pin_config); + if (config->mck_pin.enable) { + pin_config.mux_position = config->mck_pin.mux; + system_pinmux_pin_set_config(config->mck_pin.gpio, &pin_config); + } + if (config->sck_pin.enable) { + pin_config.mux_position = config->sck_pin.mux; + system_pinmux_pin_set_config(config->sck_pin.gpio, &pin_config); + } + if (config->fs_pin.enable) { + pin_config.mux_position = config->fs_pin.mux; + system_pinmux_pin_set_config(config->fs_pin.gpio, &pin_config); + } + + return STATUS_OK; +} + + +/** + * \brief Configure specified I<SUP>2</SUP>S serializer + * + * Enables the clock and initialize the serializer, based on the given + * configurations. + * + * \param[in,out] module_inst Pointer to the software module instance struct + * \param[in] serializer I<SUP>2</SUP>S serializer to initialize and configure + * \param[in] config Pointer to the I<SUP>2</SUP>S serializer configuration + * options struct + * + * \return Status of the configuration procedure. + * + * \retval STATUS_OK The module was initialized successfully + * \retval STATUS_BUSY Hardware module was busy when the + * configuration procedure was attempted + * \retval STATUS_ERR_DENIED Hardware module was already enabled + */ +enum status_code i2s_serializer_set_config( + struct i2s_module *const module_inst, + const enum i2s_serializer serializer, + const struct i2s_serializer_config *config) +{ + Assert(module_inst); + Assert(module_inst->hw); + Assert(serializer < I2S_SERIALIZER_N); + Assert(config); + + /* Status check */ + uint32_t ctrla, syncbusy; + syncbusy = module_inst->hw->SYNCBUSY.reg; + ctrla = module_inst->hw->CTRLA.reg; + + /* Busy ? */ + if (syncbusy & ((I2S_SYNCBUSY_SEREN0 | I2S_SYNCBUSY_DATA0) << serializer)) { + return STATUS_BUSY; + } + /* Already enabled ? */ + if (ctrla & (I2S_CTRLA_CKEN0 << serializer)) { + return STATUS_ERR_DENIED; + } + + /* Initialize Serializer */ + uint32_t serctrl = + (config->loop_back ? I2S_SERCTRL_RXLOOP : 0) | + (config->dma_usage ? I2S_SERCTRL_DMA : 0) | + (config->mono_mode ? I2S_SERCTRL_MONO : 0) | + (config->disable_data_slot[7] ? I2S_SERCTRL_SLOTDIS7 : 0) | + (config->disable_data_slot[6] ? I2S_SERCTRL_SLOTDIS6 : 0) | + (config->disable_data_slot[5] ? I2S_SERCTRL_SLOTDIS5 : 0) | + (config->disable_data_slot[4] ? I2S_SERCTRL_SLOTDIS4 : 0) | + (config->disable_data_slot[3] ? I2S_SERCTRL_SLOTDIS3 : 0) | + (config->disable_data_slot[2] ? I2S_SERCTRL_SLOTDIS2 : 0) | + (config->disable_data_slot[1] ? I2S_SERCTRL_SLOTDIS1 : 0) | + (config->disable_data_slot[0] ? I2S_SERCTRL_SLOTDIS0 : 0) | + (config->transfer_lsb_first ? I2S_SERCTRL_BITREV : 0) | + (config->data_adjust_left_in_word ? I2S_SERCTRL_WORDADJ : 0) | + (config->data_adjust_left_in_slot ? I2S_SERCTRL_SLOTADJ : 0) | + (config->data_padding ? I2S_SERCTRL_TXSAME : 0); + + if (config->clock_unit < I2S_CLOCK_UNIT_N) { + serctrl |= (config->clock_unit ? I2S_SERCTRL_CLKSEL : 0); + } else { + return STATUS_ERR_INVALID_ARG; + } + + serctrl |= + I2S_SERCTRL_SERMODE(config->mode) | + I2S_SERCTRL_TXDEFAULT(config->line_default_state) | + I2S_SERCTRL_DATASIZE(config->data_size) | + I2S_SERCTRL_EXTEND(config->bit_padding); + + /* Write Serializer configuration */ + module_inst->hw->SERCTRL[serializer].reg = serctrl; + + /* Initialize pins */ + struct system_pinmux_config pin_config; + system_pinmux_get_config_defaults(&pin_config); + if (config->data_pin.enable) { + pin_config.mux_position = config->data_pin.mux; + system_pinmux_pin_set_config(config->data_pin.gpio, &pin_config); + } + + /* Save configure */ + module_inst->serializer[serializer].mode = config->mode; + module_inst->serializer[serializer].data_size = config->data_size; + + return STATUS_OK; +} + + + +/** + * \brief Retrieves the current module status. + * + * Retrieves the status of the module, giving overall state information. + * + * \param[in] module_inst Pointer to the I<SUP>2</SUP>S software instance struct + * + * \return Bitmask of \c I2S_STATUS_* flags. + * + * \retval I2S_STATUS_SYNC_BUSY Module is busy synchronization + * \retval I2S_STATUS_TRANSMIT_UNDERRUN(x) Serializer x (0~1) is underrun + * \retval I2S_STATUS_TRANSMIT_READY(x) Serializer x (0~1) is ready to + * transmit new data word + * \retval I2S_STATUS_RECEIVE_OVERRUN(x) Serializer x (0~1) is overrun + * \retval I2S_STATUS_RECEIVE_READY(x) Serializer x (0~1) has data ready to + * read + */ +uint32_t i2s_get_status( + const struct i2s_module *const module_inst) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + uint32_t intflag = module_inst->hw->INTFLAG.reg; + uint32_t status; + if (module_inst->hw->SYNCBUSY.reg) { + status = I2S_STATUS_SYNC_BUSY; + } else { + status = 0; + } + if (intflag & I2S_INTFLAG_TXUR0) { + status |= I2S_STATUS_TRANSMIT_UNDERRUN(0); + } + if (intflag & I2S_INTFLAG_TXUR1) { + status |= I2S_STATUS_TRANSMIT_UNDERRUN(1); + } + if ((intflag & I2S_INTFLAG_TXRDY0) && + !module_inst->hw->SYNCBUSY.bit.DATA0) { + status |= I2S_STATUS_TRANSMIT_READY(0); + } + if ((intflag & I2S_INTFLAG_TXRDY1) && + !module_inst->hw->SYNCBUSY.bit.DATA1) { + status |= I2S_STATUS_TRANSMIT_READY(1); + } + if (intflag & I2S_INTFLAG_RXOR0) { + status |= I2S_STATUS_RECEIVE_OVERRUN(0); + } + if (intflag & I2S_INTFLAG_RXOR1) { + status |= I2S_STATUS_RECEIVE_OVERRUN(1); + } + if (intflag & I2S_INTFLAG_RXRDY0) { + status |= I2S_STATUS_RECEIVE_READY(0); + } + if (intflag & I2S_INTFLAG_RXRDY1) { + status |= I2S_STATUS_RECEIVE_READY(1); + } + return status; +} + +/** + * \brief Clears a module status flags. + * + * Clears the given status flags of the module. + * + * \param[in] module_inst Pointer to the I<SUP>2</SUP>S software instance struct + * \param[in] status Bitmask of \c I2S_STATUS_* flags to clear + */ +void i2s_clear_status( + const struct i2s_module *const module_inst, + uint32_t status) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + uint32_t intflag = 0; + + if (status & I2S_STATUS_TRANSMIT_UNDERRUN(0)) { + intflag = I2S_INTFLAG_TXUR0; + } + if (status & I2S_STATUS_TRANSMIT_UNDERRUN(1)) { + intflag = I2S_INTFLAG_TXUR1; + } + if (status & I2S_STATUS_TRANSMIT_READY(0)) { + intflag = I2S_INTFLAG_TXRDY0; + } + if (status & I2S_STATUS_TRANSMIT_READY(1)) { + intflag = I2S_INTFLAG_TXRDY1; + } + if (status & I2S_STATUS_RECEIVE_OVERRUN(0)) { + intflag = I2S_INTFLAG_RXOR0; + } + if (status & I2S_STATUS_RECEIVE_OVERRUN(1)) { + intflag = I2S_INTFLAG_RXOR1; + } + if (status & I2S_STATUS_RECEIVE_READY(0)) { + intflag = I2S_INTFLAG_RXRDY0; + } + if (status & I2S_STATUS_RECEIVE_READY(1)) { + intflag = I2S_INTFLAG_RXRDY1; + } + module_inst->hw->INTFLAG.reg = intflag; +} + +/** + * \brief Enable interrupts on status set + * + * Enable the given status interrupt request from the I<SUP>2</SUP>S module. + * + * \param[in] module_inst Pointer to the I<SUP>2</SUP>S software instance struct + * \param[in] status Status interrupts to enable + * + * \return Status of enable procedure. + * + * \retval STATUS_OK Interrupt is enabled successfully + * \retval STATUS_ERR_INVALID_ARG Status with no interrupt is passed + */ +enum status_code i2s_enable_status_interrupt( + struct i2s_module *const module_inst, + uint32_t status) +{ + /* Sanity check arguments */ + Assert(module_inst); + + /* No sync busy interrupt */ + if (status & I2S_STATUS_SYNC_BUSY) { + return STATUS_ERR_INVALID_ARG; + } + Assert(module_inst->hw); + + uint32_t intflag = 0; + if (status & I2S_STATUS_TRANSMIT_UNDERRUN(0)) { + intflag = I2S_INTFLAG_TXUR0; + } + if (status & I2S_STATUS_TRANSMIT_UNDERRUN(1)) { + intflag = I2S_INTFLAG_TXUR1; + } + if (status & I2S_STATUS_TRANSMIT_READY(0)) { + intflag = I2S_INTFLAG_TXRDY0; + } + if (status & I2S_STATUS_TRANSMIT_READY(1)) { + intflag = I2S_INTFLAG_TXRDY1; + } + if (status & I2S_STATUS_RECEIVE_OVERRUN(0)) { + intflag = I2S_INTFLAG_RXOR0; + } + if (status & I2S_STATUS_RECEIVE_OVERRUN(1)) { + intflag = I2S_INTFLAG_RXOR1; + } + if (status & I2S_STATUS_RECEIVE_READY(0)) { + intflag = I2S_INTFLAG_RXRDY0; + } + if (status & I2S_STATUS_RECEIVE_READY(1)) { + intflag = I2S_INTFLAG_RXRDY1; + } + module_inst->hw->INTENSET.reg = intflag; + return STATUS_OK; +} + +/** + * \brief Disable interrupts on status set + * + * Disable the given status interrupt request from the I<SUP>2</SUP>S module. + * + * \param[in] module_inst Pointer to the I<SUP>2</SUP>S software instance struct + * \param[in] status Status interrupts to disable + */ +void i2s_disable_status_interrupt( + struct i2s_module *const module_inst, + uint32_t status) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + uint32_t intflag = 0; + if (status & I2S_STATUS_TRANSMIT_UNDERRUN(0)) { + intflag = I2S_INTFLAG_TXUR0; + } + if (status & I2S_STATUS_TRANSMIT_UNDERRUN(1)) { + intflag = I2S_INTFLAG_TXUR1; + } + if (status & I2S_STATUS_TRANSMIT_READY(0)) { + intflag = I2S_INTFLAG_TXRDY0; + } + if (status & I2S_STATUS_TRANSMIT_READY(1)) { + intflag = I2S_INTFLAG_TXRDY1; + } + if (status & I2S_STATUS_RECEIVE_OVERRUN(0)) { + intflag = I2S_INTFLAG_RXOR0; + } + if (status & I2S_STATUS_RECEIVE_OVERRUN(1)) { + intflag = I2S_INTFLAG_RXOR1; + } + if (status & I2S_STATUS_RECEIVE_READY(0)) { + intflag = I2S_INTFLAG_RXRDY0; + } + if (status & I2S_STATUS_RECEIVE_READY(1)) { + intflag = I2S_INTFLAG_RXRDY1; + } + module_inst->hw->INTENCLR.reg = intflag; +} + + +/** + * \brief Write buffer to the specified Serializer of I<SUP>2</SUP>S module + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] serializer The serializer to write to + * \param[in] buffer The data buffer to write + * \param[in] size Number of data words to write + * + * \return Status of the initialization procedure. + * + * \retval STATUS_OK The data was sent successfully + * \retval STATUS_ERR_DENIED The module or serializer is disabled + * \retval STATUS_ERR_INVALID_ARG An invalid buffer pointer was supplied + */ +enum status_code i2s_serializer_write_buffer_wait( + const struct i2s_module *const module_inst, + enum i2s_serializer serializer, + void *buffer, uint32_t size) +{ + Assert(module_inst); + Assert(module_inst->hw); + Assert(serializer < I2S_SERIALIZER_N); + Assert(buffer); + + if (size == 0) { + return STATUS_OK; + } + + uint8_t data_size = 1; /* number of bytes */ + struct i2s_serializer_module *data_module = (struct i2s_serializer_module *) + &module_inst->serializer[serializer]; + + /* Check buffer */ + switch(data_module->data_size) { + case I2S_DATA_SIZE_32BIT: + case I2S_DATA_SIZE_24BIT: + case I2S_DATA_SIZE_20BIT: + case I2S_DATA_SIZE_18BIT: + if ((uint32_t)buffer & 0x3) { + return STATUS_ERR_INVALID_ARG; + } + data_size = 4; + break; + case I2S_DATA_SIZE_16BIT: + case I2S_DATA_SIZE_16BIT_COMPACT: + if ((uint32_t)buffer & 0x1) { + return STATUS_ERR_INVALID_ARG; + } + data_size = 2; + break; + default: + break; + } + + /* Check status */ + if (!(module_inst->hw->CTRLA.reg & + (I2S_CTRLA_ENABLE | (I2S_CTRLA_SEREN0 << serializer)))) { + return STATUS_ERR_DENIED; + } + + /* Write */ + uint32_t i; + uint32_t sync_bit = I2S_SYNCBUSY_DATA0 << serializer; + uint32_t ready_bit = I2S_INTFLAG_TXRDY0 << serializer; + if (4 == data_size) { + uint32_t *p32 = (uint32_t*)buffer; + for (i = 0; i < size; i ++) { + while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { + /* Wait Tx ready */ + } + while(module_inst->hw->SYNCBUSY.reg & sync_bit) { + /* Wait Sync */ + } + module_inst->hw->DATA[serializer].reg = p32[i]; + module_inst->hw->INTFLAG.reg = ready_bit; + } + } else if (2 == data_size) { + uint16_t *p16 = (uint16_t*)buffer; + for (i = 0; i < size; i ++) { + while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { + /* Wait Tx ready */ + } + while(module_inst->hw->SYNCBUSY.reg & sync_bit) { + /* Wait Sync */ + } + module_inst->hw->DATA[serializer].reg = p16[i]; + module_inst->hw->INTFLAG.reg = ready_bit; + } + } else { + uint8_t *p8 = (uint8_t*)buffer; + for (i = 0; i < size; i ++) { + while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { + /* Wait Tx ready */ + } + while(module_inst->hw->SYNCBUSY.reg & sync_bit) { + /* Wait Sync */ + } + module_inst->hw->DATA[serializer].reg = p8[i]; + module_inst->hw->INTFLAG.reg = ready_bit; + } + } + + return STATUS_OK; +} + +/** + * \brief Read from the specified Serializer of I<SUP>2</SUP>S module to a buffer + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] serializer The serializer to write to + * \param[in] buffer The buffer to fill read data (NULL to discard) + * \param[in] size Number of data words to read + * + * \return Status of the initialization procedure. + * + * \retval STATUS_OK The data was sent successfully + * \retval STATUS_ERR_DENIED The module or serializer is disabled + * \retval STATUS_ERR_INVALID_ARG An invalid buffer pointer was supplied + */ +enum status_code i2s_serializer_read_buffer_wait( + const struct i2s_module *const module_inst, + enum i2s_serializer serializer, + void *buffer, uint32_t size) +{ + Assert(module_inst); + Assert(module_inst->hw); + + if (size == 0) { + return STATUS_OK; + } + + uint8_t data_size = 1; /* number of bytes */ + struct i2s_serializer_module *data_module = (struct i2s_serializer_module *) + &module_inst->serializer[serializer]; + + /* Check buffer */ + switch(data_module->data_size) { + case I2S_DATA_SIZE_32BIT: + case I2S_DATA_SIZE_24BIT: + case I2S_DATA_SIZE_20BIT: + case I2S_DATA_SIZE_18BIT: + if ((uint32_t)buffer & 0x3) { + return STATUS_ERR_INVALID_ARG; + } + data_size = 4; + break; + case I2S_DATA_SIZE_16BIT: + case I2S_DATA_SIZE_16BIT_COMPACT: + if ((uint32_t)buffer & 0x1) { + return STATUS_ERR_INVALID_ARG; + } + data_size = 2; + break; + default: + break; + } + + /* Check status */ + if (!(module_inst->hw->CTRLA.reg & + (I2S_CTRLA_ENABLE | (I2S_CTRLA_SEREN0 << serializer)))) { + return STATUS_ERR_DENIED; + } + + /* Read */ + uint32_t i; + uint32_t sync_bit = I2S_SYNCBUSY_DATA0 << serializer; + uint32_t ready_bit = I2S_INTFLAG_RXRDY0 << serializer; + if (buffer == NULL) { + for (i = 0; i < size; i ++) { + while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { + /* Wait Rx ready */ + } + while(module_inst->hw->SYNCBUSY.reg & sync_bit) { + /* Wait Sync */ + } + module_inst->hw->DATA[serializer].reg; + module_inst->hw->INTFLAG.reg = ready_bit; + } + } + else if (4 == data_size) { + uint32_t *p32 = (uint32_t*)buffer; + for (i = 0; i < size; i ++) { + while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { + /* Wait Rx ready */ + } + while(module_inst->hw->SYNCBUSY.reg & sync_bit) { + /* Wait Sync */ + } + p32[i] = module_inst->hw->DATA[serializer].reg; + module_inst->hw->INTFLAG.reg = ready_bit; + } + } else if (2 == data_size) { + uint16_t *p16 = (uint16_t*)buffer; + for (i = 0; i < size; i ++) { + while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { + /* Wait Rx ready */ + } + while(module_inst->hw->SYNCBUSY.reg & sync_bit) { + /* Wait Sync */ + } + p16[i] = module_inst->hw->DATA[serializer].reg; + module_inst->hw->INTFLAG.reg = ready_bit; + } + } else { + uint8_t *p8 = (uint8_t*)buffer; + for (i = 0; i < size; i ++) { + while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { + /* Wait Tx ready */ + } + while(module_inst->hw->SYNCBUSY.reg & sync_bit) { + /* Wait Sync */ + } + p8[i] = module_inst->hw->DATA[serializer].reg; + module_inst->hw->INTFLAG.reg = ready_bit; + } + } + + return STATUS_OK; +} diff --git a/atmel-samd/asf/sam0/drivers/i2s/i2s.h b/atmel-samd/asf/sam0/drivers/i2s/i2s.h new file mode 100644 index 000000000..0e965d8d3 --- /dev/null +++ b/atmel-samd/asf/sam0/drivers/i2s/i2s.h @@ -0,0 +1,1386 @@ +/** + * \file + * + * \brief SAM I2S - Inter-IC Sound Controller + * + * Copyright (c) 2014-2016 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit <a href="http://www.atmel.com/design-support/">Atmel Support</a> + */ + +#ifndef I2S_H_INCLUDED +#define I2S_H_INCLUDED + +/** + * \defgroup asfdoc_sam0_i2s_group SAM Inter-IC Sound Controller (I2S) Driver + * + * This driver for Atmel® | SMART ARM®-based microcontrollers provides + * an interface for the configuration and management of the device's Inter-IC + * Sound Controller functionality. + * + * The following driver API modes are covered by this manual: + * - Polled APIs + * \if I2S_CALLBACK_MODE + * - Callback APIs + * \endif + * + * The following peripheral is used by this module: + * - I<SUP>2</SUP>S (Inter-IC Sound Controller) + * + * The following devices can use this module: + * - Atmel | SMART SAM D21 + * - Atmel | SMART SAM DA1 + * + * The outline of this documentation is as follows: + * - \ref asfdoc_sam0_i2s_prerequisites + * - \ref asfdoc_sam0_i2s_module_overview + * - \ref asfdoc_sam0_i2s_special_considerations + * - \ref asfdoc_sam0_i2s_extra_info + * - \ref asfdoc_sam0_i2s_examples + * - \ref asfdoc_sam0_i2s_api_overview + * + * \section asfdoc_sam0_i2s_prerequisites Prerequisites + * + * There are no prerequisites for this module. + * + * \section asfdoc_sam0_i2s_module_overview Module Overview + * + * The I<SUP>2</SUP>S provides bidirectional, synchronous, digital audio link with + * external audio devices through these signal pins: + * - Serial Data (SDm) + * - Frame Sync (FSn) + * - Serial Clock (SCKn) + * - Master Clock (MCKn) + * + * The I<SUP>2</SUP>S consists of two Clock Units and two Serializers, which can be + * separately configured and enabled, to provide varies functionalities as follow: + * - Communicate to Audio CODECs as Master or Slave, or provides clock and + * frame sync signals as Controller + * - Communicate to DAC or ADC through dedicated I<SUP>2</SUP>S serial interface + * - Communicate to multi-slot or multiple stereo DACs or ADCs, via + * Time Division Multiplexed (TDM) format + * - Reading mono or stereo MEMS microphones, using the Pulse Density + * Modulation (PDM) interface + * + * The I<SUP>2</SUP>S supports compact stereo data word, where left channel data bits are + * in lower half and right channel data bits are in upper half. It reduces the + * number of data words for stereo audio data and the DMA bandwidth. + * + * In master mode, the frame is configured by number of slots and slot size, and + * allows range covering 16fs to 1024fs MCK, to provide oversampling clock to an + * external audio CODEC or digital signal processor (DSP). + * + * A block diagram of the I<SUP>2</SUP>S can be seen in + * \ref asfdoc_sam0_i2s_module_block_diagram "the figure below". + * + * \anchor asfdoc_sam0_i2s_module_block_diagram + * \image html i2s_blocks.svg "I2S Block Diagram" + * + * This driver for I<SUP>2</SUP>S module provides an interface to: + * - Initialize and control I<SUP>2</SUP>S module + * - Configure and control the I<SUP>2</SUP>S Clock Unit and Serializer + * - Transmit/receive data through I<SUP>2</SUP>S Serializer + * + * \subsection asfdoc_sam0_i2s_module_overview_clocks Clocks + * + * To use I<SUP>2</SUP>S module, the I<SUP>2</SUP>S bus interface clock (clk_i2s) + * must be enabled via Power Manager. + * + * For each I<SUP>2</SUP>S Clock Unit, a generic clock (gclk_i2s_n) is connnected. + * When I<SUP>2</SUP>S works in master mode the generic clock is used. It should + * be prepared before clock unit is used. In master mode the input generic clock + * will be used as MCK for SCKn and FSn generation, in addition, the MCK could be + * devided and output to I<SUP>2</SUP>S MCKn pin, as oversampling clock to + * external audio device. + * + * The I<SUP>2</SUP>S Serializer uses clock and control signal from Clock Unit to handle + * transfer. Select different clock unit with different configurations allows + * the I<SUP>2</SUP>S to work as master or slave, to work on non-related clocks. + * + * When using the driver with ASF, enabling the register interface is normally + * done by the \c init function. + * The Generic Clock Controller (GCLK) source for the asynchronous domain is + * normally configured and set through the _configuration + * struct_ / _init_ function. + * If GCLK source != 0 is used, this source has to be configured and enabled + * through invoking the system_gclk driver function when needed, or modifying + * conf_clock.h to enable it at the beginning. + * + * \subsection asfdoc_sam0_i2s_module_overview_frame Audio Frame Generation + * + * Audio sample data for all channels are sent in frames, one frame can consist + * 1 - 8 slots where each slot can be configured to a size 8-bit, 16-bit, 24-bit, + * or 32-bit. The audio frame synch clock is generated by the I<SUP>2</SUP>S + * Clock unit in the master/controller mode. The frame rate (or frame sync + * frequency) is calculated as follows: + * + * FS = SCK / number_of_slots / number_of_bits_in_slot + * + * The serial clock (SCK) source is either an external source (slave mode) or + * generated by the I<SUP>2</SUP>S clock unit (controller or master mode) using + * the MCK as source. + * + * SCK = MCK / sck_div + * \note SCK generation division value is MCKDIV in register. + * + * MCK is either an external source or generated using the GCLK input from a + * generic clock generator. + * + * \subsection asfdoc_sam0_i2s_module_overview_mode Master, Controller, and Slave Modes + * + * The I<SUP>2</SUP>S module has three modes: master, controller, and slave. + * + * \subsubsection asfdoc_sam0_i2s_module_overview_mode_mst Master + * In master mode the module will control the data flow on the I<SUP>2</SUP>S bus and can + * be responsible for clock generation. The Serializers are enabled and will + * transmit/receive data. On a bus with only master and slave the SCK, and FS + * clock signal will be outputted on the SCK and FS pin on the master module. + * MCK can optionally be outputted on the MCK pin, if there is a controller + * module on the bus the SCK, FS, and optionally the MCK clock is sourced from + * the same pins. Serial data will be trancieved on the SD pin in both + * scenarios. + * + * \subsubsection asfdoc_sam0_i2s_module_overview_mode_ctl Controller + * In controller mode the module will generate the clock signals, but the + * Serializers are disabled and no data will be transmitted/received by the + * module in this mode. The clock signals is outputted on the SCK, FS and + * optionally the MCK pin. + * + * \subsubsection asfdoc_sam0_i2s_module_overview_mode_slv Slave + * In slave mode the module will use the SCK and FS clock source from the master + * or the controller which is received on the SCK and FS pin. The MCK can + * optionally be sourced externally on the MCK pin. The Serializers are enabled + * and will tranceive data on the SD pin. All data flow is controlled by the + * master. + * + * \subsubsection asfdoc_sam0_i2s_module_overview_mode_chg Switch Modes + * The mode switching between master, controller, and slave modes are actually + * done by modifying the source mode of I<SUP>2</SUP>S pins. + * The source mode of I<SUP>2</SUP>S pins are selected by writing corresponding + * bits in CLKCTRLn. + * Since source mode switching changes the direction of pin, the mode must be + * changed when the I<SUP>2</SUP>S Clock Unit is stopped. + * + * \subsection asfdoc_sam0_i2s_module_overview_data Data Stream Reception/Transmission + * + * The I<SUP>2</SUP>S module support several data stream formats: + * - I<SUP>2</SUP>S format + * - Time Division Multiplexed (TDM) format + * - Pulse Density Modulation (PDM) format (reception only) + * + * Basically the I<SUP>2</SUP>S module can send several words within each frame, + * it's more like TDM format. With adjust to the number of data words in a frame, + * the FS width, the FS to data bits delay, etc., the module is able to handle + * I<SUP>2</SUP>S compliant data stream. + * + * Also the Serializer can receive PDM format data stream, which allows the + * I<SUP>2</SUP>S module receive 1 PDM data on each SCK edge. + * + * \subsubsection asfdoc_sam0_i2s_module_overview_data_i2s I2S Stream Reception/Transmission + * + * For 2-channel I<SUP>2</SUP>S compliant data stream format the I<SUP>2</SUP>S + * module uses the FS line as word select (WS) signal and will send left channel + * data word on low WS level and right channel data word on high WS level as + * specified in the I<SUP>2</SUP>S standard. The supported word sizes are 8-, + * 16-, 18-, 20-, 24-, and 32- bit. + * + * Thus for I<SUP>2</SUP>S stream, the following settings should be applied to the module: + * - Data starting delay after FS transition : one SCK period + * - FS width : half of frame + * - Data bits adjust in word : left-adjusted + * - Bit transmitting order : MSB first + * + * Following is an example for I<SUP>2</SUP>S application connections and waveforms. See + * the figure below. + * + * \anchor asfdoc_sam0_i2s_module_i2s_example_diagram + * \image html i2s_example.svg "I2S Example Diagram" + * + * \subsubsection asfdoc_sam0_i2s_module_overview_data_tdm TDM Stream Reception/Transmission + * In TDM format, the module sends several data words in each frame. For this + * data stream format most of the configurations could be adjusted: + * - Main Frame related settings are as follow: + * - Frame Sync (FS) options: + * - The active edge of the FS (or if FS is inverted before use) + * - The width of the FS + * - The delay between FS to first data bit + * - Data alignment in slot + * - The number of slots and slot size can be adjusted, it has been mentioned + * in \ref asfdoc_sam0_i2s_module_overview_frame + * - The data word size is controlled by Serializer, it can be chosen among + * 8, 16, 18, 20, 24, and 32 bits. + * + * The general TDM waveform generation is as follows: + * + * \anchor asfdoc_sam0_i2s_module_tdm_wave_diagram + * \image html tdm_wave.svg "TDM Waveform Generation" + * + * Some other settings could also be found to set up clock, data formatting and + * pin multiplexer (MUX). + * Refer to \ref i2s_clock_unit_config "Clock Unit Configurations" + * and \ref i2s_serializer_config "Serializer Configurations" for more + * details. + * + * Following is examples for different application use cases. + * + * See \ref asfdoc_sam0_i2s_module_tdm_timeslot_example_diagram "here" for + * the Time Slot Application connection and waveform example. + * + * \anchor asfdoc_sam0_i2s_module_tdm_timeslot_example_diagram + * \image html tdm_timeslot_example.svg "Codec Example Diagram" + * + * See \ref asfdoc_sam0_i2s_module_tdm_codec_example_diagram "here" for the + * Codec Application connection and waveform example. + * + * \anchor asfdoc_sam0_i2s_module_tdm_codec_example_diagram + * \image html tdm_codec_example.svg "Time Slot Example Diagram" + * + * \subsubsection asfdoc_sam0_i2s_module_overview_data_pdm PDM Reception + * The I<SUP>2</SUP>S Serializer integrates PDM reception feature, to use this feature, + * simply select PDM2 mode in Serializer configuration. In PDM2 mode, it assumes + * two microphones are input for stereo stream. The left microphone bits will + * be stored in lower half and right microphone bits in upper half of the data + * word, like in compact stereo format. + * + * See \ref asfdoc_sam0_i2s_module_pdm_example_diagram "following figure" for an + * example of PDM Microphones Application with both left and right channel + * microphone connected. + * + * \anchor asfdoc_sam0_i2s_module_pdm_example_diagram + * \image html pdm_example.svg "Time PDM2 Example Diagram" + * + * \subsubsection asfdoc_sam0_i2s_module_overview_data_fmt MONO and Compact Data + * The I<SUP>2</SUP>S Serializer can accept some pre-defined data format and generates + * the data stream in specified way. + * + * When transmitting data, the Serializer can work in MONO mode: assum input + * is single channel mono data on left channel and copy it to right channel + * automatically. + * + * Also the I<SUP>2</SUP>S Serializer can support compact stereo data word. The data word + * size of the Serializer can be set to \ref I2S_DATA_SIZE_16BIT_COMPACT + * "16-bit compact" or \ref I2S_DATA_SIZE_8BIT_COMPACT "8-bit compact", with + * these option I<SUP>2</SUP>S Serializer will compact left channel data and right channel + * data together, the left channel data will take lower bytes and right channel + * data take higher bytes. + * + * \subsection asfdoc_sam0_i2s_module_overview_loop Loop-back Mode + * The I<SUP>2</SUP>S can be configured to loop back the Transmitter to Receiver. In this + * mode Serializer's input will be connected to another Serializer's output + * internally. + * + * \subsection asfdoc_sam0_i2s_module_overview_sleep Sleep Modes + * The I<SUP>2</SUP>S will continue to operate in any sleep mode, where the selected source + * clocks are running. + * + * \section asfdoc_sam0_i2s_special_considerations Special Considerations + * + * There is no special considerations for I<SUP>2</SUP>S module. + * + * \section asfdoc_sam0_i2s_extra_info Extra Information + * + * For extra information see \ref asfdoc_sam0_i2s_extra. This includes: + * - \ref asfdoc_sam0_i2s_extra_acronyms + * - \ref asfdoc_sam0_i2s_extra_dependencies + * - \ref asfdoc_sam0_i2s_extra_errata + * - \ref asfdoc_sam0_i2s_extra_history + * + * \section asfdoc_sam0_i2s_examples Examples + * + * For a list of examples related to this driver, see + * \ref asfdoc_sam0_i2s_exqsg. + * + * + * \section asfdoc_sam0_i2s_api_overview API Overview + * @{ + */ + +#ifdef __cplusplus +extern "C" { +#endif + +#include <compiler.h> +#include <system.h> + +#if I2S_CALLBACK_MODE == true +# include <system_interrupt.h> + +#if !defined(__DOXYGEN__) +extern struct i2s_module *_i2s_instances[I2S_INST_NUM]; +#endif + +/** Forward definition of the device instance */ +struct i2s_module; + +/** Type of the callback functions. */ +typedef void (*i2s_serializer_callback_t) + (struct i2s_module *const module); + +/** + * \brief I<SUP>2</SUP>S Serializer Callback enum + */ +enum i2s_serializer_callback { + /** Callback for buffer read/write finished */ + I2S_SERIALIZER_CALLBACK_BUFFER_DONE, + /** Callback for Serializer overrun/underrun */ + I2S_SERIALIZER_CALLBACK_OVER_UNDER_RUN, +# if !defined(__DOXYGEN__) + I2S_SERIALIZER_CALLBACK_N +# endif +}; + +#endif /* #if I2S_CALLBACK_MODE == true */ + +/** + * \name Module Status Flags + * + * I<SUP>2</SUP>S status flags, returned by \ref i2s_get_status() and cleared by + * \ref i2s_clear_status(). + * + * @{ + */ + +/** Module Serializer x (0~1) Transmit Underrun. */ +#define I2S_STATUS_TRANSMIT_UNDERRUN(x) (1u << ((x)+0)) +/** Module Serializer x (0~1) is ready to accept new data to be transmitted. */ +#define I2S_STATUS_TRANSMIT_READY(x) (1u << ((x)+2)) +/** Module Serializer x (0~1) Receive Overrun. */ +#define I2S_STATUS_RECEIVE_OVERRUN(x) (1u << ((x)+4)) +/** Module Serializer x (0~1) has received a new data. */ +#define I2S_STATUS_RECEIVE_READY(x) (1u << ((x)+6)) +/** Module is busy on synchronization. */ +#define I2S_STATUS_SYNC_BUSY (1u << 8) + +/** @} */ + +/** + * Master Clock (MCK) source selection. + */ +enum i2s_master_clock_source { + /** Master Clock (MCK) is from general clock */ + I2S_MASTER_CLOCK_SOURCE_GCLK, + /** Master Clock (MCK) is from MCK input pin */ + I2S_MASTER_CLOCK_SOURCE_MCKPIN +}; + +/** + * Serial Clock (SCK) source selection. + */ +enum i2s_serial_clock_source { + /** Serial Clock (SCK) is divided from Master Clock */ + I2S_SERIAL_CLOCK_SOURCE_MCKDIV, + /** Serial Clock (SCK) is input from SCK input pin */ + I2S_SERIAL_CLOCK_SOURCE_SCKPIN +}; + +/** + * Data delay from Frame Sync (FS). + */ +enum i2s_data_delay { + /** Left Justified (no delay) */ + I2S_DATA_DELAY_0, + /** I<SUP>2</SUP>S data delay (1-bit delay) */ + I2S_DATA_DELAY_1, + /** Left Justified (no delay) */ + I2S_DATA_DELAY_LEFT_JUSTIFIED = I2S_DATA_DELAY_0, + /** I<SUP>2</SUP>S data delay (1-bit delay) */ + I2S_DATA_DELAY_I2S = I2S_DATA_DELAY_1 +}; + +/** + * Frame Sync (FS) source. + */ +enum i2s_frame_sync_source { + /** Frame Sync (FS) is divided from I<SUP>2</SUP>S Serial Clock */ + I2S_FRAME_SYNC_SOURCE_SCKDIV, + /** Frame Sync (FS) is input from FS input pin */ + I2S_FRAME_SYNC_SOURCE_FSPIN +}; + +/** + * Frame Sync (FS) output pulse width. + */ +enum i2s_frame_sync_width { + /** Frame Sync (FS) Pulse is one slot width */ + I2S_FRAME_SYNC_WIDTH_SLOT, + /** Frame Sync (FS) Pulse is half a frame width */ + I2S_FRAME_SYNC_WIDTH_HALF_FRAME, + /** Frame Sync (FS) Pulse is one bit width */ + I2S_FRAME_SYNC_WIDTH_BIT, + /** 1-bit wide Frame Sync (FS) per Data sample, only used when Data transfer + * is requested */ + I2S_FRAME_SYNC_WIDTH_BURST +}; + +/** + * Time Slot Size in number of I<SUP>2</SUP>S serial clocks (bits). + */ +enum i2s_slot_size { + /** 8-bit slot */ + I2S_SLOT_SIZE_8_BIT, + /** 16-bit slot */ + I2S_SLOT_SIZE_16_BIT, + /** 24-bit slot */ + I2S_SLOT_SIZE_24_BIT, + /** 32-bit slot */ + I2S_SLOT_SIZE_32_BIT +}; + +/** + * DMA channels usage for I<SUP>2</SUP>S. + */ +enum i2s_dma_usage { + /** Single DMA channel for all I<SUP>2</SUP>S channels */ + I2S_DMA_USE_SINGLE_CHANNEL_FOR_ALL, + /** One DMA channel per data channel */ + I2S_DMA_USE_ONE_CHANNEL_PER_DATA_CHANNEL +}; + +/** + * I<SUP>2</SUP>S data format, to extend mono data to two channels. + */ +enum i2s_data_format { + /** Normal mode, keep data to its right channel */ + I2S_DATA_FORMAT_STEREO, + /** Assume input is mono data for left channel, the data is duplicated to + * right channel */ + I2S_DATA_FORMAT_MONO +}; + +/** + * I<SUP>2</SUP>S data bit order. + */ +enum i2s_bit_order { + /** Transfer Data Most Significant Bit first + * (Default for I<SUP>2</SUP>S protocol) + */ + I2S_BIT_ORDER_MSB_FIRST, + /** Transfer Data Least Significant Bit first */ + I2S_BIT_ORDER_LSB_FIRST +}; + +/** + * I<SUP>2</SUP>S data bit padding. + */ +enum i2s_bit_padding { + /** Padding with 0 */ + I2S_BIT_PADDING_0, + /** Padding with 1 */ + I2S_BIT_PADDING_1, + /** Padding with MSBit */ + I2S_BIT_PADDING_MSB, + /** Padding with LSBit */ + I2S_BIT_PADDING_LSB, +}; + +/** + * I<SUP>2</SUP>S data word adjust. + */ +enum i2s_data_adjust { + /** Data is right adjusted in word */ + I2S_DATA_ADJUST_RIGHT, + /** Data is left adjusted in word */ + I2S_DATA_ADJUST_LEFT +}; + +/** + * I<SUP>2</SUP>S data word size. + */ +enum i2s_data_size { + /** 32-bit */ + I2S_DATA_SIZE_32BIT, + /** 24-bit */ + I2S_DATA_SIZE_24BIT, + /** 20-bit */ + I2S_DATA_SIZE_20BIT, + /** 18-bit */ + I2S_DATA_SIZE_18BIT, + /** 16-bit */ + I2S_DATA_SIZE_16BIT, + /** 16-bit compact stereo */ + I2S_DATA_SIZE_16BIT_COMPACT, + /** 8-bit */ + I2S_DATA_SIZE_8BIT, + /** 8-bit compact stereo */ + I2S_DATA_SIZE_8BIT_COMPACT +}; + +/** + * I<SUP>2</SUP>S data slot adjust. + */ +enum i2s_slot_adjust { + /** Data is right adjusted in slot */ + I2S_SLOT_ADJUST_RIGHT, + /** Data is left adjusted in slot */ + I2S_SLOT_ADJUST_LEFT +}; + +/** + * I<SUP>2</SUP>S data padding. + */ +enum i2s_data_padding { + /** Padding 0 in case of under-run */ + I2S_DATA_PADDING_0, + /** Padding last data in case of under-run */ + I2S_DATA_PADDING_SAME_AS_LAST, + /** Padding last data in case of under-run + * (abbr. \c I2S_DATA_PADDING_SAME_AS_LAST) */ + I2S_DATA_PADDING_LAST = I2S_DATA_PADDING_SAME_AS_LAST, + /** Padding last data in case of under-run + * (abbr. \c I2S_DATA_PADDING_SAME_AS_LAST) */ + I2S_DATA_PADDING_SAME = I2S_DATA_PADDING_SAME_AS_LAST +}; + +/** + * I<SUP>2</SUP>S line default value when slot disabled. + */ +enum i2s_line_default_state { + /** Output default value is 0 */ + I2S_LINE_DEFAULT_0, + /** Output default value is 1 */ + I2S_LINE_DEFAULT_1, + /** Output default value is high impedance */ + I2S_LINE_DEFAULT_HIGH_IMPEDANCE = 3, + /** Output default value is high impedance + * (abbr. \c I2S_LINE_DEFAULT_HIGH_IMPEDANCE) */ + I2S_LINE_DEFAULT_HIZ = I2S_LINE_DEFAULT_HIGH_IMPEDANCE +}; + +/** + * I<SUP>2</SUP>S Serializer mode. + */ +enum i2s_serializer_mode { + /** Serializer is used to receive data */ + I2S_SERIALIZER_RECEIVE, + /** Serializer is used to transmit data */ + I2S_SERIALIZER_TRANSMIT, + /** Serializer is used to receive PDM data on each clock edge */ + I2S_SERIALIZER_PDM2 +}; + +/** + * I<SUP>2</SUP>S clock unit selection. + */ +enum i2s_clock_unit { + /** Clock Unit channel 0 */ + I2S_CLOCK_UNIT_0, + /** Clock Unit channel 1 */ + I2S_CLOCK_UNIT_1, + /** Number of Clock Unit channels */ + I2S_CLOCK_UNIT_N +}; + +/** + * I<SUP>2</SUP>S Serializer selection. + */ +enum i2s_serializer { + /** Serializer channel 0 */ + I2S_SERIALIZER_0, + /** Serializer channel 1 */ + I2S_SERIALIZER_1, + /** Number of Serializer channels */ + I2S_SERIALIZER_N +}; + + +/** + * Configure for I<SUP>2</SUP>S pin. + */ +struct i2s_pin_config { + /** GPIO index to access the pin */ + uint8_t gpio; + /** Pin function MUX */ + uint8_t mux; + /** Enable this pin for I<SUP>2</SUP>S module */ + bool enable; +}; + +/** + * Configure for I<SUP>2</SUP>S clock (SCK). + */ +struct i2s_clock_config { + /** Divide generic clock to master clock output (1~32, 0,1 means no div) */ + uint8_t mck_out_div; + /** Divide generic clock to serial clock (1~32, 0,1 means no div) */ + uint8_t sck_div; + /** Clock source selection */ + enum gclk_generator gclk_src; + /** Master clock source selection: generated or input from pin */ + enum i2s_master_clock_source mck_src; + /** Serial clock source selection: generated or input from pin */ + enum i2s_serial_clock_source sck_src; + /** Invert master clock output */ + bool mck_out_invert; + /** Invert serial clock output */ + bool sck_out_invert; + /** Generate MCK clock output */ + bool mck_out_enable; +}; + +/** + * Configure for I<SUP>2</SUP>S frame sync (FS). + */ +struct i2s_frame_sync_config { + /** Frame Sync (FS) generated or input from pin */ + enum i2s_frame_sync_source source; + /** Frame Sync (FS) width */ + enum i2s_frame_sync_width width; + /** Invert Frame Sync (FS) signal before use */ + bool invert_use; + /** Invert Frame Sync (FS) signal before output */ + bool invert_out; +}; + +/** + * Configure for I<SUP>2</SUP>S frame. + */ +struct i2s_frame_config { + /** Number of slots in a frame (1~8, 0,1 means minimum 1) */ + uint8_t number_slots; + /** Size of each slot in frame */ + enum i2s_slot_size slot_size; + /** Data delay from Frame Sync (FS) to first data bit */ + enum i2s_data_delay data_delay; + /** Frame sync (FS) */ + struct i2s_frame_sync_config frame_sync; +}; + +/** + * Configure for I<SUP>2</SUP>S clock unit. + */ +struct i2s_clock_unit_config { + /** Configure clock generation */ + struct i2s_clock_config clock; + /** Configure frame generation */ + struct i2s_frame_config frame; + + /** Configure master clock pin */ + struct i2s_pin_config mck_pin; + /** Configure serial clock pin */ + struct i2s_pin_config sck_pin; + /** Configure frame sync pin */ + struct i2s_pin_config fs_pin; +}; + +/** + * Configure for I<SUP>2</SUP>S Serializer. + */ +struct i2s_serializer_config { + /** Configure Serializer data pin */ + struct i2s_pin_config data_pin; + + /** Set to \c true to loop-back output to input pin for test */ + bool loop_back; + + /** Set to \c true to assumes mono input and duplicate it (left channel) to + * right channel */ + bool mono_mode; + + /** Disable data slot */ + bool disable_data_slot[8]; + + /** Set to \c true to transfer LSB first, \c false to transfer MSB first */ + bool transfer_lsb_first; + /** Data Word Formatting Adjust, + * set to \c true to adjust bits in word to left */ + bool data_adjust_left_in_word; + /** Data Slot Formatting Adjust, + * set to \c true to adjust words in slot to left */ + bool data_adjust_left_in_slot; + + /** Data Word Size */ + enum i2s_data_size data_size; + /** Data Formatting Bit Extension */ + enum i2s_bit_padding bit_padding; + /** Data padding when under-run */ + enum i2s_data_padding data_padding; + + /** DMA usage */ + enum i2s_dma_usage dma_usage; + + /** Clock unit selection */ + enum i2s_clock_unit clock_unit; + + /** Line default state where slot is disabled */ + enum i2s_line_default_state line_default_state; + + /** Serializer Mode */ + enum i2s_serializer_mode mode; +}; + +/** + * \brief I<SUP>2</SUP>S Serializer instance struct. + */ +struct i2s_serializer_module { + +#if I2S_CALLBACK_MODE == true + /** Callbacks list for Serializer */ + i2s_serializer_callback_t callback[I2S_SERIALIZER_CALLBACK_N]; + + /** Job buffer */ + void *job_buffer; + /** Requested data words to read/write */ + uint32_t requested_words; + /** Transferred data words for read/write */ + uint32_t transferred_words; + + /** Callback mask for registered callbacks */ + uint8_t registered_callback_mask; + /** Callback mask for enabled callbacks */ + uint8_t enabled_callback_mask; + + /** Status of the ongoing or last transfer job */ + enum status_code job_status; +#endif + + /** Serializer mode */ + enum i2s_serializer_mode mode; + /** Serializer data word size */ + enum i2s_data_size data_size; +}; + +/** + * \brief I<SUP>2</SUP>S Software Module instance struct. + */ +struct i2s_module { + /** Module HW register access base */ + I2s *hw; + + /** Module Serializer used */ + struct i2s_serializer_module serializer[2]; +}; + +/** + * \brief Determines if the hardware module(s) are currently synchronizing to the bus. + * + * Checks to see if the underlying hardware peripheral module(s) are currently + * synchronizing across multiple clock domains to the hardware bus, This + * function can be used to delay further operations on a module until such time + * that it is ready, to prevent blocking delays for synchronization in the + * user application. + * + * \param[in] module_inst Pointer to the software module instance struct + * + * \return Synchronization status of the underlying hardware module(s). + * + * \retval false If the module has completed synchronization + * \retval true If the module synchronization is ongoing + */ +static inline bool i2s_is_syncing( + const struct i2s_module *const module_inst) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + return (module_inst->hw->SYNCBUSY.reg > 0); +} + +/** + * \name Driver Initialization + * @{ + */ + +enum status_code i2s_init( + struct i2s_module *const module_inst, + I2s *hw); + +/** @} */ + +/** + * \name Enable/Disable/Reset + * @{ + */ + +/** + * \brief Enable the I<SUP>2</SUP>S module. + * + * Enables a I<SUP>2</SUP>S module that has been previously initialized. + * + * \param[in] module_inst Pointer to the software module instance struct + */ +static inline void i2s_enable(const struct i2s_module *const module_inst) +{ + Assert(module_inst); + Assert(module_inst->hw); + + while (module_inst->hw->SYNCBUSY.reg & I2S_SYNCBUSY_ENABLE) { + /* Sync wait */ + } + module_inst->hw->CTRLA.reg |= I2S_SYNCBUSY_ENABLE; +} + +/** + * \brief Disables the I<SUP>2</SUP>S module. + * + * Disables a I<SUP>2</SUP>S module. + * + * \param[in] module_inst Pointer to the software module instance struct + */ +static inline void i2s_disable(const struct i2s_module *const module_inst) +{ + Assert(module_inst); + Assert(module_inst->hw); + + while (module_inst->hw->SYNCBUSY.reg & I2S_SYNCBUSY_ENABLE) { + /* Sync wait */ + } + + module_inst->hw->INTENCLR.reg = I2S_INTENCLR_MASK; + module_inst->hw->INTFLAG.reg = I2S_INTFLAG_MASK; + module_inst->hw->CTRLA.reg &= ~I2S_SYNCBUSY_ENABLE; +} + +/** + * \brief Resets the I<SUP>2</SUP>S module. + * + * Resets the I<SUP>2</SUP>S module, restoring all hardware module registers to their + * default values and disabling the module. The I<SUP>2</SUP>S module will not be + * accessible while the reset is being performed. + * + * \param[in] module_inst Pointer to the software module instance struct + */ +static inline void i2s_reset(const struct i2s_module *const module_inst) +{ + Assert(module_inst); + Assert(module_inst->hw); + + /* Disable the module if it is running */ + if (module_inst->hw->CTRLA.reg & I2S_CTRLA_ENABLE) { + i2s_disable(module_inst); + while (i2s_is_syncing(module_inst)) { + /* Sync wait */ + } + } + /* Reset the HW module */ + module_inst->hw->CTRLA.reg = I2S_CTRLA_SWRST; +} + +/** @} */ + +/** + * \name Clock Unit Initialization and Configuration + * @{ + */ + +/** + * \brief Initializes config with predefined default values for I<SUP>2</SUP>S clock unit. + * + * This function will initialize a given I<SUP>2</SUP>S Clock Unit configuration structure + * to a set of known default values. This function should be called on any new + * instance of the configuration structures before being modified by the user + * application. + * + * The default configuration is as follows: + * - The clock unit does not generate output clocks (MCK, SCK, and FS) + * - The pins (MCK, SCK, and FS) and MUX configurations are not set + * + * \param[out] config Pointer to a I<SUP>2</SUP>S module clock unit configuration struct + * to set + */ +static inline void i2s_clock_unit_get_config_defaults( + struct i2s_clock_unit_config *const config) +{ + Assert(config); + + config->clock.mck_out_enable = false; + config->clock.gclk_src = GCLK_GENERATOR_0; + + config->clock.mck_src = I2S_MASTER_CLOCK_SOURCE_GCLK; + config->clock.mck_out_div = 1; + config->clock.mck_out_invert = false; + + config->clock.sck_src = I2S_SERIAL_CLOCK_SOURCE_MCKDIV; + config->clock.sck_div = 1; + config->clock.sck_out_invert = false; + + config->frame.number_slots = 1; + config->frame.slot_size = I2S_SLOT_SIZE_32_BIT; + config->frame.data_delay = I2S_DATA_DELAY_I2S; + + config->frame.frame_sync.source = I2S_FRAME_SYNC_SOURCE_SCKDIV; + config->frame.frame_sync.width = I2S_FRAME_SYNC_WIDTH_HALF_FRAME; + config->frame.frame_sync.invert_use = false; + config->frame.frame_sync.invert_out = false; + + config->mck_pin.enable = false; + config->mck_pin.mux = 0; + config->mck_pin.gpio = 0; + + config->sck_pin.enable = false; + config->sck_pin.mux = 0; + config->sck_pin.gpio = 0; + + config->fs_pin.enable = false; + config->fs_pin.mux = 0; + config->fs_pin.gpio = 0; +} + +enum status_code i2s_clock_unit_set_config( + struct i2s_module *const module_inst, + const enum i2s_clock_unit clock_unit, + const struct i2s_clock_unit_config *config); + +/** @} */ + + +/** + * \name Clock Unit Enable/Disable + * @{ + */ + +/** + * \brief Enable the Specified Clock Unit of I<SUP>2</SUP>S module. + * + * Enables a Clock Unit in I<SUP>2</SUP>S module that has been previously initialized. + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] clock_unit I<SUP>2</SUP>S Clock Unit to enable + */ +static inline void i2s_clock_unit_enable( + const struct i2s_module *const module_inst, + const enum i2s_clock_unit clock_unit) +{ + uint32_t cken_bit; + + Assert(module_inst); + Assert(module_inst->hw); + + cken_bit = I2S_CTRLA_CKEN0 << clock_unit; + + while (module_inst->hw->SYNCBUSY.reg & cken_bit) { + /* Sync wait */ + } + module_inst->hw->CTRLA.reg |= cken_bit; +} + +/** + * \brief Disable the Specified Clock Unit of I<SUP>2</SUP>S module. + * + * Disables a Clock Unit in I<SUP>2</SUP>S module that has been previously initialized. + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] clock_unit I<SUP>2</SUP>S Clock Unit to disable + */ +static inline void i2s_clock_unit_disable( + const struct i2s_module *const module_inst, + const enum i2s_clock_unit clock_unit) +{ + uint32_t cken_bit; + + Assert(module_inst); + Assert(module_inst->hw); + + cken_bit = I2S_CTRLA_CKEN0 << clock_unit; + + while (module_inst->hw->SYNCBUSY.reg & cken_bit) { + /* Sync wait */ + } + module_inst->hw->CTRLA.reg &= ~cken_bit; +} + +/** @} */ + + +/** + * \name Serializer Initialization and Configuration + * @{ + */ + +/** + * \brief Initializes config with predefined default values for I<SUP>2</SUP>S Serializer. + * + * This function will initialize a given I<SUP>2</SUP>S Clock Unit configuration structure + * to a set of known default values. This function should be called on any new + * instance of the configuration structures before being modified by the user + * application. + * + * The default configuration is as follows: + * - Output data does not internally loopback to input line + * - Does not extend mono data (left channel) to right channel + * - None of the data slot is disabled + * - MSB of I<SUP>2</SUP>S data is transferred first + * - In data word data is adjusted right + * - In slot data word is adjusted left + * - The data size is 16-bit width + * - I<SUP>2</SUP>S will padd 0 to not defined bits + * - I<SUP>2</SUP>S will padd 0 to not defined words + * - I<SUP>2</SUP>S will use single DMA channel for all data channels + * - I<SUP>2</SUP>S will use clock unit 0 to serve as clock + * - The default data line state is 0, when there is no data + * - I<SUP>2</SUP>S will transmit data to output line + * - The data pin and MUX configuration are not set + * + * \param[out] config Pointer to a I<SUP>2</SUP>S module Serializer configuration struct + * to set + */ +static inline void i2s_serializer_get_config_defaults( + struct i2s_serializer_config *const config) +{ + config->loop_back = false; + + config->mono_mode = false; + + config->disable_data_slot[0] = false; + config->disable_data_slot[1] = false; + config->disable_data_slot[2] = false; + config->disable_data_slot[3] = false; + config->disable_data_slot[4] = false; + config->disable_data_slot[5] = false; + config->disable_data_slot[6] = false; + config->disable_data_slot[7] = false; + + config->transfer_lsb_first = false; + config->data_adjust_left_in_word = false; + config->data_adjust_left_in_slot = true; + + config->data_size = I2S_DATA_SIZE_16BIT; + + config->bit_padding = I2S_BIT_PADDING_0; + config->data_padding = I2S_DATA_PADDING_0; + + config->dma_usage = I2S_DMA_USE_SINGLE_CHANNEL_FOR_ALL; + + config->clock_unit = I2S_CLOCK_UNIT_0; + + config->line_default_state = I2S_LINE_DEFAULT_0; + + config->mode = I2S_SERIALIZER_TRANSMIT; + + config->data_pin.enable = false; + config->data_pin.gpio = 0; + config->data_pin.mux = 0; +} + +enum status_code i2s_serializer_set_config( + struct i2s_module *const module_inst, + const enum i2s_serializer serializer, + const struct i2s_serializer_config *config); +/** @} */ + +/** + * \name Serializer Enable/Disable + * @{ + */ + +/** + * \brief Enable the Specified Serializer of I<SUP>2</SUP>S module. + * + * Enables a Serializer in I<SUP>2</SUP>S module that has been previously initialized. + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] serializer I<SUP>2</SUP>S Serializer to enable + */ +static inline void i2s_serializer_enable( + const struct i2s_module *const module_inst, + const enum i2s_serializer serializer) +{ + uint32_t seren_bit; + + Assert(module_inst); + Assert(module_inst->hw); + + seren_bit = I2S_CTRLA_SEREN0 << serializer; + + while (module_inst->hw->SYNCBUSY.reg & seren_bit) { + /* Sync wait */ + } + module_inst->hw->CTRLA.reg |= seren_bit; +} + +/** + * \brief Disable the Specified Serializer of I<SUP>2</SUP>S module. + * + * Disables a Serializer in I<SUP>2</SUP>S module that has been previously initialized. + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] serializer I<SUP>2</SUP>S Serializer to disable + */ +static inline void i2s_serializer_disable( + const struct i2s_module *const module_inst, + const enum i2s_serializer serializer) +{ + uint32_t seren_bit; + + Assert(module_inst); + Assert(module_inst->hw); + + seren_bit = I2S_CTRLA_SEREN0 << serializer; + + while (module_inst->hw->SYNCBUSY.reg & seren_bit) { + /* Sync wait */ + } + module_inst->hw->CTRLA.reg &= ~seren_bit; +} +/** @} */ + +/** + * \name Status Management + * @{ + */ + +uint32_t i2s_get_status( + const struct i2s_module *const module_inst); + +void i2s_clear_status( + const struct i2s_module *const module_inst, + uint32_t status); + + +enum status_code i2s_enable_status_interrupt( + struct i2s_module *const module_inst, + uint32_t status); + +void i2s_disable_status_interrupt( + struct i2s_module *const module_inst, + uint32_t status); + +/** @}*/ + +/** + * \name Data Read/Write + * @{ + */ + +/** + * \brief Write a data word to the specified Serializer of I<SUP>2</SUP>S module + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] serializer The Serializer to write to + * \param[in] data The data to write + * + */ +static inline void i2s_serializer_write_wait( + const struct i2s_module *const module_inst, + enum i2s_serializer serializer, + uint32_t data) +{ + uint32_t sync_bit, ready_bit; + + Assert(module_inst); + Assert(module_inst->hw); + + ready_bit = I2S_INTFLAG_TXRDY0 << serializer; + while (!(module_inst->hw->INTFLAG.reg & ready_bit)) { + /* Wait until ready to transmit */ + } + sync_bit = I2S_SYNCBUSY_DATA0 << serializer; + while (module_inst->hw->SYNCBUSY.reg & sync_bit) { + /* Wait sync */ + } + /* Write data */ + module_inst->hw->DATA[serializer].reg = data; + module_inst->hw->INTFLAG.reg = ready_bit; +} + +/** + * \brief Read a data word from the specified Serializer of I<SUP>2</SUP>S module + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] serializer The Serializer to read + */ +static inline uint32_t i2s_serializer_read_wait( + const struct i2s_module *const module_inst, + enum i2s_serializer serializer) +{ + uint32_t sync_bit, ready_bit; + uint32_t data; + + Assert(module_inst); + Assert(module_inst->hw); + + ready_bit = I2S_INTFLAG_RXRDY0 << serializer; + while (!(module_inst->hw->INTFLAG.reg & ready_bit)) { + /* Wait until ready to transmit */ + } + sync_bit = I2S_SYNCBUSY_DATA0 << serializer; + while (module_inst->hw->SYNCBUSY.reg & sync_bit) { + /* Wait sync */ + } + /* Read data */ + data = module_inst->hw->DATA[serializer].reg; + module_inst->hw->INTFLAG.reg = ready_bit; + return data; +} + +enum status_code i2s_serializer_write_buffer_wait( + const struct i2s_module *const module_inst, + enum i2s_serializer serializer, + void *buffer, uint32_t size); + +enum status_code i2s_serializer_read_buffer_wait( + const struct i2s_module *const module_inst, + enum i2s_serializer serializer, + void *buffer, uint32_t size); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +/** @} */ + + +/** + * \page asfdoc_sam0_i2s_extra Extra Information for I2S Driver + * + * \section asfdoc_sam0_i2s_extra_acronyms Acronyms + * Below is a table listing the acronyms used in this module, along with their + * intended meanings. + * + * <table> + * <tr> + * <th>Acronym</th> + * <th>Description</th> + * </tr> + * <tr> + * <td>I<SUP>2</SUP>S, IIS</td> + * <td>Inter-IC Sound Controller</td> + * </tr> + * <tr> + * <td>MCK</td> + * <td>Master Clock</td> + * </tr> + * <tr> + * <td>SCK</td> + * <td>Serial Clock</td> + * </tr> + * <tr> + * <td>FS</td> + * <td>Frame Sync</td> + * </tr> + * <tr> + * <td>SD</td> + * <td>Serial Data</td> + * </tr> + * <tr> + * <td>ADC</td> + * <td>Analog-to-Digital Converter</td> + * </tr> + * <tr> + * <td>DAC</td> + * <td>Digital-to-Analog Converter</td> + * </tr> + * <tr> + * <td>TDM</td> + * <td>Time Division Multiplexed</td> + * </tr> + * <tr> + * <td>PDM</td> + * <td>Pulse Density Modulation</td> + * </tr> + * <tr> + * <td>LSB</td> + * <td>Least Significant Bit</td> + * </tr> + * <tr> + * <td>MSB</td> + * <td>Most Significant Bit</td> + * </tr> + * <tr> + * <td>DSP</td> + * <td>Digital Signal Processor</td> + * </tr> + * </table> + * + * + * \section asfdoc_sam0_i2s_extra_dependencies Dependencies + * This driver has the following dependencies: + * + * - \ref asfdoc_sam0_system_pinmux_group "System Pin Multiplexer Driver" + * + * + * \section asfdoc_sam0_i2s_extra_errata Errata + * There are no errata related to this driver. + * + * + * \section asfdoc_sam0_i2s_extra_history Module History + * An overview of the module history is presented in the table below, with + * details on the enhancements and fixes made to the module since its first + * release. The current version of this corresponds to the newest version in + * the table. + * + * <table> + * <tr> + * <th>Changelog</th> + * </tr> + * <tr> + * <td>Initial Release</td> + * </tr> + * </table> + */ + +/** + * \page asfdoc_sam0_i2s_exqsg Examples for I2S Driver + * + * This is a list of the available Quick Start guides (QSGs) and example + * applications for \ref asfdoc_sam0_i2s_group. QSGs are simple examples with + * step-by-step instructions to configure and use this driver in a selection of + * use cases. Note that QSGs can be compiled as a standalone application or be + * added to the user application. + * + * - \subpage asfdoc_sam0_i2s_basic_use_case + * \if I2S_CALLBACK_MODE + * - \subpage asfdoc_sam0_i2s_callback_use_case + * \endif + * - \subpage asfdoc_sam0_i2s_dma_use_case + * + * \page asfdoc_sam0_i2s_document_revision_history Document Revision History + * + * <table> + * <tr> + * <th>Doc. Rev.</th> + * <th>Date</th> + * <th>Comments</th> + * </tr> + * <tr> + * <td>42255B</td> + * <td>12/2015</td> + * <td>Added support for SAM DA1</td> + * </tr> + * <tr> + * <td>42255A</td> + * <td>01/2014</td> + * <td>Initial release</td> + * </tr> + * </table> + */ + +#endif /* #ifndef I2S_H_INCLUDED */ diff --git a/atmel-samd/asf/sam0/drivers/i2s/i2s_callback.c b/atmel-samd/asf/sam0/drivers/i2s/i2s_callback.c new file mode 100644 index 000000000..fae543c11 --- /dev/null +++ b/atmel-samd/asf/sam0/drivers/i2s/i2s_callback.c @@ -0,0 +1,392 @@ +/** + * \file + * + * \brief SAM I<SUP>2</SUP>S - Inter-IC Sound Controller + * + * Copyright (C) 2014-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit <a href="http://www.atmel.com/design-support/">Atmel Support</a> + */ + +#include "i2s_callback.h" + +struct i2s_module *_i2s_instances[I2S_INST_NUM]; + +static void _i2s_interrupt_handler(const uint8_t instance) +{ + struct i2s_module *module = _i2s_instances[instance]; + struct i2s_serializer_module *data_module; + + /* Get interrupt flags */ + uint32_t intflag = module->hw->INTFLAG.reg; + uint32_t inten = intflag & module->hw->INTENSET.reg; + uint32_t run_flags = (I2S_INTFLAG_TXUR0 | I2S_INTFLAG_RXOR0); + uint32_t ready_flags = (I2S_INTFLAG_TXRDY0 | I2S_INTFLAG_RXRDY0); + uint32_t call_mask; + uint8_t serializer; + + for (serializer = 0; serializer < 2; serializer ++) { + data_module = &module->serializer[serializer]; + call_mask = data_module->registered_callback_mask & + data_module->enabled_callback_mask; + + if (intflag & (run_flags | ready_flags)) { + /* Serializer Tx ready */ + if ((I2S_INTFLAG_TXRDY0 << serializer) & inten) { + + if (data_module->transferred_words < + data_module->requested_words) { + + /* Write data word */ + while (module->hw->SYNCBUSY.reg & + (I2S_SYNCBUSY_DATA0 << serializer)) { + /* Wait sync */ + } + switch(data_module->data_size) { + case I2S_DATA_SIZE_32BIT: + case I2S_DATA_SIZE_24BIT: + case I2S_DATA_SIZE_20BIT: + case I2S_DATA_SIZE_18BIT: + module->hw->DATA[serializer].reg = + ((uint32_t*)data_module->job_buffer) \ + [data_module->transferred_words]; + break; + case I2S_DATA_SIZE_16BIT: + case I2S_DATA_SIZE_16BIT_COMPACT: + module->hw->DATA[serializer].reg = + ((uint16_t*)data_module->job_buffer) \ + [data_module->transferred_words]; + break; + default: + module->hw->DATA[serializer].reg = + ((uint8_t*)data_module->job_buffer) \ + [data_module->transferred_words]; + } + /* Clear interrupt status */ + module->hw->INTFLAG.reg = I2S_INTFLAG_TXRDY0 << serializer; + + /* Count data */ + data_module->transferred_words ++; + } + + /* Check if the buffer is done */ + if (data_module->transferred_words >= + data_module->requested_words) { + /* It's done */ + data_module->job_status = STATUS_OK; + /* Disable interrupt */ + module->hw->INTENCLR.reg = + I2S_INTFLAG_TXRDY0 << serializer; + /* Invoke callback */ + if ((1 << I2S_SERIALIZER_CALLBACK_BUFFER_DONE) & + call_mask) { + (data_module->callback \ + [I2S_SERIALIZER_CALLBACK_BUFFER_DONE])(module); + } + } + return; + } + /* Serializer Rx ready */ + if ((I2S_INTFLAG_RXRDY0 << serializer) & inten) { + /* Read data word */ + switch(data_module->data_size) { + case I2S_DATA_SIZE_32BIT: + case I2S_DATA_SIZE_24BIT: + case I2S_DATA_SIZE_20BIT: + case I2S_DATA_SIZE_18BIT: + ((uint32_t*)data_module->job_buffer) \ + [data_module->transferred_words] = + module->hw->DATA[serializer].reg; + break; + case I2S_DATA_SIZE_16BIT: + case I2S_DATA_SIZE_16BIT_COMPACT: + ((uint16_t*)data_module->job_buffer) \ + [data_module->transferred_words] = + (uint16_t)module->hw->DATA[serializer].reg; + break; + default: + ((uint8_t*)data_module->job_buffer) \ + [data_module->transferred_words] = + (uint8_t)module->hw->DATA[serializer].reg; + + } + /* Clear interrupt status */ + module->hw->INTFLAG.reg = I2S_INTFLAG_RXRDY0 << serializer; + + /* Count data */ + data_module->transferred_words ++; + + /* Check if the buffer is done */ + if (data_module->transferred_words >= + data_module->requested_words) { + if (data_module->job_status == STATUS_BUSY) { + data_module->job_status = STATUS_OK; + /* Disable interrupt */ + module->hw->INTENCLR.reg = + I2S_INTFLAG_RXRDY0 << serializer; + /* Invoke callback */ + if ((1 << I2S_SERIALIZER_CALLBACK_BUFFER_DONE) & + call_mask) { + (data_module->callback \ + [I2S_SERIALIZER_CALLBACK_BUFFER_DONE])(module); + } + } + } + return; + } + /* Serializer Tx undrerun or Rx overrun */ + if (run_flags & inten) { + module->hw->INTFLAG.reg = I2S_INTFLAG_TXUR0 << serializer; + if ((1 << I2S_SERIALIZER_CALLBACK_OVER_UNDER_RUN) & + call_mask) { + (data_module->callback \ + [I2S_SERIALIZER_CALLBACK_OVER_UNDER_RUN])(module); + } + return; + } + } + run_flags <<= 1; + ready_flags <<= 1; + } + +} + +/** Interrupt handler for the I<SUP>2</SUP>S module */ +void I2S_Handler(void) +{ + _i2s_interrupt_handler(0); +} + +/** + * \brief Write buffer to the specified Serializer of I<SUP>2</SUP>S module + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] serializer The serializer to write to + * \param[in] buffer The data buffer to write + * \param[in] size Number of data words to write + * + * \return Status of the initialization procedure. + * + * \retval STATUS_OK The data was sent successfully + * \retval STATUS_ERR_DENIED The serializer is not in transmit mode + * \retval STATUS_ERR_INVALID_ARG An invalid buffer pointer was supplied + */ +enum status_code i2s_serializer_write_buffer_job( + struct i2s_module *const module_inst, + const enum i2s_serializer serializer, + const void *buffer, + const uint32_t size) +{ + struct i2s_serializer_module *data_module; + + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + Assert(serializer < I2S_SERIALIZER_N); + + data_module = &module_inst->serializer[serializer]; + + /* Serializer must in transmit mode */ + if (data_module->mode != I2S_SERIALIZER_TRANSMIT) { + return STATUS_ERR_DENIED; + } + + /* Buffer should be aligned */ + switch(data_module->data_size) { + case I2S_DATA_SIZE_32BIT: + case I2S_DATA_SIZE_24BIT: + case I2S_DATA_SIZE_20BIT: + case I2S_DATA_SIZE_18BIT: + if ((uint32_t)buffer & 0x3) { + return STATUS_ERR_INVALID_ARG; + } + break; + case I2S_DATA_SIZE_16BIT: + case I2S_DATA_SIZE_16BIT_COMPACT: + if ((uint32_t)buffer & 0x1) { + return STATUS_ERR_INVALID_ARG; + } + break; + default: + break; + } + + data_module = &module_inst->serializer[serializer]; + if (data_module->job_status == STATUS_BUSY) { + return STATUS_BUSY; + } + + data_module->job_status = STATUS_BUSY; + data_module->requested_words = size; + data_module->transferred_words = 0; + data_module->job_buffer = (void*)buffer; + + module_inst->hw->INTENSET.reg = (I2S_INTENSET_TXRDY0 << serializer); + + return STATUS_OK; +} + +/** + * \brief Read from the specified Serializer of I<SUP>2</SUP>S module to a buffer + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] serializer The serializer to write to + * \param[out] buffer The buffer to fill read data + * \param[in] size Number of data words to read + * + * \return Status of the initialization procedure. + * + * \retval STATUS_OK The data was sent successfully + * \retval STATUS_ERR_DENIED The serializer is not in receive mode + * \retval STATUS_ERR_INVALID_ARG An invalid buffer pointer was supplied + */ +enum status_code i2s_serializer_read_buffer_job( + struct i2s_module *const module_inst, + const enum i2s_serializer serializer, + void *buffer, + const uint32_t size) +{ + struct i2s_serializer_module *data_module; + + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + Assert(serializer < I2S_SERIALIZER_N); + + data_module = &module_inst->serializer[serializer]; + + /* Serializer must in receive mode */ + if (data_module->mode == I2S_SERIALIZER_TRANSMIT) { + return STATUS_ERR_DENIED; + } + + /* Data buffer must be aligned */ + switch(data_module->data_size) { + case I2S_DATA_SIZE_32BIT: + case I2S_DATA_SIZE_24BIT: + case I2S_DATA_SIZE_20BIT: + case I2S_DATA_SIZE_18BIT: + if ((uint32_t)buffer & 0x3) { + return STATUS_ERR_INVALID_ARG; + } + break; + case I2S_DATA_SIZE_16BIT: + case I2S_DATA_SIZE_16BIT_COMPACT: + if ((uint32_t)buffer & 0x1) { + return STATUS_ERR_INVALID_ARG; + } + break; + default: + break; + } + + data_module = &module_inst->serializer[serializer]; + if (data_module->job_status == STATUS_BUSY) { + return STATUS_BUSY; + } + + data_module->job_status = STATUS_BUSY; + data_module->requested_words = size; + data_module->transferred_words = 0; + data_module->job_buffer = (void*)buffer; + + module_inst->hw->INTENCLR.reg = (I2S_INTENSET_RXRDY0 << serializer); + module_inst->hw->INTENSET.reg = (I2S_INTENSET_RXRDY0 << serializer); + + return STATUS_OK; +} + +/** + * \brief Aborts an ongoing job running on serializer + * + * Aborts an ongoing job. + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] serializer The serializer which runs the job + * \param[in] job_type Type of job to abort + */ +void i2s_serializer_abort_job( + struct i2s_module *const module_inst, + const enum i2s_serializer serializer, + const enum i2s_job_type job_type) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + Assert(serializer < I2S_SERIALIZER_N); + + if (job_type == I2S_JOB_WRITE_BUFFER) { + /* Disable interrupt */ + module_inst->hw->INTENCLR.reg = (I2S_INTENCLR_TXRDY0 << serializer); + /* Mark job as aborted */ + module_inst->serializer[serializer].job_status = STATUS_ABORTED; + } else if (job_type == I2S_JOB_READ_BUFFER) { + /* Disable interrupt */ + module_inst->hw->INTENCLR.reg = (I2S_INTENCLR_RXRDY0 << serializer); + /* Mark job as aborted */ + module_inst->serializer[serializer].job_status = STATUS_ABORTED; + } +} + +/** + * \brief Gets the status of a job running on serializer + * + * Gets the status of an ongoing or the last job. + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] serializer The serializer which runs the job + * \param[in] job_type Type of job to abort + * + * \return Status of the job. + */ +enum status_code i2s_serializer_get_job_status( + const struct i2s_module *const module_inst, + const enum i2s_serializer serializer, + const enum i2s_job_type job_type) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(serializer < I2S_SERIALIZER_N); + + if (job_type == I2S_JOB_WRITE_BUFFER || job_type == I2S_JOB_READ_BUFFER) { + return module_inst->serializer[serializer].job_status; + } else { + return STATUS_ERR_INVALID_ARG; + } +} diff --git a/atmel-samd/asf/sam0/drivers/i2s/i2s_callback.h b/atmel-samd/asf/sam0/drivers/i2s/i2s_callback.h new file mode 100644 index 000000000..6fa98f3e1 --- /dev/null +++ b/atmel-samd/asf/sam0/drivers/i2s/i2s_callback.h @@ -0,0 +1,234 @@ +/** + * \file + * + * \brief SAM I2S - Inter-IC Sound Controller + * + * Copyright (C) 2014-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit <a href="http://www.atmel.com/design-support/">Atmel Support</a> + */ + +#ifndef I2S_CALLBACK_H_INCLUDED +#define I2S_CALLBACK_H_INCLUDED + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \addtogroup asfdoc_sam0_i2s_group + * + * @{ + */ + +#include <i2s.h> + +/** + * Enum for the possible types of I<SUP>2</SUP>S asynchronous jobs that may be issued to + * the driver. + */ +enum i2s_job_type { + /** Asynchronous I<SUP>2</SUP>S write from a user provided buffer */ + I2S_JOB_WRITE_BUFFER, + /** Asynchronous I<SUP>2</SUP>S read into a user provided buffer */ + I2S_JOB_READ_BUFFER +}; + +/** + * \name Callback Management + * @{ + */ + +/** + * \brief Registers a callback for serializer + * + * Registers a callback function which is implemented by the user. + * + * \note The callback must be enabled by for the interrupt handler to call it + * when the condition for the callback is met. + * + * \param[in] module Pointer to ADC software instance struct + * \param[in] serializer The serializer that generates callback + * \param[in] callback_func Pointer to callback function + * \param[in] callback_type Callback type given by an enum + * + */ +static inline void i2s_serializer_register_callback( + struct i2s_module *const module_inst, + const enum i2s_serializer serializer, + const i2s_serializer_callback_t callback_func, + const enum i2s_serializer_callback callback_type) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(serializer < I2S_SERIALIZER_N); + + module_inst->serializer[serializer].callback[callback_type] = callback_func; + module_inst->serializer[serializer].registered_callback_mask |= + (1u << callback_type); +} + +/** + * \brief Unregisters a callback for serializer + * + * Unregisters a callback function which is implemented by the user. + * + * \param[in] module Pointer to ADC software instance struct + * \param[in] serializer The serializer that generates callback + * \param[in] callback_type Callback type given by an enum + * + */ +static inline void i2s_serializer_unregister_callback( + struct i2s_module *const module_inst, + const enum i2s_serializer serializer, + const enum i2s_serializer_callback callback_type) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(serializer < I2S_SERIALIZER_N); + + module_inst->serializer[serializer].callback[callback_type] = NULL; + module_inst->serializer[serializer].registered_callback_mask &= + ~(1u << callback_type); +} + +/** + * \brief Enables callback for serializer + * + * Enables the callback function registered by \ref + * i2s_serializer_register_callback. The callback function will be called from + * the interrupt handler when the conditions for the callback type are met. + * + * \param[in] module Pointer to ADC software instance struct + * \param[in] serializer The serializer that generates callback + * \param[in] callback_type Callback type given by an enum + * + */ +static inline void i2s_serializer_enable_callback( + struct i2s_module *const module_inst, + const enum i2s_serializer serializer, + const enum i2s_serializer_callback callback_type) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + Assert(serializer < I2S_SERIALIZER_N); + + module_inst->serializer[serializer].enabled_callback_mask |= + (1u << callback_type); + if (I2S_SERIALIZER_CALLBACK_OVER_UNDER_RUN != callback_type) { + return; + } + module_inst->hw->INTENSET.reg = + (module_inst->serializer[serializer].mode == I2S_SERIALIZER_TRANSMIT) ? + (I2S_INTFLAG_TXUR0 << serializer) : + (I2S_INTFLAG_RXOR0 << serializer); +} + +/** + * \brief Disables callback for Serializer + * + * Disables the callback function registered by the \ref + * i2s_serializer_register_callback. + * + * \param[in] module Pointer to ADC software instance struct + * \param[in] serializer The serializer that generates callback + * \param[in] callback_type Callback type given by an enum + * + */ +static inline void i2s_serializer_disable_callback( + struct i2s_module *const module_inst, + const enum i2s_serializer serializer, + const enum i2s_serializer_callback callback_type) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + Assert(serializer < I2S_SERIALIZER_N); + + module_inst->serializer[serializer].enabled_callback_mask &= + ~(1u << callback_type); + if (I2S_SERIALIZER_CALLBACK_OVER_UNDER_RUN != callback_type) { + return; + } + module_inst->hw->INTENCLR.reg = + (module_inst->serializer[serializer].mode == I2S_SERIALIZER_TRANSMIT) ? + (I2S_INTFLAG_TXUR0 << serializer) : + (I2S_INTFLAG_RXOR0 << serializer); +} + +/** @} */ + +/** + * \name Job Management + * + * @{ + */ + +enum status_code i2s_serializer_write_buffer_job( + struct i2s_module *const module_inst, + const enum i2s_serializer serializer, + const void *buffer, + const uint32_t size); + +enum status_code i2s_serializer_read_buffer_job( + struct i2s_module *const module_inst, + const enum i2s_serializer serializer, + void *buffer, + const uint32_t size); + +void i2s_serializer_abort_job( + struct i2s_module *const module_inst, + const enum i2s_serializer serializer, + const enum i2s_job_type job_type); + +enum status_code i2s_serializer_get_job_status( + const struct i2s_module *const module_inst, + const enum i2s_serializer serializer, + const enum i2s_job_type job_type); + +/** @} */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* #ifndef I2S_CALLBACK_H_INCLUDED */ diff --git a/atmel-samd/boards/circuitplayground_express/pins.c b/atmel-samd/boards/circuitplayground_express/pins.c index 098292ff5..046844738 100644 --- a/atmel-samd/boards/circuitplayground_express/pins.c +++ b/atmel-samd/boards/circuitplayground_express/pins.c @@ -36,8 +36,8 @@ STATIC const mp_map_elem_t board_global_dict_table[] = { { MP_OBJ_NEW_QSTR(MP_QSTR_IR_TX), (mp_obj_t)&pin_PA23 }, { MP_OBJ_NEW_QSTR(MP_QSTR_IR_PROXIMITY), (mp_obj_t)&pin_PA04 }, - { MP_OBJ_NEW_QSTR(MP_QSTR_MICROPHONE_SCK), (mp_obj_t)&pin_PA10 }, - { MP_OBJ_NEW_QSTR(MP_QSTR_MICROPHONE_DO), (mp_obj_t)&pin_PA08 }, + { MP_OBJ_NEW_QSTR(MP_QSTR_MICROPHONE_CLOCK), (mp_obj_t)&pin_PA10 }, + { MP_OBJ_NEW_QSTR(MP_QSTR_MICROPHONE_DATA), (mp_obj_t)&pin_PA08 }, { MP_OBJ_NEW_QSTR(MP_QSTR_ACCELEROMETER_INTERRUPT), (mp_obj_t)&pin_PA13 }, { MP_OBJ_NEW_QSTR(MP_QSTR_ACCELEROMETER_SDA), (mp_obj_t)&pin_PA00 }, diff --git a/atmel-samd/common-hal/audiobusio/PDMIn.c b/atmel-samd/common-hal/audiobusio/PDMIn.c new file mode 100644 index 000000000..0b8837abd --- /dev/null +++ b/atmel-samd/common-hal/audiobusio/PDMIn.c @@ -0,0 +1,320 @@ +/* + * This file is part of the Micro Python project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2017 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include <stdint.h> +#include <string.h> + +#include "py/gc.h" +#include "py/mperrno.h" +#include "py/runtime.h" +#include "common-hal/analogio/AnalogOut.h" +#include "common-hal/audiobusio/PDMIn.h" +#include "shared-bindings/analogio/AnalogOut.h" +#include "shared-bindings/audiobusio/PDMIn.h" +#include "shared-bindings/microcontroller/Pin.h" + +#include "asf/sam0/drivers/port/port.h" +#include "samd21_pins.h" + +#include "shared_dma.h" +#include "tick.h" + +void pdmin_reset(void) { + while (I2S->SYNCBUSY.reg & I2S_SYNCBUSY_ENABLE) {} + I2S->INTENCLR.reg = I2S_INTENCLR_MASK; + I2S->INTFLAG.reg = I2S_INTFLAG_MASK; + I2S->CTRLA.reg &= ~I2S_SYNCBUSY_ENABLE; + while (I2S->SYNCBUSY.reg & I2S_SYNCBUSY_ENABLE) {} + I2S->CTRLA.reg = I2S_CTRLA_SWRST; +} + +void common_hal_audiobusio_pdmin_construct(audiobusio_pdmin_obj_t* self, + const mcu_pin_obj_t* clock_pin, + const mcu_pin_obj_t* data_pin, + uint32_t frequency, + uint8_t bit_depth, + bool mono, + uint8_t oversample) { + self->clock_pin = clock_pin; // PA10, PA20 -> SCK0, PB11 -> SCK1 + if (clock_pin == &pin_PA10 + #ifdef PIN_PA20 + || clock_pin == &pin_PA20 + #endif + ) { + self->clock_unit = 0; + #ifdef PIN_PB11 + } else if (clock_pin == &pin_PB11) { + self->clock_unit = 1; + #endif + } else { + mp_raise_ValueError("Invalid clock pin"); + } + + self->data_pin = data_pin; // PA07, PA19 -> SD0, PA08, PB16 -> SD1 + + if (data_pin == &pin_PA07 || data_pin == &pin_PA19) { + self->serializer = 0; + } else if (data_pin == &pin_PA08 + #ifdef PB16 + || data_pin == &pin_PB16) { + #else + ) { + #endif + self->serializer = 1; + } else { + mp_raise_ValueError("Invalid data pin"); + } + + claim_pin(clock_pin); + claim_pin(data_pin); + + if (MP_STATE_VM(audiodma_block_counter) == NULL && + !allocate_block_counter()) { + mp_raise_RuntimeError("Unable to allocate audio DMA block counter."); + } + + if (bit_depth != 16 || !mono || oversample != 64) { + mp_raise_NotImplementedError(""); + } + + // TODO(tannewt): Use the DPLL to get a more precise sampling rate. + // DFLL -> GCLK (/600 for 8khz, /300 for 16khz and /150 for 32khz) -> DPLL (*(63 + 1)) -> GCLK ( / 10) -> 512khz + + i2s_init(&self->i2s_instance, I2S); + struct i2s_clock_unit_config config_clock_unit; + i2s_clock_unit_get_config_defaults(&config_clock_unit); + config_clock_unit.clock.gclk_src = GCLK_GENERATOR_3; + + config_clock_unit.clock.mck_src = I2S_MASTER_CLOCK_SOURCE_GCLK; + config_clock_unit.clock.mck_out_enable = false; + + config_clock_unit.clock.sck_src = I2S_SERIAL_CLOCK_SOURCE_MCKDIV; + config_clock_unit.clock.sck_div = 8000000 / frequency / oversample; + self->frequency = 8000000 / config_clock_unit.clock.sck_div / oversample; + + config_clock_unit.frame.number_slots = 2; + config_clock_unit.frame.slot_size = I2S_SLOT_SIZE_16_BIT; + config_clock_unit.frame.data_delay = I2S_DATA_DELAY_1; + + config_clock_unit.frame.frame_sync.width = I2S_FRAME_SYNC_WIDTH_SLOT; + + config_clock_unit.mck_pin.enable = false; + config_clock_unit.sck_pin.enable = true; + config_clock_unit.sck_pin.gpio = self->clock_pin->pin; + // Mux is always the same. + config_clock_unit.sck_pin.mux = 6L; + config_clock_unit.fs_pin.enable = false; + i2s_clock_unit_set_config(&self->i2s_instance, self->clock_unit, &config_clock_unit); + + struct i2s_serializer_config config_serializer; + i2s_serializer_get_config_defaults(&config_serializer); + config_serializer.clock_unit = self->clock_unit; + config_serializer.mode = I2S_SERIALIZER_PDM2; + config_serializer.data_size = I2S_DATA_SIZE_32BIT; + config_serializer.data_pin.gpio = self->data_pin->pin; + // Mux is always the same. + config_serializer.data_pin.mux = 6L; + config_serializer.data_pin.enable = true; + i2s_serializer_set_config(&self->i2s_instance, self->serializer, &config_serializer); + i2s_enable(&self->i2s_instance); + + self->bytes_per_sample = oversample >> 3; + self->bit_depth = bit_depth; +} + +void common_hal_audiobusio_pdmin_deinit(audiobusio_pdmin_obj_t* self) { + i2s_disable(&self->i2s_instance); + i2s_reset(&self->i2s_instance); +} + +uint8_t common_hal_audiobusio_pdmin_get_bit_depth(audiobusio_pdmin_obj_t* self) { + return self->bit_depth; +} + +uint32_t common_hal_audiobusio_pdmin_get_frequency(audiobusio_pdmin_obj_t* self) { + return self->frequency; +} + +static void setup_dma(audiobusio_pdmin_obj_t* self, uint32_t length, + DmacDescriptor* second_descriptor, + uint8_t words_per_buffer, uint8_t words_per_sample, + uint32_t* first_buffer, uint32_t* second_buffer) { + // Set up the DMA + struct dma_descriptor_config descriptor_config; + dma_descriptor_get_config_defaults(&descriptor_config); + descriptor_config.beat_size = DMA_BEAT_SIZE_WORD; + descriptor_config.step_selection = DMA_STEPSEL_SRC; + descriptor_config.source_address = (uint32_t)&I2S->DATA[self->serializer]; + descriptor_config.src_increment_enable = false; + // Block transfer count is the number of beats per block (aka descriptor). + // In this case there are two bytes per beat so divide the length by two. + uint16_t block_transfer_count = words_per_buffer; + if (length * words_per_sample < words_per_buffer) { + block_transfer_count = length * words_per_sample; + } + descriptor_config.block_transfer_count = block_transfer_count; + descriptor_config.destination_address = ((uint32_t) first_buffer + sizeof(uint32_t) * block_transfer_count); + descriptor_config.event_output_selection = DMA_EVENT_OUTPUT_BLOCK; + descriptor_config.next_descriptor_address = 0; + if (length * words_per_sample > words_per_buffer) { + descriptor_config.next_descriptor_address = ((uint32_t)second_descriptor); + } + dma_descriptor_create(audio_dma.descriptor, &descriptor_config); + + if (length * words_per_sample > words_per_buffer) { + block_transfer_count = words_per_buffer; + descriptor_config.next_descriptor_address = ((uint32_t)audio_dma.descriptor); + if (length * words_per_sample < 2 * words_per_buffer) { + block_transfer_count = 2 * words_per_buffer - length * words_per_sample; + descriptor_config.next_descriptor_address = 0; + } + descriptor_config.block_transfer_count = block_transfer_count; + descriptor_config.destination_address = ((uint32_t) second_buffer + sizeof(uint32_t) * block_transfer_count); + dma_descriptor_create(second_descriptor, &descriptor_config); + } + + switch_audiodma_trigger(I2S_DMAC_ID_RX_0 + self->serializer); +} + +void start_dma(audiobusio_pdmin_obj_t* self) { + dma_start_transfer_job(&audio_dma); + tc_start_counter(MP_STATE_VM(audiodma_block_counter)); + i2s_clock_unit_enable(&self->i2s_instance, self->clock_unit); + i2s_serializer_enable(&self->i2s_instance, self->serializer); + I2S->DATA[1].reg = I2S->DATA[1].reg; +} + +void stop_dma(audiobusio_pdmin_obj_t* self) { + // Turn off the I2S clock and serializer. Peripheral is still enabled. + i2s_serializer_disable(&self->i2s_instance, self->serializer); + i2s_clock_unit_disable(&self->i2s_instance, self->clock_unit); + + // Shutdown the DMA + tc_stop_counter(MP_STATE_VM(audiodma_block_counter)); + dma_abort_job(&audio_dma); +} + +static const uint16_t sinc_filter[64] = { + 0, 1, 6, 16, 29, 49, 75, 108, + 149, 200, 261, 334, 418, 514, 622, 742, + 872, 1012, 1161, 1315, 1472, 1631, 1787, 1938, + 2081, 2212, 2329, 2429, 2509, 2568, 2604, 2616, + 2604, 2568, 2509, 2429, 2329, 2212, 2081, 1938, + 1787, 1631, 1472, 1315, 1161, 1012, 872, 742, + 622, 514, 418, 334, 261, 200, 149, 108, + 75, 49, 29, 16, 6, 1, 0, 0 +}; + +static uint16_t filter_sample(uint32_t pdm_samples[4]) { + uint16_t sample = 0; + for (uint8_t i = 0; i < 4; i++) { + uint16_t pdm = pdm_samples[i] & 0xffff; + for (uint8_t j = 0; j < 16; j++) { + if ((pdm & 0x8000) != 0) { + sample += sinc_filter[i * 16 + j]; + } + pdm <<= 1; + } + } + return sample; +} + +uint32_t common_hal_audiobusio_pdmin_record_to_buffer(audiobusio_pdmin_obj_t* self, + uint16_t* output_buffer, uint32_t length) { + // Write the wave file header. + + // We allocate two 256 byte buffers on the stack to use for double buffering. + // Our oversample rate is 64 (bits) so each buffer produces 32 samples. + // TODO(tannewt): Can the compiler optimize better if we fix the size of + // these buffers? + uint8_t samples_per_buffer = 32; + // For every word we record, we throw away 2 bytes of a phantom second channel. + uint8_t words_per_sample = self->bytes_per_sample / 2; + uint8_t words_per_buffer = samples_per_buffer * words_per_sample; + uint32_t first_buffer[words_per_buffer]; + uint32_t second_buffer[words_per_buffer]; + + COMPILER_ALIGNED(16) DmacDescriptor second_descriptor; + + setup_dma(self, length, &second_descriptor, words_per_buffer, + words_per_sample, first_buffer, second_buffer); + + start_dma(self); + + // Record + uint32_t buffers_processed = 0; + uint32_t total_bytes = 0; + + uint64_t start_ticks = ticks_ms; + while (total_bytes < length) { + // Wait for the next buffer to fill + while (tc_get_count_value(MP_STATE_VM(audiodma_block_counter)) == buffers_processed) { + #ifdef MICROPY_VM_HOOK_LOOP + MICROPY_VM_HOOK_LOOP + #endif + } + if (tc_get_count_value(MP_STATE_VM(audiodma_block_counter)) != (buffers_processed + 1)) { + break; + } + // Throw away the first ~10ms of data because thats during mic start up. + if (ticks_ms - start_ticks < 10) { + buffers_processed++; + continue; + } + uint32_t* buffer = first_buffer; + DmacDescriptor* descriptor = audio_dma.descriptor; + if (buffers_processed % 2 == 1) { + buffer = second_buffer; + descriptor = &second_descriptor; + } + // Decimate and filter the last buffer + int32_t samples_gathered = descriptor->BTCNT.reg / words_per_sample; + for (uint16_t i = 0; i < samples_gathered; i++) { + if (self->bit_depth == 8) { + ((uint8_t*) output_buffer)[total_bytes] = filter_sample(buffer + i * words_per_sample) >> 8; + total_bytes += 1; + } else if (self->bit_depth == 16) { + output_buffer[total_bytes / 2] = filter_sample(buffer + i * words_per_sample); + total_bytes += 2; + } + } + buffers_processed++; + + if (length - total_bytes < samples_per_buffer) { + descriptor->BTCNT.reg = (length - total_bytes) * words_per_sample; + descriptor->DSTADDR.reg = ((uint32_t) buffer) + (length - total_bytes) * self->bytes_per_sample; + descriptor->DESCADDR.reg = 0; + } + } + + stop_dma(self); + + return total_bytes; +} + +void common_hal_audiobusio_pdmin_record_to_file(audiobusio_pdmin_obj_t* self, uint8_t* buffer, uint32_t length) { + +} diff --git a/atmel-samd/common-hal/audiobusio/PDMIn.h b/atmel-samd/common-hal/audiobusio/PDMIn.h new file mode 100644 index 000000000..beeae566e --- /dev/null +++ b/atmel-samd/common-hal/audiobusio/PDMIn.h @@ -0,0 +1,53 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2017 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#ifndef __MICROPY_INCLUDED_ATMEL_SAMD_COMMON_HAL_AUDIOBUSIO_AUDIOOUT_H__ +#define __MICROPY_INCLUDED_ATMEL_SAMD_COMMON_HAL_AUDIOBUSIO_AUDIOOUT_H__ + +#include "common-hal/microcontroller/Pin.h" +#include "asf/sam0/drivers/i2s/i2s.h" +#include "asf/sam0/drivers/tc/tc.h" + +#include "extmod/vfs_fat_file.h" +#include "py/obj.h" + +typedef struct { + mp_obj_base_t base; + const mcu_pin_obj_t *clock_pin; + const mcu_pin_obj_t *data_pin; + uint32_t frequency; + struct i2s_module i2s_instance; + uint8_t serializer; + uint8_t clock_unit; + uint8_t bytes_per_sample; + uint8_t bit_depth; +} audiobusio_pdmin_obj_t; + +void pdmin_reset(void); + +void pdmin_background(void); + +#endif // __MICROPY_INCLUDED_ATMEL_SAMD_COMMON_HAL_AUDIOBUSIO_AUDIOOUT_H__ diff --git a/atmel-samd/common-hal/audiobusio/__init__.c b/atmel-samd/common-hal/audiobusio/__init__.c new file mode 100644 index 000000000..87db40496 --- /dev/null +++ b/atmel-samd/common-hal/audiobusio/__init__.c @@ -0,0 +1 @@ +// No audiobusio module functions. diff --git a/atmel-samd/common-hal/audioio/AudioOut.c b/atmel-samd/common-hal/audioio/AudioOut.c index 30562d1a9..b9961466c 100644 --- a/atmel-samd/common-hal/audioio/AudioOut.c +++ b/atmel-samd/common-hal/audioio/AudioOut.c @@ -76,7 +76,7 @@ void audioout_reset(void) { // Only reset DMA. PWMOut will reset the timer. Other code will reset the DAC. refcount = 0; MP_STATE_VM(audioout_sample_timer) = NULL; - MP_STATE_VM(audioout_block_counter) = NULL; + MP_STATE_VM(audiodma_block_counter) = NULL; MP_STATE_VM(audioout_dac_instance) = NULL; if (MP_STATE_VM(audioout_sample_event) != NULL) { @@ -85,10 +85,10 @@ void audioout_reset(void) { } MP_STATE_VM(audioout_sample_event) = NULL; - if (MP_STATE_VM(audioout_block_event) != NULL) { - events_release(MP_STATE_VM(audioout_block_event)); + if (MP_STATE_VM(audiodma_block_event) != NULL) { + events_release(MP_STATE_VM(audiodma_block_event)); } - MP_STATE_VM(audioout_block_event) = NULL; + MP_STATE_VM(audiodma_block_event) = NULL; if (MP_STATE_VM(audioout_dac_event) != NULL) { events_detach_user(MP_STATE_VM(audioout_dac_event), EVSYS_ID_USER_DMAC_CH_0); @@ -102,12 +102,12 @@ void audioout_reset(void) { // WARN(tannewt): DO NOT print from here. It calls background tasks and causes a // stack overflow. void audioout_background(void) { - if (MP_STATE_VM(audioout_block_counter) != NULL && + if (MP_STATE_VM(audiodma_block_counter) != NULL && active_audioout != NULL && active_audioout->second_buffer != NULL && - active_audioout->last_loaded_block < tc_get_count_value(MP_STATE_VM(audioout_block_counter))) { + active_audioout->last_loaded_block < tc_get_count_value(MP_STATE_VM(audiodma_block_counter))) { uint8_t* buffer; - if (tc_get_count_value(MP_STATE_VM(audioout_block_counter)) % 2 == 1) { + if (tc_get_count_value(MP_STATE_VM(audiodma_block_counter)) % 2 == 1) { buffer = active_audioout->buffer; } else { buffer = active_audioout->second_buffer; @@ -148,82 +148,6 @@ void audioout_background(void) { } } -static void allocate_block_counter(audioio_audioout_obj_t* self) { - // Find a timer to count DMA block completions. - Tc *t = NULL; - Tc *tcs[TC_INST_NUM] = TC_INSTS; - for (uint8_t i = TC_INST_NUM; i > 0; i--) { - if (tcs[i - 1]->COUNT16.CTRLA.bit.ENABLE == 0) { - t = tcs[i - 1]; - break; - } - } - if (t == NULL) { - common_hal_audioio_audioout_deinit(self); - mp_raise_RuntimeError("All timers in use"); - return; - } - MP_STATE_VM(audioout_block_counter) = gc_alloc(sizeof(struct tc_module), false); - if (MP_STATE_VM(audioout_block_counter) == NULL) { - common_hal_audioio_audioout_deinit(self); - mp_raise_msg(&mp_type_MemoryError, ""); - } - - // Don't bother setting the period. We set it before you playback anything. - struct tc_config config_tc; - tc_get_config_defaults(&config_tc); - config_tc.counter_size = TC_COUNTER_SIZE_16BIT; - config_tc.clock_prescaler = TC_CLOCK_PRESCALER_DIV1; - if (tc_init(MP_STATE_VM(audioout_block_counter), t, &config_tc) != STATUS_OK) { - common_hal_audioio_audioout_deinit(self); - mp_raise_OSError(MP_EIO); - return; - }; - - struct tc_events events_tc; - events_tc.generate_event_on_overflow = false; - events_tc.on_event_perform_action = true; - events_tc.event_action = TC_EVENT_ACTION_INCREMENT_COUNTER; - tc_enable_events(MP_STATE_VM(audioout_block_counter), &events_tc); - - // Connect the timer overflow event, which happens at the target frequency, - // to the DAC conversion trigger. - MP_STATE_VM(audioout_block_event) = gc_alloc(sizeof(struct events_resource), false); - if (MP_STATE_VM(audioout_block_event) == NULL) { - common_hal_audioio_audioout_deinit(self); - mp_raise_msg(&mp_type_MemoryError, ""); - } - struct events_config config; - events_get_config_defaults(&config); - - uint8_t user = EVSYS_ID_USER_TC3_EVU; - if (t == TC4) { - user = EVSYS_ID_USER_TC4_EVU; - } else if (t == TC5) { - user = EVSYS_ID_USER_TC5_EVU; -#ifdef TC6 - } else if (t == TC6) { - user = EVSYS_ID_USER_TC6_EVU; -#endif -#ifdef TC7 - } else if (t == TC7) { - user = EVSYS_ID_USER_TC7_EVU; -#endif - } - - config.generator = EVSYS_ID_GEN_DMAC_CH_0; - config.path = EVENTS_PATH_ASYNCHRONOUS; - if (events_allocate(MP_STATE_VM(audioout_block_event), &config) != STATUS_OK || - events_attach_user(MP_STATE_VM(audioout_block_event), user) != STATUS_OK) { - common_hal_audioio_audioout_deinit(self); - mp_raise_OSError(MP_EIO); - return; - } - - tc_enable(MP_STATE_VM(audioout_block_counter)); - tc_stop_counter(MP_STATE_VM(audioout_block_counter)); -} - static void shared_construct(audioio_audioout_obj_t* self, const mcu_pin_obj_t* pin) { assert_pin_free(pin); @@ -380,8 +304,8 @@ void common_hal_audioio_audioout_construct_from_file(audioio_audioout_obj_t* sel refcount++; shared_construct(self, pin); } - if (MP_STATE_VM(audioout_block_counter) == NULL) { - allocate_block_counter(self); + if (MP_STATE_VM(audiodma_block_counter) == NULL && !allocate_block_counter()) { + mp_raise_RuntimeError("Unable to allocate audio DMA block counter."); } // Load the wave @@ -519,6 +443,7 @@ void common_hal_audioio_audioout_play(audioio_audioout_obj_t* self, bool loop) { } else { dac_enable(MP_STATE_VM(audioout_dac_instance)); } + switch_audiodma_trigger(DAC_DMAC_ID_EMPTY); struct dma_descriptor_config descriptor_config; dma_descriptor_get_config_defaults(&descriptor_config); if (self->bytes_per_sample == 2) { @@ -580,8 +505,8 @@ void common_hal_audioio_audioout_play(audioio_audioout_obj_t* self, bool loop) { active_audioout = self; dma_start_transfer_job(&audio_dma); - if (MP_STATE_VM(audioout_block_counter) != NULL) { - tc_start_counter(MP_STATE_VM(audioout_block_counter)); + if (MP_STATE_VM(audiodma_block_counter) != NULL) { + tc_start_counter(MP_STATE_VM(audiodma_block_counter)); } set_timer_frequency(self->frequency); tc_start_counter(MP_STATE_VM(audioout_sample_timer)); @@ -589,8 +514,8 @@ void common_hal_audioio_audioout_play(audioio_audioout_obj_t* self, bool loop) { void common_hal_audioio_audioout_stop(audioio_audioout_obj_t* self) { if (active_audioout == self) { - if (MP_STATE_VM(audioout_block_counter) != NULL) { - tc_stop_counter(MP_STATE_VM(audioout_block_counter)); + if (MP_STATE_VM(audiodma_block_counter) != NULL) { + tc_stop_counter(MP_STATE_VM(audiodma_block_counter)); } tc_stop_counter(MP_STATE_VM(audioout_sample_timer)); dma_abort_job(&audio_dma); diff --git a/atmel-samd/main.c b/atmel-samd/main.c index 842dae451..d84c44f86 100644 --- a/atmel-samd/main.c +++ b/atmel-samd/main.c @@ -28,6 +28,7 @@ #include "common-hal/analogio/AnalogIn.h" #include "common-hal/audioio/AudioOut.h" +#include "common-hal/audiobusio/PDMIn.h" #include "common-hal/pulseio/PulseIn.h" #include "common-hal/pulseio/PulseOut.h" #include "common-hal/pulseio/PWMOut.h" @@ -161,13 +162,16 @@ void reset_samd21(void) { } #ifdef EXPRESS_BOARD + audioout_reset(); touchin_reset(); + pdmin_reset(); + pulsein_reset(); + pulseout_reset(); + pwmout_reset(); #endif analogin_reset(); - pulsein_reset(); - pulseout_reset(); // Wait for the DAC to sync then reset. while (DAC->STATUS.reg & DAC_STATUS_SYNCBUSY) {} @@ -175,8 +179,6 @@ void reset_samd21(void) { reset_all_pins(); - audioout_reset(); - pwmout_reset(); usb_hid_reset(); diff --git a/atmel-samd/mpconfigport.h b/atmel-samd/mpconfigport.h index 7755959ea..f28f4b657 100644 --- a/atmel-samd/mpconfigport.h +++ b/atmel-samd/mpconfigport.h @@ -139,6 +139,7 @@ typedef long mp_off_t; extern const struct _mp_obj_module_t microcontroller_module; extern const struct _mp_obj_module_t bitbangio_module; extern const struct _mp_obj_module_t audioio_module; +extern const struct _mp_obj_module_t audiobusio_module; extern const struct _mp_obj_module_t analogio_module; extern const struct _mp_obj_module_t digitalio_module; extern const struct _mp_obj_module_t pulseio_module; @@ -167,6 +168,7 @@ extern const struct _mp_obj_module_t usb_hid_module; #define MICROPY_PY_FRAMEBUF (1) #define EXTRA_BUILTIN_MODULES \ { MP_OBJ_NEW_QSTR(MP_QSTR_audioio), (mp_obj_t)&audioio_module }, \ + { MP_OBJ_NEW_QSTR(MP_QSTR_audiobusio), (mp_obj_t)&audiobusio_module }, \ { MP_OBJ_NEW_QSTR(MP_QSTR_pulseio), (mp_obj_t)&pulseio_module }, \ { MP_OBJ_NEW_QSTR(MP_QSTR_bitbangio), (mp_obj_t)&bitbangio_module } #define EXPRESS_BOARD @@ -218,11 +220,11 @@ extern const struct _mp_obj_module_t usb_hid_module; #define MICROPY_PORT_ROOT_POINTERS \ const char *readline_hist[8]; \ vstr_t *repl_line; \ + struct tc_module* audiodma_block_counter; \ + struct events_resource* audiodma_block_event; \ struct tc_module* audioout_sample_timer; \ - struct tc_module* audioout_block_counter; \ struct dac_module* audioout_dac_instance; \ struct events_resource* audioout_sample_event; \ - struct events_resource* audioout_block_event; \ struct events_resource* audioout_dac_event; \ struct tc_module* pulseout_tc_instance; \ FLASH_ROOT_POINTERS \ diff --git a/atmel-samd/shared_dma.c b/atmel-samd/shared_dma.c index 9c82b249b..bffd37880 100644 --- a/atmel-samd/shared_dma.c +++ b/atmel-samd/shared_dma.c @@ -25,7 +25,14 @@ */ #include "shared_dma.h" +#include "py/gc.h" +#include "py/mpstate.h" + +#include "asf/sam0/drivers/events/events.h" #include "asf/sam0/drivers/system/interrupt/system_interrupt.h" +#include "asf/sam0/drivers/tc/tc.h" + +#undef ENABLE // We allocate two DMA resources for the entire lifecycle of the board (not the // vm) because the general_dma resource will be shared between the REPL and SPI @@ -72,16 +79,21 @@ static uint8_t sercom_index(Sercom* sercom) { return ((uint32_t) sercom - (uint32_t) SERCOM0) / 0x400; } -static void dma_configure(uint8_t channel, uint8_t trigsrc) { +static void dma_configure(uint8_t channel, uint8_t trigsrc, bool output_event) { system_interrupt_enter_critical_section(); /** Select the DMA channel and clear software trigger */ DMAC->CHID.reg = DMAC_CHID_ID(channel); DMAC->CHCTRLA.reg &= ~DMAC_CHCTRLA_ENABLE; DMAC->CHCTRLA.reg = DMAC_CHCTRLA_SWRST; DMAC->SWTRIGCTRL.reg &= (uint32_t)(~(1 << channel)); - DMAC->CHCTRLB.reg = DMAC_CHCTRLB_LVL(DMA_PRIORITY_LEVEL_0) | \ - DMAC_CHCTRLB_TRIGSRC(trigsrc) | \ - DMAC_CHCTRLB_TRIGACT(DMA_TRIGGER_ACTION_BEAT); + uint32_t event_output_enable = 0; + if (output_event) { + event_output_enable = DMAC_CHCTRLB_EVOE; + } + DMAC->CHCTRLB.reg = DMAC_CHCTRLB_LVL(DMA_PRIORITY_LEVEL_0) | + DMAC_CHCTRLB_TRIGSRC(trigsrc) | + DMAC_CHCTRLB_TRIGACT(DMA_TRIGGER_ACTION_BEAT) | + event_output_enable; system_interrupt_leave_critical_section(); } @@ -89,7 +101,7 @@ enum status_code shared_dma_write(Sercom* sercom, const uint8_t* buffer, uint32_ if (general_dma_tx.job_status != STATUS_OK) { return general_dma_tx.job_status; } - dma_configure(general_dma_tx.channel_id, sercom_index(sercom) * 2 + 2); + dma_configure(general_dma_tx.channel_id, sercom_index(sercom) * 2 + 2, false); // Set up TX second. struct dma_descriptor_config descriptor_config; @@ -128,8 +140,8 @@ enum status_code shared_dma_read(Sercom* sercom, uint8_t* buffer, uint32_t lengt return general_dma_tx.job_status; } - dma_configure(general_dma_tx.channel_id, sercom_index(sercom) * 2 + 2); - dma_configure(general_dma_rx.channel_id, sercom_index(sercom) * 2 + 1); + dma_configure(general_dma_tx.channel_id, sercom_index(sercom) * 2 + 2, false); + dma_configure(general_dma_rx.channel_id, sercom_index(sercom) * 2 + 1, false); // Set up RX first. struct dma_descriptor_config descriptor_config; @@ -168,3 +180,76 @@ enum status_code shared_dma_read(Sercom* sercom, uint8_t* buffer, uint32_t lengt while (sercom->SPI.INTFLAG.bit.RXC == 1) {} return general_dma_rx.job_status; } + +bool allocate_block_counter() { + // Find a timer to count DMA block completions. + Tc *t = NULL; + Tc *tcs[TC_INST_NUM] = TC_INSTS; + for (uint8_t i = TC_INST_NUM; i > 0; i--) { + if (tcs[i - 1]->COUNT16.CTRLA.bit.ENABLE == 0) { + t = tcs[i - 1]; + break; + } + } + if (t == NULL) { + return false; + } + MP_STATE_VM(audiodma_block_counter) = gc_alloc(sizeof(struct tc_module), false); + if (MP_STATE_VM(audiodma_block_counter) == NULL) { + return false; + } + + // Don't bother setting the period. We set it before you playback anything. + struct tc_config config_tc; + tc_get_config_defaults(&config_tc); + config_tc.counter_size = TC_COUNTER_SIZE_16BIT; + config_tc.clock_prescaler = TC_CLOCK_PRESCALER_DIV1; + if (tc_init(MP_STATE_VM(audiodma_block_counter), t, &config_tc) != STATUS_OK) { + return false; + }; + + struct tc_events events_tc; + events_tc.generate_event_on_overflow = false; + events_tc.on_event_perform_action = true; + events_tc.event_action = TC_EVENT_ACTION_INCREMENT_COUNTER; + tc_enable_events(MP_STATE_VM(audiodma_block_counter), &events_tc); + + // Connect the timer overflow event, which happens at the target frequency, + // to the DAC conversion trigger. + MP_STATE_VM(audiodma_block_event) = gc_alloc(sizeof(struct events_resource), false); + if (MP_STATE_VM(audiodma_block_event) == NULL) { + return false; + } + struct events_config config; + events_get_config_defaults(&config); + + uint8_t user = EVSYS_ID_USER_TC3_EVU; + if (t == TC4) { + user = EVSYS_ID_USER_TC4_EVU; + } else if (t == TC5) { + user = EVSYS_ID_USER_TC5_EVU; +#ifdef TC6 + } else if (t == TC6) { + user = EVSYS_ID_USER_TC6_EVU; +#endif +#ifdef TC7 + } else if (t == TC7) { + user = EVSYS_ID_USER_TC7_EVU; +#endif + } + + config.generator = EVSYS_ID_GEN_DMAC_CH_0; + config.path = EVENTS_PATH_ASYNCHRONOUS; + if (events_allocate(MP_STATE_VM(audiodma_block_event), &config) != STATUS_OK || + events_attach_user(MP_STATE_VM(audiodma_block_event), user) != STATUS_OK) { + return false; + } + + tc_enable(MP_STATE_VM(audiodma_block_counter)); + tc_stop_counter(MP_STATE_VM(audiodma_block_counter)); + return true; +} + +void switch_audiodma_trigger(uint8_t trigger_dmac_id) { + dma_configure(audio_dma.channel_id, trigger_dmac_id, true); +} diff --git a/atmel-samd/shared_dma.h b/atmel-samd/shared_dma.h index 190001b6b..380d561c6 100644 --- a/atmel-samd/shared_dma.h +++ b/atmel-samd/shared_dma.h @@ -33,9 +33,15 @@ extern struct dma_resource audio_dma; extern struct dma_resource general_dma_tx; extern struct dma_resource general_dma_rx; +volatile bool audio_dma_in_use; + void init_shared_dma(void); enum status_code shared_dma_write(Sercom* sercom, const uint8_t* buffer, uint32_t length); enum status_code shared_dma_read(Sercom* sercom, uint8_t* buffer, uint32_t length, uint8_t tx); +// Allocate a counter to track how far along we are in a DMA double buffer. +bool allocate_block_counter(void); +void switch_audiodma_trigger(uint8_t trigger_dmac_id); + #endif // __MICROPY_INCLUDED_ATMEL_SAMD_SHARED_DMA_H__ diff --git a/atmel-samd/spi_flash.c b/atmel-samd/spi_flash.c index bf1f190c8..4a58b13be 100644 --- a/atmel-samd/spi_flash.c +++ b/atmel-samd/spi_flash.c @@ -137,6 +137,19 @@ static bool write_flash(uint32_t address, const uint8_t* data, uint32_t data_len if (!spi_flash_is_initialised) { return false; } + // Don't bother writing if the data is all 1s. Thats equivalent to the flash + // state after an erase. + bool all_ones = true; + for (uint16_t i = 0; i < data_length; i++) { + if (data[i] != 0xff) { + all_ones = false; + break; + } + } + if (all_ones) { + return true; + } + for (uint32_t bytes_written = 0; bytes_written < data_length; bytes_written += SPI_FLASH_PAGE_SIZE) { @@ -145,12 +158,14 @@ static bool write_flash(uint32_t address, const uint8_t* data, uint32_t data_len } enum status_code status; + #ifdef SPI_FLASH_SECTOR_PROTECTION // Print out the protection status. - uint8_t protect_check[5] = {0x3C, 0x00, 0x00, 0x00, 0x00}; - address_to_bytes(address + bytes_written, protect_check + 1); - flash_enable(); - status = spi_write_buffer_wait(&spi_flash_instance, protect_check, 5); - flash_disable(); + // uint8_t protect_check[5] = {0x3C, 0x00, 0x00, 0x00, 0x00}; + // address_to_bytes(address + bytes_written, protect_check + 1); + // flash_enable(); + // status = spi_write_buffer_wait(&spi_flash_instance, protect_check, 5); + // flash_disable(); + #endif flash_enable(); uint8_t command[4] = {CMD_PAGE_PROGRAM, 0x00, 0x00, 0x00}; @@ -167,6 +182,34 @@ static bool write_flash(uint32_t address, const uint8_t* data, uint32_t data_len return true; } +static bool page_erased(uint32_t sector_address) { + // Check the first few bytes to catch the common case where there is data + // without using a bunch of memory. + uint8_t short_buffer[4]; + if (read_flash(sector_address, short_buffer, 4)) { + for (uint16_t i = 0; i < 4; i++) { + if (short_buffer[i] != 0xff) { + return false; + } + } + } else { + return false; + } + + // Now check the full length. + uint8_t full_buffer[FILESYSTEM_BLOCK_SIZE]; + if (read_flash(sector_address, full_buffer, FILESYSTEM_BLOCK_SIZE)) { + for (uint16_t i = 0; i < FILESYSTEM_BLOCK_SIZE; i++) { + if (short_buffer[i] != 0xff) { + return false; + } + } + } else { + return false; + } + return true; +} + // Erases the given sector. Make sure you copied all of the data out of it you // need! Also note, sector_address is really 24 bits. static bool erase_sector(uint32_t sector_address) { @@ -553,9 +596,14 @@ bool spi_flash_write_block(const uint8_t *data, uint32_t block) { uint32_t this_sector = address & (~(SPI_FLASH_ERASE_SIZE - 1)); uint8_t block_index = (address / FILESYSTEM_BLOCK_SIZE) % (SPI_FLASH_ERASE_SIZE / FILESYSTEM_BLOCK_SIZE); uint8_t mask = 1 << (block_index); - // Flush the cache if we're moving onto a sector our we're writing the + // Flush the cache if we're moving onto a sector or we're writing the // same block again. if (current_sector != this_sector || (mask & dirty_mask) > 0) { + // Check to see if we'd write to an erased page. In that case we + // can write directly. + if (page_erased(address)) { + return write_flash(address, data, FILESYSTEM_BLOCK_SIZE); + } if (current_sector != NO_SECTOR_LOADED) { spi_flash_flush_keep_cache(true); } |
