GPIO programming lets you control physical parts like lights and sensors with your Raspberry Pi. It is the base for making your Pi interact with the real world.
0
0
Why GPIO programming is foundational in Raspberry Pi
Introduction
Turning on an LED light when a button is pressed.
Reading temperature from a sensor to display on a screen.
Controlling a motor to move a small robot.
Making a simple alarm that sounds when motion is detected.
Building a home automation system to switch devices on or off.
Syntax
Raspberry Pi
import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(pin_number, GPIO.OUT) GPIO.output(pin_number, GPIO.HIGH) # or GPIO.LOW GPIO.cleanup()
Use GPIO.setmode(GPIO.BCM) to refer to pins by their Broadcom number.
Always call GPIO.cleanup() at the end to reset pins safely.
Examples
Turns on an LED connected to pin 18.
Raspberry Pi
import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.OUT) GPIO.output(18, GPIO.HIGH) GPIO.cleanup()
Reads the state of a button connected to pin 23 and prints it.
Raspberry Pi
import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(23, GPIO.IN) button_state = GPIO.input(23) print(button_state) GPIO.cleanup()
Sample Program
This program blinks an LED connected to pin 17 five times. It turns the LED on and off every second and prints the state.
Raspberry Pi
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) LED_PIN = 17 GPIO.setup(LED_PIN, GPIO.OUT) for i in range(5): GPIO.output(LED_PIN, GPIO.HIGH) # Turn LED on print('LED ON') time.sleep(1) GPIO.output(LED_PIN, GPIO.LOW) # Turn LED off print('LED OFF') time.sleep(1) GPIO.cleanup()
OutputSuccess
Important Notes
GPIO pins can be damaged if connected incorrectly. Always check your wiring.
Use resistors with LEDs to avoid burning them out.
Running GPIO code usually requires root permission (use sudo).
Summary
GPIO programming connects your Raspberry Pi to the physical world.
It is used to control or read devices like LEDs, buttons, and sensors.
Learning GPIO basics is the first step to building fun and useful projects.