Question

I'm having trouble getting consistent results with the code I am using. I want to run my Arduino for a specific amount of time (say 20 seconds) and collect data from the analog pin with a specific sampling rate (say four samples a second). The code is as follows.

a_pin = 0;
tic;
i = 0;

while toc < 20
    i = i + 1;
    time(i) = toc;
    v(i) = a.analogRead(a_pin);
    pause(.25);
end

Is there a way to set the loop to run a specific time and then in the loop sample at a different rate?

Was it helpful?

Solution

You can try this:

a_pin = 0;

fs = 4;   % sampling frequency (samplings per second)
mt = 20;  % time for measurements

ind = 1;
nind = 1;
last_beep = 0;
tic;
while toc < mt

    time(ind) = toc;
    v(ind) = a.analogRead(a_pin);

    % wait for appropriate time for next measurement
    while( nind == ind )
        nind = floor(toc*fs) + 1;
    end
    ind = nind;

    % beep every second
    if (ceil(toc) > last_beep)
        beep(); % don't know if this one exist, check docs
        last_beep = ceil(toc);
    end
end 

OTHER TIPS

Maximal sampling time for a single Arduino analog read command is around 0.04 s, in practice I'd go minimally 0.05. Adding two read operations is in the order of 2*0.04, in practice more like 0.1 s. I think it is mainly limited by the USB communication speeds.

I am also new at arduino, but having implemented a real time analysis for EEG using it, on practice, I was able to sample 2 analog channels with a samplinf frequency between 57 and 108Hz. It was very variable (calculated through tic/toc), but it is still proper for realtime processing in my case.

My code uses a While loop, a series of memory updates, digital pin manipulations, plot of trace (drawnow) and seems to run smoothly enough

My answer is simply here : 0.0283 sec for sampling 2 analog inputs in my case.

Cheers

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top