I'm working on an Arduino program but am getting bogged down on what is the 'correct' implementation. I understand that multiple versions may work, so for my needs the 'correct' version will be the fastest (i.e. executing in the fewest clock cycles)
I need to set three analog input pins on my Mega 2560 - let's call them PF2-0.
- I could use pinMode() - but that performs some extra checks that I want to leave out.
- I could use _BV() in the process, but that's another function call I wish to avoid.
So, using port manipulation, I can write:
DDRF = 0x07; //PF2, PF1, PF0 as input
PORTF = 0x07; // Disable pullups
This should configure my three pins as inputs - and reduce any extraneous function calls. This should even be faster than writing:
DDRF = (1 << PF2) | (1 << PF1) | (1 << PF0)
Is this the fastest implementation?
*To be honest, I'm not sure how to profile this to know for sure.
I could use _BV() in the process, but that's another function call I wish to avoid.
- it isn't a function, it's a macro. And the compiler optimizes the results. As Edgar Bonet points out, using it three times in one line and ORing the results together, gives you a single machine instruction which executes in one cycle (plus another to write to the register). You can't improve on that.DDRF = 0x07; //PF2, PF1, PF0 as input
- surely that makes them outputs?