I'm trying to load and unload a capacitor over a resistor, in a short time.
I've made a sketch in which this is done.
I was hoping by including a delay based on a fixed value and on the time spend on certain tasks i could get a very accurate repeating loop.
Looking at my scope the signal varies in time however.
If i print the time spend for each loop on the serial monitor it varies between 324 and 336 microseconds, where is this variation coming from?
I was hoping by including a delay based on a fixed value and on the time spend on certain tasks i could get a very accurate repeating loop.
That's the problem with hoping. It rarely works. There are the millis() and micos() functions that allow you to record when something happened (a task started) and to determine whether another event (stop the task) should happen. See the blink without delay example, without delay.
The plan is to use it at some point.
I was using it in a previous version of the code but i've been throwing things away to get to the source of the problem.
Apparently it is quite difficult (at least for me) to get a stable time signal in the microseconds regime.
Anyone a pointer on how to do this correctly?
Attached skecth is still all over my scope...
KingBee:
Looking at my scope the signal varies in time however.
If i print the time spend for each loop on the serial monitor it varies between 324 and 336 microseconds, where is this variation coming from?
The the microseconds value that delayMicroseconds() function uses has a resolution of 4 microseconds. Plus there is overhead in making the call. You can use one of the timers to get more resolution.
Try this.
In setup() configure timer2 for a 0.5 us resolution with these two statements:
TCCR2A = 0;
TCCR2B = 2;
Then replace each call to delayMicroseconds(100-(time2-time1)) with this:
{uint8_t t0 = TCNT2; while (TCNT2 - t0 < 2*(100-(time2-time1));}
You'll probably find that you need to tweak the number "100" down somewhat to account for the time it takes to execute code.
Read Nick Gammon's web page on timers. It's good stuff.
The goal is to charge and discharge a capacitor over an unknown resistor to determine the value.
As the resistor in this case is a fluid, the polarities need to change with each charge/discharge to prevent accumulation at the probe.
For each discharge the RC time is measured and referred to a lookup table to obtain the fluid resistance.