The Raspberry Pi 4 Pin Layout: Quick Decision Guide
The Raspberry Pi 4 pin layout features a 40-pin header containing 26 usable general-purpose I/O (GPIO) pins, 2 dedicated I2C channels, 2 SPI channels, 1 UART port, and 2 hardware PWM pins. If you are wiring a new peripheral and need to know exactly which physical pin to use, use this decision tree to lock in your selection immediately.
| Protocol / Function Needed | Condition / Constraint | Concrete Pick (Physical Pin / BCM) |
|---|---|---|
| Hardware PWM (Motor/Fan speed) | Need true hardware timing, no CPU jitter | Physical 12 / BCM 18 (PWM0) |
| I2C Sensor (Temp/Display) | Standard 100kHz/400kHz bus, needs pull-ups | Physical 3 & 5 / BCM 2 & 3 (SDA1/SCL1) |
| SPI High-Speed (ADC/RFID) | Need >1MHz clock, full duplex | Physical 19, 21, 23 / BCM 10, 9, 11 (MOSI, MISO, SCLK) |
| Standard Digital Input | Button or limit switch, internal pull-up OK | Physical 16 / BCM 23 (Safe, no boot conflicts) |
| UART Serial Console | Debugging headless, GPS module | Physical 8 & 10 / BCM 14 & 15 (TXD/RXD) |
Hardware Spec Sheet & Parts List
The code and wiring diagrams in this guide target a specific board variant to ensure pin behavior matches the silicon. We are using the Raspberry Pi 4 Model B (8GB RAM, Rev 1.5). Earlier Rev 1.1/1.2 boards had minor USB-C power delivery issues but identical GPIO layouts. The GPIO header is driven by the BCM2711 SoC, which operates strictly at 3.3V logic. Feeding 5V into any GPIO pin will permanently destroy the SoC.
Project Parts List: PWM-Controlled Active Cooling
To demonstrate the pin layout in action, we are building a hardware-PWM cooling fan controller that reads the SoC temperature and scales fan speed. Total cost is roughly $95 if you already own the Pi.
- Microcontroller: Raspberry Pi 4 Model B (8GB) - ~$75
- Fan: Noctua NF-A4x10 5V PWM (40x40x10mm) - ~$15 (Must be 5V, not 12V)
- Switching Transistor: 2N2222 NPN (TO-92 package) - ~$0.10
- Base Resistor: 1kΩ (1/4W) to limit GPIO current to ~2.6mA
- Flyback Diode: 1N4001 across fan terminals to kill inductive kickback
- Wiring: 22 AWG solid core jumper wires, half-size breadboard
The 40-Pin GPIO Mapping Table
When looking at the Pi with the USB ports facing you and the GPIO header on the top right, Pin 1 is the top-left pin (3.3V), and Pin 2 is the top-right pin (5V). Below is the functional mapping. For authoritative reference, always cross-check with the official Pinout.xyz interactive diagram and the Raspberry Pi Foundation hardware documentation.
| Physical Pin | BCM GPIO | Function / Name | Notes & Warnings |
|---|---|---|---|
| 1 | - | 3.3V Power | Max draw ~50mA total across all 3.3V pins |
| 2 | - | 5V Power | Tied directly to USB-C input. Can backpower Pi. |
| 3 | 2 | SDA1 (I2C) | Has physical 1.8kΩ pull-up to 3.3V on board. |
| 4 | - | 5V Power | Same as Pin 2. |
| 5 | 3 | SCL1 (I2C) | Has physical 1.8kΩ pull-up to 3.3V on board. |
| 6 | - | Ground | Primary ground reference. |
| 7 | 4 | GPIO 4 (GPCLK0) | Default 1-Wire bus pin in raspi-config. |
| 8 | 14 | TXD (UART) | Serial console output. 3.3V logic. |
| 9 | - | Ground | |
| 10 | 15 | RXD (UART) | Serial console input. Do not feed 5V RS232 here! |
| 11 | 17 | GPIO 17 | Safe for general use. |
| 12 | 18 | GPIO 18 (PWM0) | Hardware PWM. Ideal for audio and fan control. |
| 14 | - | Ground | |
| 15 | 22 | GPIO 22 | Safe for general use. |
| 16 | 23 | GPIO 23 | Safe for general use. |
| 18 | 24 | GPIO 24 | Safe for general use. |
| 19 | 10 | MOSI (SPI0) | SPI Master Out Slave In. |
| 21 | 9 | MISO (SPI0) | SPI Master In Slave Out. |
| 23 | 11 | SCLK (SPI0) | SPI Clock. |
| 25 | - | Ground | |
| 27 | 0 | SDA0 (I2C ID) | Reserved for HAT EEPROM ID. Do not use. |
| 29 | 5 | GPIO 5 | Safe for general use. |
| 31 | 6 | GPIO 6 | Safe for general use. |
| 32 | 12 | GPIO 12 (PWM0) | Hardware PWM. Alt function to Pin 18. |
| 33 | 13 | GPIO 13 (PWM1) | Hardware PWM channel 1. |
| 34 | - | Ground | |
| 35 | 19 | MISO (SPI1) | Auxiliary SPI. |
| 36 | 16 | GPIO 16 | Safe for general use. |
| 37 | 26 | GPIO 26 | Safe for general use. |
| 38 | 20 | MOSI (SPI1) | Auxiliary SPI. |
| 40 | 21 | SCLK (SPI1) | Auxiliary SPI. |
Build & Code: PWM Fan Controller with Error Handling
This Python script uses the RPi.GPIO library to read the internal SoC temperature via the vcgencmd utility and outputs a hardware PWM signal to Physical Pin 12 (BCM 18). The 1kΩ resistor connects BCM 18 to the base of the 2N2222. The fan's ground wire connects to the collector, and the emitter connects to Pi Ground. The fan's 5V wire connects to Physical Pin 2 or 4.
- Wire the circuit: Connect BCM 18 to the 1kΩ resistor, then to the 2N2222 Base. Connect 2N2222 Emitter to Pi GND. Connect Fan Black (GND) to Collector. Connect Fan Red (5V) to Pi 5V. Place the 1N4001 diode across the fan wires (stripe facing Red/5V).
- Enable GPIO library: Run
sudo apt update && sudo apt install python3-rpi.gpioin the terminal. - Deploy the script: Save the code below as
fan_control.pyand execute withsudo python3 fan_control.py.
import RPi.GPIO as GPIO
import time
import os
import sys
# --- PIN DEFINITIONS (BCM Numbering) ---
FAN_PIN = 18 # Physical Pin 12, Hardware PWM0
FAN_FREQ = 25000 # 25kHz frequency (inaudible for PC fans)
TEMP_THRESHOLD = 55 # Start ramping fan at 55C
TEMP_MAX = 75 # 100% duty cycle at 75C
def get_cpu_temp():
"""Reads the SoC temperature using the built-in vcgencmd tool."""
try:
res = os.popen('vcgencmd measure_temp').readline()
return float(res.replace('temp=', '').replace("'C\n", ''))
except Exception:
return 50.0 # Fallback safe temp if read fails
def main():
# Explicitly set BCM mode to avoid physical pin numbering confusion
GPIO.setmode(GPIO.BCM)
try:
# Setup pin with error handling for invalid channel access
GPIO.setup(FAN_PIN, GPIO.OUT)
pwm = GPIO.PWM(FAN_PIN, FAN_FREQ)
pwm.start(0) # Start at 0% duty cycle
print(f'Fan control active on BCM {FAN_PIN}. Press Ctrl+C to stop.')
while True:
temp = get_cpu_temp()
if temp < TEMP_THRESHOLD:
duty = 0
elif temp >= TEMP_MAX:
duty = 100
else:
# Linear interpolation between threshold and max
duty = ((temp - TEMP_THRESHOLD) / (TEMP_MAX - TEMP_THRESHOLD)) * 100
pwm.ChangeDutyCycle(duty)
print(f'Temp: {temp:.1f}C | Fan Duty: {duty:.0f}%')
time.sleep(5)
except RuntimeError as e:
print(f'GPIO Runtime Error: {e}')
sys.exit(1)
except KeyboardInterrupt:
print('\nShutting down gracefully...')
finally:
# CRITICAL: Always clean up to release hardware locks
try:
pwm.stop()
except NameError:
pass
GPIO.cleanup()
if __name__ == '__main__':
main()
Debugging: Fatal Errors and the First Three Checks
When working with the Raspberry Pi 4 pin layout, RPi.GPIO will aggressively halt your script if it detects hardware misuse. Here are the exact error strings you will encounter, ranked by frequency, and how to fix them.
Error 1: 'RuntimeError: The channel sent is invalid on a Raspberry Pi'
Ranked Causes:
- Numbering Mode Mismatch (90% of cases): You set
GPIO.setmode(GPIO.BOARD)but passed a BCM number (like 18), or vice versa. BCM 18 is Physical 12. If you are in BOARD mode and pass 18, the library looks for Physical Pin 18 (which is BCM 24). If you pass a number that doesn't exist on the physical header (like 42), it throws this error. - Targeting a Power/Ground Pin: You attempted to run
GPIO.setup(2, GPIO.OUT). Pin 2 is 5V Power. The library blocks you from redefining power rails as logic pins. - Using Reserved Pins: Attempting to use BCM 0 or BCM 1 (Physical 27/28), which are reserved for the HAT ID EEPROM I2C bus.
Error 2: 'RuntimeError: No access to /dev/mem. Try running as root!'
Ranked Causes:
- Missing Sudo: You ran
python3 script.pyinstead ofsudo python3 script.py. Direct memory access to the BCM2711 peripheral registers requires root privileges. - User Group Permissions: If running without sudo, your current user is not in the
gpioanddialoutgroups. Fix viasudo usermod -aG gpio,dialout $USERand reboot.
Error 3: 'RuntimeError: This channel is already in use, continuing anyway.'
Cause: A previous execution of your script crashed or was killed via kill -9 before reaching GPIO.cleanup(). The hardware register remains locked.
Fix: Add GPIO.setwarnings(False) at the top of your script during development, or ensure your finally: block always executes GPIO.cleanup().
- Verify Numbering: Print
GPIO.getmode()at the start of your script to confirm if you are in BCM (11) or BOARD (10) mode. - Multimeter Continuity: With the Pi powered off, use a multimeter to check continuity between your jumper wire and the physical pin on the header. Breadboard contacts frequently wear out and lose grip on 22 AWG wire.
- Check for 5V Backfeed: Measure the voltage between your sensor's data line and Pi Ground. If it reads >3.4V, your sensor is pushing 5V logic into a 3.3V pin. Use a logic level converter immediately before powering the Pi back on.
Extending and Simplifying the Build
Once you have the basic fan controller running, you will likely want to iterate on the hardware. Here is how to scale the project up or strip it down based on your deployment environment.
How to Simplify (The HAT Route)
If you are building a media center or retro-gaming console and want to eliminate breadboards and transistor wiring entirely, abandon the custom circuit and buy a pre-made cooling HAT. The Argon ONE M.2 Case (~$45) integrates a magnetic pogo-pin connection to the Pi 4 pin layout's 5V, GND, and BCM 18 pins, routing the fan control through an onboard microcontroller. You simply flash their provided argon1.py daemon. This removes the risk of blowing the Pi's SoC with a misplaced jumper wire.
How to Extend (Adding I2C Telemetry)
To add a visual display without consuming extra GPIO pins, wire a 0.96-inch SSD1306 I2C OLED to the dedicated I2C pins.
- Connect OLED VCC to Physical Pin 1 (3.3V).
- Connect OLED GND to Physical Pin 6 (Ground).
- Connect OLED SDA to Physical Pin 3 (BCM 2).
- Connect OLED SCL to Physical Pin 5 (BCM 3).
Adafruit_SSD1306 Python library, initialize the bus at address 0x3C, and push the temp and duty variables to the screen inside the main while loop. This leverages the dedicated hardware I2C controller, freeing the CPU to handle network tasks or Docker containers without display-tearing latency.
For deeper technical specifications on the BCM2711 peripheral addresses and register maps, refer to the BCM2711 ARM Peripherals Manual. Always respect the 3.3V logic boundary, verify your pin mapping mode before applying power, and your Pi 4 will run reliably for years.






