source: trunk/Arduino/libraries/Adafruit_Circuit_Playground/utility/Adafruit_ZeroPDM.cpp @ 3

Last change on this file since 3 was 3, checked in by markus, 7 years ago

Setup project structure

File size: 13.3 KB
Line 
1// Adafruit Arduino Zero / Feather M0 I2S audio library.
2// Author: Tony DiCola & Limor "ladyada" Fried
3//
4// The MIT License (MIT)
5//
6// Copyright (c) 2016 Adafruit Industries
7//
8// Permission is hereby granted, free of charge, to any person obtaining a copy
9// of this software and associated documentation files (the "Software"), to deal
10// in the Software without restriction, including without limitation the rights
11// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12// copies of the Software, and to permit persons to whom the Software is
13// furnished to do so, subject to the following conditions:
14//
15// The above copyright notice and this permission notice shall be included in all
16// copies or substantial portions of the Software.
17//
18// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24// SOFTWARE.
25#include "Adafruit_ZeroPDM.h"
26
27#if defined(ARDUINO_ARCH_SAMD)
28
29// Define macros for debug output that optimize out when debug mode is disabled.
30#ifdef DEBUG
31  #define DEBUG_PRINT(...) DEBUG_PRINTER.print(__VA_ARGS__)
32  #define DEBUG_PRINTLN(...) DEBUG_PRINTER.println(__VA_ARGS__)
33#else
34  #define DEBUG_PRINT(...)
35  #define DEBUG_PRINTLN(...)
36#endif
37
38
39Adafruit_ZeroPDM::Adafruit_ZeroPDM(int clockpin, int datapin, uint8_t gclk):
40  _gclk(gclk), _clk(clockpin), _data(datapin)  {
41
42}
43
44bool Adafruit_ZeroPDM::begin(void) {
45  // check the pins are valid!
46  _clk_pin = _clk_mux = _data_pin = _data_mux = 0;
47
48  // Clock pin, can only be one of 3 options
49  uint32_t clockport = g_APinDescription[_clk].ulPort;
50  uint32_t clockpin = g_APinDescription[_clk].ulPin;
51  if ((clockport == 0) && (clockpin == 10)) {
52    // PA10
53    _i2sclock = I2S_CLOCK_UNIT_0;
54    _clk_pin = PIN_PA10G_I2S_SCK0;
55    _clk_mux = MUX_PA10G_I2S_SCK0;
56  } else if ((clockport == 1) && (clockpin == 10)) {
57    // PB11
58    _i2sclock = I2S_CLOCK_UNIT_1;
59    _clk_pin = PIN_PB11G_I2S_SCK1;
60    _clk_mux = MUX_PB11G_I2S_SCK1;
61  } else if ((clockport == 0) && (clockpin == 20)) {
62    // PA20
63    _i2sclock = I2S_CLOCK_UNIT_0;
64    _clk_pin = PIN_PA20G_I2S_SCK0;
65    _clk_mux = MUX_PA20G_I2S_SCK0;
66  } else {
67    DEBUG_PRINTLN("Clock isnt on a valid pin");
68    return false;
69  }
70
71  // Data pin, can only be one of 3 options
72  uint32_t datapin = g_APinDescription[_data].ulPin;
73  uint32_t dataport = g_APinDescription[_data].ulPort;
74  if ((dataport == 0) && (datapin == 7)) {
75    // PA07
76    _i2sserializer = I2S_SERIALIZER_0;
77    _data_pin = PIN_PA07G_I2S_SD0;
78    _data_mux = MUX_PA07G_I2S_SD0;
79  } else if ((dataport == 0) && (datapin == 8)) {
80    // PA08
81    _i2sserializer = I2S_SERIALIZER_1;
82    _data_pin = PIN_PA08G_I2S_SD1;
83    _data_mux = MUX_PA08G_I2S_SD1;
84  } else if ((dataport == 0) && (datapin == 19)) {
85    // PA19
86    _i2sserializer = I2S_SERIALIZER_0;
87    _data_pin = PIN_PA19G_I2S_SD0;
88    _data_mux = MUX_PA19G_I2S_SD0;
89  } else {
90    DEBUG_PRINTLN("Data isnt on a valid pin");
91    return false;
92  }
93
94  // Initialize I2S module from the ASF.
95  // replace "status_code res = i2s_init(&_i2s_instance, I2S);
96  //  if (res != STATUS_OK) {
97  //  DEBUG_PRINT("i2s_init failed with result: "); DEBUG_PRINTLN(res);
98  //  return false;
99  // }" with:
100
101  /* Enable the user interface clock in the PM */
102  //system_apb_clock_set_mask(SYSTEM_CLOCK_APB_APBC, PM_APBCMASK_I2S);
103  PM->APBCMASK.reg |= PM_APBCMASK_I2S;
104
105  /* Status check */
106  uint32_t ctrla = I2S->CTRLA.reg;
107  if (ctrla & I2S_CTRLA_ENABLE) {
108    if (ctrla & (I2S_CTRLA_SEREN1 |
109                 I2S_CTRLA_SEREN0 | I2S_CTRLA_CKEN1 | I2S_CTRLA_CKEN0)) {
110      //return STATUS_BUSY;
111      return false;
112    } else {
113      //return STATUS_ERR_DENIED;
114      return false;
115    }
116  }
117
118  /* Initialize module */
119  _hw = I2S;
120
121  return true;
122}
123
124void Adafruit_ZeroPDM::end(void) {
125  while (_hw->SYNCBUSY.reg & I2S_SYNCBUSY_ENABLE); // Sync wait
126  _hw->CTRLA.reg &= ~I2S_SYNCBUSY_ENABLE;
127}
128
129bool Adafruit_ZeroPDM::configure(uint32_t sampleRateHz, boolean stereo) {
130  // Convert bit per sample int into explicit ASF values.
131
132  // Disable I2S while it is being reconfigured to prevent unexpected output.
133  end();
134
135
136  /******************************* Set the GCLK generator config and enable it. *************/
137  {
138    /* Cache new register configurations to minimize sync requirements. */
139    uint32_t new_genctrl_config = (_gclk << GCLK_GENCTRL_ID_Pos);
140    uint32_t new_gendiv_config  = (_gclk << GCLK_GENDIV_ID_Pos);
141   
142    /* Select the requested source clock for the generator */
143    // Set the clock generator to use the 48mhz main CPU clock and divide it down
144    // to the SCK frequency.
145    new_genctrl_config |= GCLK_SOURCE_DFLL48M  << GCLK_GENCTRL_SRC_Pos;
146    uint32_t division_factor = F_CPU / (sampleRateHz*16); // 16 clocks for 16 stereo bits
147   
148    /* Set division factor */
149    if (division_factor > 1) {
150      /* Check if division is a power of two */
151      if (((division_factor & (division_factor - 1)) == 0)) {
152        /* Determine the index of the highest bit set to get the
153         * division factor that must be loaded into the division
154         * register */
155       
156        uint32_t div2_count = 0;
157       
158        uint32_t mask;
159        for (mask = (1UL << 1); mask < division_factor;
160             mask <<= 1) {
161          div2_count++;
162        }
163       
164        /* Set binary divider power of 2 division factor */
165        new_gendiv_config  |= div2_count << GCLK_GENDIV_DIV_Pos;
166        new_genctrl_config |= GCLK_GENCTRL_DIVSEL;
167      } else {
168        /* Set integer division factor */
169       
170        new_gendiv_config  |=
171          (division_factor) << GCLK_GENDIV_DIV_Pos;
172       
173        /* Enable non-binary division with increased duty cycle accuracy */
174        new_genctrl_config |= GCLK_GENCTRL_IDC;
175      } 
176    }
177   
178    noInterrupts();  // cpu_irq_enter_critical();
179
180    while (GCLK->STATUS.reg & GCLK_STATUS_SYNCBUSY);  // Wait for synchronization
181    *((uint8_t*)&GCLK->GENDIV.reg) = _gclk;   /* Select the correct generator */
182
183    while (GCLK->STATUS.reg & GCLK_STATUS_SYNCBUSY);  // Wait for synchronization
184    GCLK->GENDIV.reg  = new_gendiv_config;    /* Write the new generator configuration */
185   
186    while (GCLK->STATUS.reg & GCLK_STATUS_SYNCBUSY);  // Wait for synchronization
187    GCLK->GENCTRL.reg = new_genctrl_config | (GCLK->GENCTRL.reg & GCLK_GENCTRL_GENEN);
188
189    // Replace "system_gclk_gen_enable(_gclk);" with:
190
191    while (GCLK->STATUS.reg & GCLK_STATUS_SYNCBUSY);  // Wait for synchronization
192    *((uint8_t*)&GCLK->GENCTRL.reg) = _gclk;          /* Select the requested generator */
193
194    while (GCLK->STATUS.reg & GCLK_STATUS_SYNCBUSY);  // Wait for synchronization
195    GCLK->GENCTRL.reg |= GCLK_GENCTRL_GENEN;          /* Enable generator */
196   
197    interrupts();  // cpu_irq_leave_critical();
198  }
199 
200  /******************************* Configure I2S clock *************/
201  {
202    /* Status check */
203    /* Busy ? */
204    if (_hw->SYNCBUSY.reg & (I2S_SYNCBUSY_CKEN0 << _i2sclock)) {
205      return false;           //return STATUS_BUSY;
206    }
207    /* Already enabled ? */
208    if (_hw->CTRLA.reg & (I2S_CTRLA_CKEN0 << _i2sclock)) {
209     
210      return false;           //return STATUS_ERR_DENIED;
211    }
212   
213    /***************************** Initialize Clock Unit *************/
214    uint32_t clkctrl = 
215      // I2S_CLKCTRL_MCKOUTINV | // mck out not inverted
216      // I2S_CLKCTRL_SCKOUTINV | // sck out not inverted
217      // I2S_CLKCTRL_FSOUTINV |  // fs not inverted
218      // I2S_CLKCTRL_MCKEN |    // Disable MCK output
219      // I2S_CLKCTRL_MCKSEL |   // Disable MCK output
220      // I2S_CLKCTRL_SCKSEL |   // SCK source is GCLK
221      // I2S_CLKCTRL_FSINV |    // do not invert frame sync
222      // I2S_CLKCTRL_FSSEL |    // Configure FS generation from SCK clock.
223      // I2S_CLKCTRL_BITDELAY |  // No bit delay (PDM)
224      0;
225
226    clkctrl |= I2S_CLKCTRL_MCKOUTDIV(0);
227    clkctrl |= I2S_CLKCTRL_MCKDIV(0);
228    clkctrl |= I2S_CLKCTRL_NBSLOTS(1);  // STEREO is '1' (subtract one from #)
229    clkctrl |= I2S_CLKCTRL_FSWIDTH(I2S_FRAME_SYNC_WIDTH_SLOT);  // Frame Sync (FS) Pulse is 1 Slot width
230    if (stereo) {
231      clkctrl |= I2S_CLKCTRL_SLOTSIZE(I2S_SLOT_SIZE_16_BIT);
232    } else {
233      clkctrl |= I2S_CLKCTRL_SLOTSIZE(I2S_SLOT_SIZE_32_BIT);
234    }
235   
236    /* Write clock unit configurations */
237    _hw->CLKCTRL[_i2sclock].reg = clkctrl;
238   
239    /* Select general clock source */
240    const uint8_t i2s_gclk_ids[2] = {I2S_GCLK_ID_0, I2S_GCLK_ID_1};
241
242    /* Cache the new config to reduce sync requirements */
243    uint32_t new_clkctrl_config = (i2s_gclk_ids[_i2sclock] << GCLK_CLKCTRL_ID_Pos);
244
245    /* Select the desired generic clock generator */
246    new_clkctrl_config |= _gclk << GCLK_CLKCTRL_GEN_Pos;
247
248    /* Disable generic clock channel */
249    noInterrupts();
250
251    /* Select the requested generator channel */
252    *((uint8_t*)&GCLK->CLKCTRL.reg) = i2s_gclk_ids[_i2sclock];
253
254    /* Switch to known-working source so that the channel can be disabled */
255    uint32_t prev_gen_id = GCLK->CLKCTRL.bit.GEN;
256    GCLK->CLKCTRL.bit.GEN = 0;
257
258    /* Disable the generic clock */
259    GCLK->CLKCTRL.reg &= ~GCLK_CLKCTRL_CLKEN;
260    while (GCLK->CLKCTRL.reg & GCLK_CLKCTRL_CLKEN); /* Wait for clock to become disabled */
261
262    /* Restore previous configured clock generator */
263    GCLK->CLKCTRL.bit.GEN = prev_gen_id;
264
265    /* Write the new configuration */
266    GCLK->CLKCTRL.reg = new_clkctrl_config;
267   
268    // enable it
269    *((uint8_t*)&GCLK->CLKCTRL.reg) = i2s_gclk_ids[_i2sclock];   /* Select the requested generator channel */
270    GCLK->CLKCTRL.reg |= GCLK_CLKCTRL_CLKEN;                     /* Enable the generic clock */
271
272    interrupts();
273
274    /* Initialize pins */
275    pinPeripheral(_clk, (EPioType)_clk_mux);
276  }
277
278  /***************************** Configure I2S serializer *************/
279  {
280    /* Status check */
281    /* Busy ? */
282    while (_hw->SYNCBUSY.reg & ((I2S_SYNCBUSY_SEREN0 | I2S_SYNCBUSY_DATA0) << _i2sserializer)) {
283      //return STATUS_BUSY;
284      return false;
285    }
286   
287    /* Already enabled ? */
288    if (_hw->CTRLA.reg & (I2S_CTRLA_CKEN0 << _i2sserializer)) {
289      // return STATUS_ERR_DENIED;
290      return false;
291    }
292   
293    /* Initialize Serializer */
294    uint32_t serctrl =
295      // I2S_SERCTRL_RXLOOP |    // Dont use loopback mode
296      // I2S_SERCTRL_DMA    |    // Single DMA channel for all I2S channels
297      // I2S_SERCTRL_MONO   |    // Dont use MONO mode
298      // I2S_SERCTRL_SLOTDIS7 |  // Dont have any slot disabling
299      // I2S_SERCTRL_SLOTDIS6 |
300      // I2S_SERCTRL_SLOTDIS5 |
301      // I2S_SERCTRL_SLOTDIS4 |
302      // I2S_SERCTRL_SLOTDIS3 |
303      // I2S_SERCTRL_SLOTDIS2 |
304      // I2S_SERCTRL_SLOTDIS1 |
305      // I2S_SERCTRL_SLOTDIS0 |
306      I2S_SERCTRL_BITREV   |  // Do not transfer LSB first (MSB first!)
307      // I2S_SERCTRL_WORDADJ  |  // Data NOT left in word
308      I2S_SERCTRL_SLOTADJ     |  // Data is left in slot
309      // I2S_SERCTRL_TXSAME   |  // Pad 0 on underrun
310      0;
311   
312    // Configure clock unit to use with serializer, and set serializer as an output.
313    if (_i2sclock < 2) {
314      serctrl |= (_i2sclock ? I2S_SERCTRL_CLKSEL : 0);
315    } else {
316      return false;       //return STATUS_ERR_INVALID_ARG;
317    }
318    if (stereo) {
319      serctrl |= I2S_SERCTRL_SERMODE(I2S_SERIALIZER_PDM2); //Serializer is used to receive PDM data on each clock edge
320    } else {
321      serctrl |= I2S_SERCTRL_SERMODE(I2S_SERIALIZER_RECEIVE); // act like I2S
322    }
323
324    // Configure serializer data size.
325    serctrl |=  I2S_SERCTRL_DATASIZE(I2S_DATA_SIZE_32BIT);  // anything other than 32 bits is ridiculous to manage, force this to be 32
326   
327    serctrl |=  I2S_SERCTRL_TXDEFAULT(I2S_LINE_DEFAULT_0) | /** Output default value is 0 */
328                I2S_SERCTRL_EXTEND(I2S_DATA_PADDING_0);     /** Padding 0 in case of under-run */
329   
330    /* Write Serializer configuration */
331    _hw->SERCTRL[_i2sserializer].reg = serctrl;
332   
333    /* Initialize pins */
334    // Enable SD pin.  See Adafruit_ZeroI2S.h for default pin value.
335    pinPeripheral(_data, (EPioType)_data_mux);
336  }
337
338  /***************************** Enable everything configured above *************/
339
340  // Replace "i2s_enable(&_i2s_instance);" with:
341  while (_hw->SYNCBUSY.reg & I2S_SYNCBUSY_ENABLE);  // Sync wait
342  _hw->CTRLA.reg |= I2S_SYNCBUSY_ENABLE;
343 
344  // Replace "i2s_clock_unit_enable(&_i2s_instance, _i2sclock);" with:
345  uint32_t cken_bit = I2S_CTRLA_CKEN0 << _i2sclock;
346  while (_hw->SYNCBUSY.reg & cken_bit); // Sync wait
347  _hw->CTRLA.reg |= cken_bit;
348 
349  // Replace "i2s_serializer_enable(&_i2s_instance, _i2sserializer);" with:
350  uint32_t seren_bit = I2S_CTRLA_SEREN0 << _i2sserializer;
351  while (_hw->SYNCBUSY.reg & seren_bit); // Sync wait
352  _hw->CTRLA.reg |= seren_bit;
353 
354  return true;
355}
356
357uint32_t Adafruit_ZeroPDM::read(void) {
358  // Read the sample from the I2S data register.
359  // This will wait for the I2S hardware to be ready to send the byte.
360  //return i2s_serializer_read_wait(&_i2s_instance, _i2sserializer);
361
362  // replace i2s_serializer_read_wait with deASF'd code:
363  {
364    uint32_t sync_bit, ready_bit;
365    uint32_t data;
366    ready_bit = I2S_INTFLAG_RXRDY0 << _i2sserializer;
367    while (!(_hw->INTFLAG.reg & ready_bit)) {
368      /* Wait until ready to transmit */
369    }
370    sync_bit = I2S_SYNCBUSY_DATA0 << _i2sserializer;
371    while (_hw->SYNCBUSY.reg & sync_bit) {
372      /* Wait sync */
373    }
374    /* Read data */
375    data = _hw->DATA[_i2sserializer].reg;
376    _hw->INTFLAG.reg = ready_bit;
377    return data;
378  }
379}
380
381#endif
Note: See TracBrowser for help on using the repository browser.