Monday, August 1, 2011

Code changes

I've experienced that the Arduino seem to be slow sometimes, especially when writing values. So I did a little research and tested stuff on my own - and the Arduino is not slow. But the code is.

For instance:

Using regular digitalWrites, 2500 on/off cycles:   35764 microseconds.
Using digitalWriteFast, 2500 on/off cycles:            2614 microseconds.

The old code is almost 14 (!) times slower than the new code! Damn...
Of course, there are caveats. It requires the pin number AND state to be static and known at compile time. Most of us do this all the time anyway (const, #define etc) so it's not a big deal.

The syntaxes are similar, if not identical, too.

Old: digitalWrite(PINNR, STATE);
New: digitalWriteFast(PINNR, STATE);

The static STATE can be avoided by simply doing something similar to:
if (someState) 
   digitalWriteFast(PINNR, HIGH);
  digitalWriteFast(PINNR, LOW);

So - If your are developing on Arduino, download the digitalWriteFast library before doing any coding! It's  A LOT faster and doesn't require that much planning ahead. I've already begun converting my code (and redesigning it along the way) to gain the juicy speedup.

The numbers where taken from the top of my head so I don't remember the two last digits of each value, but the magnitude of the values are correct. With a 14x speedup, the last two digits are indeed the least significant values. 

No comments:

Post a Comment