https://gist.github.com/RickKimball/8bc … 6f73ccf2e9
To use it in your program do something like this. include the header file, create an instance of dwt_timer, call its init() function in setup(). Then use the delay_cycles() function with the number of cycles you want to delay.
//
#include "dwt_timer.h"
static const dwt_timer usec_timer;
void setup() {
usec_timer.init();
}
void loop() {
DoSomething1();
usec_timer.delay_cycles((usec2cycles(1)-0)); /* optionally subtract cycles to deal with DoSomething1()'s overhead */
DoSomething2();
usec_timer.delay_cycles((usec2cycles(9)-0));
}
Perhaps the current delay() can be replaced with this version.
I looked at the current version some time ago, and leaflabs made an effort to get the timing right, but from the comments I’ve seen on the original maple forum, basically the delay function is not very accurate.
Here is another code snippet, using the dwt_timer.get() method to figure out how many cycles the digitalWrite functions take, and account for them with the delay:
// slightly more accurate usec blink
#include "dwt_timer.h"
#define PIN PB12
static const dwt_timer usec_timer;
void setup() {
pinMode(PIN, OUTPUT);
usec_timer.init();
}
void loop() {
uint32_t s0, e0;
s0 = usec_timer.get();
digitalWrite(PIN,1);
e0 = usec_timer.get();
const uint32_t overhead = e0-s0;
digitalWrite(PIN,0);
const uint32_t overhead1 = (e0-s0) + 21; /* the 21 hmm .. just kept tweaking until it was 10 usec cycle*/
while(1) {
digitalWrite(PIN,1);
usec_timer.delay_cycles(usec2cycles(1)-(overhead));
digitalWrite(PIN,0);
usec_timer.delay_cycles(usec2cycles(9)-(overhead1));
}
}
OK.
Its definitely worth bearing in mind, as a future replacement to delay() (and microsecond delay)
wonder if it was a good idea in general purpose code because of that..
Of course I can see its value in situations where you need a low overhead accurate delay, very useful. But if its
used to replace delay(), which is often sprinkled all through code..
Of course I could be talking rubbish – does it actually interfere? Need to go read the actual code when I head is clearer
(damn meetings, the enemy of productivity!)
wonder if it was a good idea in general purpose code because of that..
-rick
Well, that made me gulp my coffee!
Sounds like a CERN poster for: Quark Strangeness and Charm
https://www.youtube.com/watch?v=lFPLgGWMndc
Ray
<…>
Fortunately, on the cortex-m3 they do provide a Debug Watchpoint Trace peripheral that can be hijacked and used to implement a delay_cycles function. I created a class and packaged it up as a header file here:

