Sync DAC and ADC for a measurement

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
capucsc
Posts: 4
Joined: Fri Nov 27, 2015 3:23 am

Sync DAC and ADC for a measurement

Post by capucsc » Fri Nov 27, 2015 3:30 am

Hi all,

I'm trying to sync a DAC waveform write with an ADC read. Both the adc and the dac are clocked to the same timer. I've noticed, using the code below, that there is an offset between the readout and the DAC buffer. I guess this is to be expected, as there is no trigger to synchronise the start of both the ADC and DAC. Any ideas on how best to implement a trigger like this?

Code: Select all

import math
import pyb

tim = pyb.Timer(6, freq=1000)         # create a timer running at 1000Hz
adc = pyb.ADC(pyb.Pin.board.X19)    # create an ADC on pin X19
dac = pyb.DAC(1)


# create a buffer containing a sine-wave
buf = bytearray(500)
for i in range(len(buf)):
    buf[i] = 128 + int(127 * math.sin(4 * math.pi * i / len(buf)))

# output the sine-wave at 400Hz
dac.write_timed(buf, tim, mode=DAC.CIRCULAR)

# Setup the read buffer
abuf = bytearray(500)                # create a buffer to store the samples
adc.read_timed(abuf, tim)            # sample 100 values, taking 10s

for enu,i in enumerate(buf): 
    print(i, abuf[enu])

User avatar
dhylands
Posts: 3821
Joined: Mon Jan 06, 2014 6:08 pm
Location: Peachland, BC, Canada
Contact:

Re: Sync DAC and ADC for a measurement

Post by dhylands » Fri Nov 27, 2015 5:59 am

I think the read_timed function is synchronous, so it will read all of the values before returning.
It looks like the DAC write_timed is async.

So I think that if you do the dac write immediately followed by the adc read, then they'll be close to synchronized.

Otherwise, you could try adding a callback to your timer, and have it read a single sample from the adc and write a single sample to the dac.

Post Reply