Embedded Systems & Firmware

To toggle an LED output pin bit between on and off each time the code runs, which C statement is correct?

  1. Aport |= (1 << 5);
  2. Bport ^= (1 << 5);
  3. 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.
Practice this topic Back to topic

More Embedded Systems & Firmware questions

  1. Which C condition correctly tests whether bit 5 of input register in is 1?
  2. The code above rewrites a multi-bit field of register reg. What does it do?
  3. While the main code updates a register bit with "reg |= mask;" (read-modify-write), an interrupt handler changes a different bit of the same register. Which pairs the possible problem with a fix correctly?
  4. A switch alone is connected to a microcontroller input pin, with no pull-up or pull-down resistor. What can happen while the switch is open?
  5. When using a microcontroller GPIO (general-purpose input/output) pin, what must be configured first?