0
0
Power-electronicsHow-ToBeginner · 3 min read

How to Toggle GPIO Pin in Embedded C: Simple Guide

To toggle a GPIO pin in Embedded C, use the ^= operator on the pin's output register bit, like GPIO_PORT ^= (1 << PIN_NUMBER);. This flips the pin state from high to low or low to high each time it runs.
📐

Syntax

To toggle a GPIO pin, you typically use the XOR operator ^= on the output register bit corresponding to the pin. This flips the pin's current state.

  • GPIO_PORT: The register controlling the output state of the GPIO pins.
  • PIN_NUMBER: The bit position of the pin you want to toggle.
  • (1 << PIN_NUMBER): Creates a mask to select the specific pin bit.
  • ^=: XOR assignment operator that toggles the bit.
c
GPIO_PORT ^= (1 << PIN_NUMBER);
💻

Example

This example toggles GPIO pin 5 on port B every 500 milliseconds. It assumes the pin is already configured as output.

c
#include <stdint.h>
#include <stdbool.h>
#include <stdio.h>
#include <unistd.h> // For usleep, replace with your platform delay

// Simulated GPIO port register
volatile uint8_t GPIO_PORTB = 0x00;

#define PIN5 5

void toggle_pin(void) {
    GPIO_PORTB ^= (1 << PIN5); // Toggle pin 5
}

int main(void) {
    printf("Initial GPIO_PORTB state: 0x%02X\n", GPIO_PORTB);
    for (int i = 0; i < 5; i++) {
        toggle_pin();
        printf("GPIO_PORTB state after toggle %d: 0x%02X\n", i + 1, GPIO_PORTB);
        usleep(500000); // 500 ms delay
    }
    return 0;
}
Output
Initial GPIO_PORTB state: 0x00 GPIO_PORTB state after toggle 1: 0x20 GPIO_PORTB state after toggle 2: 0x00 GPIO_PORTB state after toggle 3: 0x20 GPIO_PORTB state after toggle 4: 0x00 GPIO_PORTB state after toggle 5: 0x20
⚠️

Common Pitfalls

Common mistakes when toggling GPIO pins include:

  • Not configuring the pin as output before toggling.
  • Using assignment = instead of XOR ^=, which sets the pin instead of toggling.
  • Forgetting to use the correct bit mask for the pin.
  • Accessing the wrong GPIO port register.
c
/* Wrong way: This sets pin 5 high every time, no toggle */
GPIO_PORTB = (1 << PIN5);

/* Right way: Toggles pin 5 state */
GPIO_PORTB ^= (1 << PIN5);
📊

Quick Reference

Remember these tips for toggling GPIO pins:

  • Use ^= with the pin mask to toggle.
  • Ensure pin is set as output before toggling.
  • Use correct port and pin number.
  • Delay between toggles to observe changes.

Key Takeaways

Use XOR assignment (^=) with the pin mask to toggle GPIO pin state.
Always configure the GPIO pin as output before toggling.
Use the correct port register and bit mask for the pin.
Avoid using simple assignment (=) which sets the pin instead of toggling.
Add delays between toggles to see the pin state change clearly.