#define IRpin_PIN PIND
#define IRpin 2
if(IRpin_PIN & _BV(IRpin))//when do we enter the loop?
{
//do something;
}
_BV is a macro which returns the "value" of a bit.
It is:
#define _BV(bit) (1 << (bit))
So, _BV(2) expands to (1<<(2)), which is 0b00000001 shifted left twice: 0b00000100.
In this case it is then being used as a mask to select a specific bit within the IRpin_PIN macro, which equates to PIND - so it checks the status of pin D2.
Thank you! can u slightly expand your explanation because I'm new to arduino.
I didn't understand this statement : 'used as a mask to select a specific bit within the IRpin_PIN macro'.
The & operator performs a bitwise "and" operation between two variables. It is mostly used for what is known as "masking" a variable - applying one variable on-top of another to ignore certain bits within that variable so you only look at the interesting bits.
In the code you have provided, the mask is created by the _BV macro.
#define IRpin_PIN PIND
From now on all references to "IRpin_PIN" will be replaced with "PIND".
#define IRpin 2
From now on all references to "IRpin" will be replaced with "2".
if(IRpin_PIN & _BV(IRpin))//when do we enter the loop?
_BV(IRpin) is expanded to _BV(2). It is then further expanded to (1<<(2)).
So _BV(IRpin) equates to the binary value 0b00000100.
That is then "AND"ed with IRpin_PIN, which is the PIND register. This is the status of the pins in port D as inputs. This could contain anything, but for arguements sake let's take it as 0b01100100 (3 inputs high, 5 inputs low).
The AND operation returns only the bits in the two variables where they are both 1:
PIND : 0b01100100
1<<2 : 0b00000100
AND : 0b00000100
and if PIND is 0b01000000:
PIND : 0b01100000
1<<2 : 0b00000100
AND : 0b00000000
So the IF statement only sees either 0 or 4 (the decimal representations of 0b00000000 and 0b00000100) - 0 being "false" and 4 being "true".
So when do you enter the loop? Only if the condition = 0b00000001 ? in your example the if statement only sees 0 or 4, so we never execute the code in the If statement?