TEMPLATES speed UP ARDUINO I/O

It is simple to forget, however the Arduino does utilize C++. Typically, the C++ part is in the libraries as well as the framework as well as many people just tend to code their main programs utilizing a C-style just utilizing the library objects like C-language extensions. [Fredllll] just recently produced a design template library to speed up Arduino I/O as well as he shared it on GitHub.

If you’ve ever done anything major with the Arduino, you most likely understand that while digitalWrite is handy, it does a great deal of work behind the scenes to make sure the pin is configuration as well as this adds overhead to every call. [Fredllll’s] design template versions can switch a pin’s specify in two cycles. You can cut that in half if you don’t mind bothering the specify of other pins on the exact same port.

You can utilize a constant to turn on a pin, like this:

switchOn<1>();
If you don’t like to utilize magic numbers (and that’s smart) you can define a constant:

const uint8_t ledPin=1;
switchOn();
Because you most likely want to do some elegant timing, there’s likewise a nop design template that lets you delay a set number of cycles. Here’s some test code from Reddit that produces 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(); // 1 cycle
nop<5>(); // 5 cycles
switchOffPortOfPin(); // 1 cycle
nop<3>(); // 3 cycles
} while(1) //jump back to do is 2 cycles
}
Obviously, this isn’t the maximum, either, because there are eight delay cycles in the loop.

You don’t requirement to understand much about templates to utilize this library, however if you want to understand more, we’ve covered them in the past. We’ve noted before that digitalWrite is about fifty times slower than a direct port access, as well as the other I/O operations aren’t much better. It would be fascinating to check out if templates might make other operations much more efficient.

Leave a Reply

Your email address will not be published. Required fields are marked *