0
0
Raspberry Piprogramming~5 mins

Setting pin mode (IN, OUT) in Raspberry Pi

Choose your learning style9 modes available
Introduction

We set a pin mode to tell the Raspberry Pi if the pin will read signals (input) or send signals (output).

When you want to read a button press from a sensor.
When you want to turn on an LED or motor.
When you connect a switch to detect if it is pressed or not.
When you want to control a device like a buzzer or relay.
When you need to read data from a sensor like a temperature sensor.
Syntax
Raspberry Pi
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)  # Use Broadcom pin numbering
GPIO.setup(pin_number, GPIO.IN)  # Set pin as input
GPIO.setup(pin_number, GPIO.OUT)  # Set pin as output

Use GPIO.setmode(GPIO.BCM) to use the pin numbers as labeled on the Raspberry Pi board.

Use GPIO.setup() to set the pin mode before using the pin.

Examples
Set pin 17 as an input to read signals like button presses.
Raspberry Pi
GPIO.setup(17, GPIO.IN)
Set pin 18 as an output to control devices like LEDs.
Raspberry Pi
GPIO.setup(18, GPIO.OUT)
Set pin 22 as input with a pull-up resistor to avoid floating values.
Raspberry Pi
GPIO.setup(22, GPIO.IN, pull_up_down=GPIO.PUD_UP)
Sample Program

This program sets pin 18 as output and turns an LED on and off every second. It prints the LED status to the screen.

Raspberry Pi
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)

pin = 18
GPIO.setup(pin, GPIO.OUT)

try:
    while True:
        GPIO.output(pin, GPIO.HIGH)  # Turn LED on
        print("LED ON")
        time.sleep(1)
        GPIO.output(pin, GPIO.LOW)   # Turn LED off
        print("LED OFF")
        time.sleep(1)
except KeyboardInterrupt:
    GPIO.cleanup()  # Reset GPIO settings
    print("Program stopped")
OutputSuccess
Important Notes

Always call GPIO.cleanup() at the end to reset pins and avoid warnings next time.

Use GPIO.IN for reading signals and GPIO.OUT for sending signals.

Pull-up or pull-down resistors help keep input pins stable and avoid random readings.

Summary

Set pin mode to tell Raspberry Pi if pin is input or output.

Use GPIO.setup(pin, GPIO.IN) for input pins.

Use GPIO.setup(pin, GPIO.OUT) for output pins.