0
0
Power-electronicsHow-ToBeginner · 3 min read

How to Set GPIO Pin High in Embedded C: Simple Guide

To set a GPIO pin high in embedded C, you write a 1 to the specific bit of the port's output register controlling that pin using code like PORTx |= (1 << PINx);. This sets the voltage of the pin to high (usually 3.3V or 5V) so connected devices can detect it.
📐

Syntax

The basic syntax to set a GPIO pin high is:

  • PORTx: The output register for the port (e.g., PORTB, PORTC).
  • PINx: The pin number within the port (0 to 7 usually).
  • |= (1 << PINx): Bitwise OR operation to set the pin bit to 1 without changing other bits.
c
PORTx |= (1 << PINx);
💻

Example

This example shows how to set pin 3 of PORTB high on a microcontroller. It assumes the pin is already configured as an output.

c
#include <avr/io.h>

int main(void) {
    DDRB |= (1 << 3);  // Set pin 3 of PORTB as output
    PORTB |= (1 << 3); // Set pin 3 of PORTB high
    while(1) {
        // Loop forever
    }
    return 0;
}
⚠️

Common Pitfalls

Common mistakes when setting GPIO pins high include:

  • Not configuring the pin as an output before setting it high, which means the pin won't drive the voltage.
  • Using = instead of |=, which can accidentally clear other pins on the port.
  • Confusing port registers like PORTx (output register) with PINx (input register).
c
// Wrong: This clears all other pins on PORTB
PORTB = (1 << 3);

// Right: This only sets pin 3 high, keeping others unchanged
PORTB |= (1 << 3);
📊

Quick Reference

Remember these quick tips when working with GPIO pins:

  • Always set the pin as output using the Data Direction Register (e.g., DDRx).
  • Use bitwise OR |= to set pins high without affecting others.
  • Use bitwise AND with NOT &= ~ to set pins low.
  • Check your microcontroller datasheet for exact register names.

Key Takeaways

Set the pin as output before setting it high using the data direction register.
Use bitwise OR (|=) with a shifted 1 to set a specific GPIO pin high safely.
Avoid using = alone to prevent clearing other pins on the port.
Know your microcontroller's port and pin register names from its datasheet.
Setting a GPIO pin high means applying voltage to that pin for connected devices.