Embedded Systems & Firmware
To toggle an LED output pin bit between on and off each time the code runs, which C statement is correct?
- Aport |= (1 << 5);
- Bport ^= (1 << 5);
- Cport &= ~(1 << 5);
Show answer and explanation
Answer: B. port ^= (1 << 5);
With exclusive OR (XOR, ^), a bit XORed with 1 flips and with 0 stays the same. So each execution of "port ^= (1 << 5)" toggles only bit 5 between 0 and 1. It is commonly used to blink LEDs. Some microcontrollers have dedicated registers that toggle bits simply by writing to them.
- A. This always sets the bit; it does not toggle.
- B. Correct. XOR flips the selected bit.
- C. This always clears the bit; it does not toggle.