I have to generate a ramp with a fairly precise slope interspersed with a 1 second pause, and I got good results by connecting an old DAC (the DA1280), driven on the 8 most significant bits, connected to the L port of the arduino MEGA, and quickly writing the portL with the 256 values in sequence. The sketch is the following:
void setup() {
DDRL=B11111111;
}
void loop() {
for(int y=255;y>-1;y--){
PORTL=y;
delayMicroseconds(1); //ritardo tra un campione ed il successivo del DAC, ovvero durata della rampa
}
PORTL=255;
delay(1000);
}
The duration of this ramp is my problem, because with:
delayMicroseconds (1); the ramp lasts 100µsec delayMicroseconds (2); the ramp lasts 300µsec delayMicroseconds (3); the ramp lasts 520µsec delayMicroseconds (4); the ramp lasts 800µsec delayMicroseconds (5); the ramp lasts 1000µsec delayMicroseconds (6); the ramp lasts 1400µsec
(times measured with an oscilloscope).
I would also like to obtain intermediate values, such as 150, 200, 250, 300, 350 and so on, in steps of ABOUT 50µsec. What do you recommend?
I thought I was wasting some time with some "useless operation", like sums or other, to put after the delayMicroseconds (), but first I would like your opinion.
Many thanks
This function works very accurately in the range 3 microseconds and up to 16383
For accurate delays you need to turn off interrupts and can use avrlibc delays
_delay_loop_1 executes three CPU cycles per iteration, not including the overhead the compiler needs to setup the counter register. (187.5 ns/loop @ 16 MHz)
And, of course, take into account the precise instruction timing of the for loop.
The NOP instruction is a single instruction delay. You can put as many NOP instructions after each other to get a precise delay.
The compiler can do that for you with the function "__builtin_avr_delay_cycles()".
The compiler does not call a function, but replaces that with NOP instructions or any other combination of instructions and iterations to get to the exact number of clock cycle delay.
Since Arduino does not use the WatchDog, you can turn off the Arduino environment by disabling the interrupts. After that, you can no longer use Arduino functions, such as delay().
Did you know that the 'C' language uses 0b11111111 and that Arduino has defined B11111111 somewhere in a include file ?
The for-statement is too vague for precise timing, so I removed it. This is my experiment: