Q:

# Define Macro to toggle a bit of a PIN in C

Given PIN (value) and a bit to be toggled, we have to toggle it using Macro in C language.

To toggle a bit, we use XOR (^) operator.

Macro definition:

```    #define TOGGLE(PIN,N) (PIN ^=  (1<<N))
```

Here,

• TOGGLE is the Macro name
• PIN is the value whose bit to be toggled
• N is the bit number

Example:

``````#include <stdio.h>

#define TOGGLE(PIN,N) (PIN ^=  (1<<N))

int main(){

unsigned char val = 0x11;
unsigned char bit = 2;

printf("val = %X\n",val);

//TOGGLE bit number 2
TOGGLE(val, bit);
printf("Aftre toggle bit %d first  time, val = %X\n", bit, val);

//TOGGLE bit number 2 again
TOGGLE(val, bit);
printf("Aftre toggle bit %d second time, val = %X\n", bit, val);

return 0;
}``````

Output

```    val = 11
Aftre toggle bit 2 first  time, val = 15
Aftre toggle bit 2 second time, val = 11
```

Explanation:

• Initially val is 0x11, its binary value is "0001 0001".
• In this example, we are toggling bit number 2 (i.e. third bit of the val), initially bit 2 is 0, after calling TOGGLE(val, bit) first time, the bit 2 will be 1. Hence, the value of val will be "0001 0100" – thus, the output will be 0x15 in Hexadecimal.
• Now, the bit 2 is 1, after calling TOGGLE(val, bit) again, bit 2 will be 0 again, hence the value of val will be "0001 0001" – thus, the output will be 0x11 in Hexadecimal.