mmarchetti / DirectIO

Fast, simple I/O library for Arduino
GNU Lesser General Public License v3.0
116 stars 27 forks source link

How to use in function #31

Closed simeon9696 closed 3 years ago

simeon9696 commented 3 years ago

How would I pass a pin into a function?

#include <DirectIO.h> 

Output<2> pin;

void togglePin(Output pinObject){
  pinObject.toggle();
}
mmarchetti commented 3 years ago

You have a couple options. One would be to use an OutputPin:

void togglePin(OutputPin& pinObject){
  pinObject.toggle();
}

This is simplest but you don't get the maximum speed.

The other way is to use a template function, so the pin can be a template instance. Something along the lines of:

template<u8 pin>
void togglePin(Output<pin> pinObject){
  pinObject.toggle();
}

This gets you the maximum speed, but note that the compiler will create an instance of the togglePin function code for each unique pin that uses it. For large functions that are used multiple times, that will consume more code space. It also requires a bit more C++ knowledge to get right, especially if you have multiple template parameters.