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.
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.
5. You want to build a project that turns on an LED when a button is pressed using Raspberry Pi GPIO. Which two GPIO programming concepts are foundational to achieve this?
hard
A. Setting a GPIO pin as input to read the button state and setting another pin as output to control the LED.
B. Using GPIO pins only as outputs for both button and LED.
C. Configuring both pins as inputs to detect button press and LED status.
D. Using software timers without configuring GPIO pins.
Solution
Step 1: Identify pin roles for button and LED
The button must be connected to a pin set as input to detect presses; the LED must be connected to a pin set as output to turn on/off.
Step 2: Understand GPIO pin configuration
Setting pins correctly as input or output is foundational to read signals and control devices.
Final Answer:
Setting a GPIO pin as input to read the button state and setting another pin as output to control the LED. -> Option A
Quick Check:
Input pin reads button, output pin controls LED [OK]
Hint: Input pin reads button; output pin controls LED [OK]
Common Mistakes:
Configuring button pin as output
Configuring LED pin as input
Ignoring pin mode setup
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.