It is easy to forget, but the Arduino does use C++. Typically, the C++ part is in the libraries and the framework and most people just tend to code their main programs using a C-style just using the library objects like C-language extensions. [Fredllll] recently created a template library to speed up Arduino I/O and he shared it on GitHub.
If you’ve ever done anything serious with the Arduino, you probably know that while digitalWrite is handy, it does a lot of work behind the scenes to make sure the pin is setup and this adds overhead to every call. [Fredllll’s] template versions can switch a pin’s state in two cycles. You can cut that in half if you don’t mind bothering the state of other pins on the same port.
You can use a constant to turn on a pin, like this:
switchOn<1>();
If you don’t like to use magic numbers (and that’s smart) you can define a constant:
const uint8_t ledPin=1; switchOn<ledPin>();
Because you probably want to do some fancy timing, there’s also a nop template that lets you delay a set number of cycles. Here’s some test code from Reddit that generates a 1.3 MHz square wave, for example:
const uint8_t myPin = 5; void loop(){ cli(); //disable interrupts as they would screw up the timing do { switchOnExclusive<myPin>(); // 1 cycle nop<5>(); // 5 cycles switchOffPortOfPin<myPin>(); // 1 cycle nop<3>(); // 3 cycles } while(1) //jump back to do is 2 cycles }
Obviously, this isn’t the maximum, either, since there are eight delay cycles in the loop.
You don’t need to know much about templates to use this library, but if you want to know more, we’ve covered them in the past. We’ve noted before that digitalWrite is about fifty times slower than a direct port access, and the other I/O operations aren’t much better. It would be interesting to explore if templates could make other operations more efficient.
Filed under: news
No comments:
Post a Comment