I am using AVR controller atmega328. I need to check the status of two bits. I have two approaches, but not sure which one is most efficient. In first case in the code below, I am reading the port using PIND command twice (Two times PIND access is made). So is this an issue or I have to go with second if statement?
#define SW1 2
#define SW2 5
//check if both are high
if((PIND&(1<<SW1))&&(PIND&(1<<SW2)))
//Or
if((PIND&((1<<SW1)|(1<<SW2)))==((1<<SW1)|(1<<SW2)))
I suppose PIND
is a peripheral register (what do you mean by "command"?).
The first check will read it once or twice, depending on the first comparison. This might generate a glitch, if SW1 changes between the first and second read.
Presuming SW? are switches: In general, it is better to read such a register once (possibly to a variable) and test for the bits. That ensures you get a snapshot of all input bits at the same time.
Also, the seconde version is not necessarily slower, as it safes a branch (IIRC AVR has no conditional instructions other than branch/jump).