+ /* Eneble hw trigger */
+ DACC_MR |= BV(DACC_TRGEN) | (CONFIG_DAC_TIMER << DACC_TRGSEL_SHIFT);
+ dac->hw->rate = rate;
+}
+
+static void sam3x_dac_conversion(struct Dac *dac, void *buf, size_t len)
+{
+ /* setup timer and start it */
+ tc_setup(dac->hw->rate, len);
+ tc_start();
+
+ /* Setup dma and start it */
+ DACC_TPR = (uint32_t)buf;
+ DACC_TCR = len;
+ DACC_PTCR |= BV(DACC_PTCR_TXTEN);
+}
+
+static uint16_t *sample_buff;
+static size_t next_idx = 0;
+static size_t chunk_size = 0;
+static size_t remaing_size = 0;
+
+static DECLARE_ISR(irq_dac)
+{
+ if (DACC_ISR & BV(DACC_ENDTX))
+ {
+ if (remaing_size > 0)
+ {
+ DACC_TNPR = (uint32_t)&sample_buff[next_idx];
+ DACC_TNCR = chunk_size;
+
+ remaing_size -= chunk_size;
+ next_idx += chunk_size;
+ }
+ else
+ /* Clear the pending irq when the dma ends the conversion */
+ DACC_TCR = 1;
+ }
+ event_do(&buff_emtpy);
+}
+
+
+static bool sam3x_dac_isFinished(struct Dac *dac)
+{
+ return dac->hw->end;
+}
+
+static void sam3x_dac_start(struct Dac *dac, void *_buf, size_t len, size_t slice_len)
+{
+ ASSERT(dac);
+ ASSERT(len >= slice_len);
+
+ /* Reset the previous status. */
+ dac->hw->end = false;
+
+ sample_buff = (uint16_t *)_buf;
+ next_idx = 0;
+ chunk_size = slice_len;
+ remaing_size = len;
+
+
+ /* Program the dma with the first and second chunk of samples and update counter */
+ dac->ctx.callback(dac, &sample_buff[0], chunk_size);
+ DACC_TPR = (uint32_t)&sample_buff[0];
+ DACC_TCR = chunk_size;
+ remaing_size -= chunk_size;
+ next_idx += chunk_size;
+
+ if (chunk_size <= remaing_size)
+ {
+ dac->ctx.callback(dac, &sample_buff[next_idx], chunk_size);
+
+ DACC_TNPR = (uint32_t)&sample_buff[next_idx];
+ DACC_TNCR = chunk_size;
+
+ remaing_size -= chunk_size;
+ next_idx += chunk_size;
+
+ }
+
+ DACC_PTCR |= BV(DACC_PTCR_TXTEN);
+ DACC_IER = BV(DACC_ENDTX);
+
+ /* Set up timer and trig the conversions */
+ tc_setup(dac->hw->rate, len);
+ tc_start();
+
+ while (1)
+ {
+ event_wait(&buff_emtpy);
+ if (remaing_size <= 0)
+ {
+ DAC_TC_CCR = BV(TC_CCR_CLKDIS);
+ dac->hw->end = true;
+ next_idx = 0;
+ chunk_size = 0;
+ remaing_size = 0;
+ break;
+ }
+
+ dac->ctx.callback(dac, &sample_buff[next_idx], chunk_size);
+ }
+}
+
+static void sam3x_dac_stop(struct Dac *dac)
+{
+ dac->hw->end = false;
+ /* Disable the irq, timer and channel */
+ DACC_IDR = BV(DACC_ENDTX);
+ DACC_PTCR |= BV(DACC_PTCR_TXTDIS);
+ DAC_TC_CCR = BV(TC_CCR_CLKDIS);
+}
+
+
+void dac_init(struct Dac *dac)
+{
+ /* Initialize the dataready event */
+ event_initGeneric(&buff_emtpy);
+
+ /* Fill the virtual table */
+ dac->ctx.write = sam3x_dac_write;
+ dac->ctx.setCh = sam3x_dac_setCh;
+ dac->ctx.setSampleRate = sam3x_dac_setSampleRate;
+ dac->ctx.conversion = sam3x_dac_conversion;
+ dac->ctx.isFinished = sam3x_dac_isFinished;
+ dac->ctx.start = sam3x_dac_start;
+ dac->ctx.stop = sam3x_dac_stop;
+ DB(dac->ctx._type = DAC_SAM3X;)
+ dac->hw = &dac_hw;
+
+ /* Clock DAC peripheral */