The RPi.GPIO library helps you control the pins on a Raspberry Pi to connect with lights, buttons, and sensors.
0
0
RPi.GPIO library setup in Raspberry Pi
Introduction
When you want to turn an LED on or off using your Raspberry Pi.
When you need to read input from a button or switch connected to the Pi.
When you want to control motors or other devices with the Pi's pins.
When you are building a simple home automation project using Raspberry Pi.
When you want to learn how to interact with hardware using Python on Raspberry Pi.
Syntax
Raspberry Pi
import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) # or GPIO.BOARD GPIO.setup(pin_number, GPIO.OUT) # or GPIO.IN
GPIO.setmode() chooses how you number the pins: BCM uses the chip's pin numbers, BOARD uses the physical pin numbers.
GPIO.setup() prepares a pin to be an input or output.
Examples
Set pin 18 as an output using BCM numbering.
Raspberry Pi
import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.OUT)
Set physical pin 12 as an input using BOARD numbering.
Raspberry Pi
import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD) GPIO.setup(12, GPIO.IN)
Sample Program
This program turns an LED connected to pin 18 on for 2 seconds, then turns it off. It cleans up the pin settings at the end.
Raspberry Pi
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) # Use BCM pin numbering GPIO.setup(18, GPIO.OUT) # Set pin 18 as output try: GPIO.output(18, GPIO.HIGH) # Turn LED on print("LED is ON") time.sleep(2) # Wait 2 seconds GPIO.output(18, GPIO.LOW) # Turn LED off print("LED is OFF") finally: GPIO.cleanup() # Reset pins
OutputSuccess
Important Notes
Always call GPIO.cleanup() at the end to reset pins and avoid warnings next time you run your program.
Use GPIO.setmode() once at the start to choose your pin numbering style.
Make sure your Raspberry Pi has the RPi.GPIO library installed (usually pre-installed on Raspberry Pi OS).
Summary
RPi.GPIO lets you control Raspberry Pi pins with Python.
Use GPIO.setmode() to pick pin numbering style.
Use GPIO.setup() to prepare pins as input or output.