0
0
Iot-protocolsHow-ToBeginner · 3 min read

How to Set GPIO Pin as Output on Raspberry Pi

To set a GPIO pin as output on Raspberry Pi, use the RPi.GPIO library in Python. First, import the library, set the pin numbering mode with GPIO.setmode(), then configure the pin as output using GPIO.setup(pin_number, GPIO.OUT).
📐

Syntax

Here is the basic syntax to set a GPIO pin as output using the RPi.GPIO library:

  • GPIO.setmode(GPIO.BCM) - Sets the pin numbering system to BCM (Broadcom SOC channel numbers).
  • GPIO.setup(pin_number, GPIO.OUT) - Configures the specified pin as an output pin.
python
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)  # Use BCM pin numbering
GPIO.setup(18, GPIO.OUT)  # Set GPIO pin 18 as output
💻

Example

This example sets GPIO pin 18 as output and turns an LED on and off with a 1-second delay.

python
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)  # Use BCM pin numbering
GPIO.setup(18, GPIO.OUT)  # Set GPIO pin 18 as output

try:
    while True:
        GPIO.output(18, GPIO.HIGH)  # Turn LED on
        print("LED ON")
        time.sleep(1)  # Wait 1 second
        GPIO.output(18, GPIO.LOW)  # Turn LED off
        print("LED OFF")
        time.sleep(1)  # Wait 1 second
except KeyboardInterrupt:
    pass
finally:
    GPIO.cleanup()  # Reset GPIO settings
Output
LED ON LED OFF LED ON LED OFF ... (repeats every second until stopped)
⚠️

Common Pitfalls

Common mistakes when setting GPIO pins as output include:

  • Not calling GPIO.setmode() before GPIO.setup(), which causes errors.
  • Using the wrong pin numbering system (BCM vs BOARD) and mixing them up.
  • Forgetting to call GPIO.cleanup() to reset pins after the program ends, which can cause warnings on next run.
  • Trying to set a pin as output without proper permissions (run script with sudo).
python
import RPi.GPIO as GPIO

# Wrong: Missing setmode call
# GPIO.setup(18, GPIO.OUT)  # This will raise a warning or error

# Right way:
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
📊

Quick Reference

Summary tips for setting GPIO pins as output on Raspberry Pi:

  • Always call GPIO.setmode() before GPIO.setup().
  • Use GPIO.BCM or GPIO.BOARD consistently for pin numbering.
  • Use GPIO.setup(pin, GPIO.OUT) to set a pin as output.
  • Control pin output with GPIO.output(pin, GPIO.HIGH) or GPIO.output(pin, GPIO.LOW).
  • Call GPIO.cleanup() at the end to reset pins.

Key Takeaways

Always set the pin numbering mode with GPIO.setmode() before configuring pins.
Use GPIO.setup(pin_number, GPIO.OUT) to set a GPIO pin as output.
Control the output state with GPIO.output(pin_number, GPIO.HIGH) or GPIO.LOW.
Run your script with sudo to access GPIO pins on Raspberry Pi.
Call GPIO.cleanup() at the end to avoid warnings and reset pins.