Raspberry Pi GPIO4 (BCM 4, Physical Pin 7) is the hardware default for the 1-Wire protocol on all Raspberry Pi models. While it can function as a standard digital input/output, its primary claim to fame in the embedded world is serving as the dedicated data line for 1-Wire devices, most notably the DS18B20 digital temperature sensor. If you are building an environmental monitor, a homebrew fermentation tracker, or a server rack thermal alarm, GPIO4 is where your sensor bus begins.

This guide targets the Raspberry Pi 4 Model B (4GB variant) running Raspberry Pi OS Bookworm. We will cover the exact hardware requirements, the physics of the 1-Wire pull-up resistor, a production-ready Python script with error handling, and a debugging matrix for the exact error strings that halt most beginners.

Hardware Spec Sheet & Parts List

The 1-Wire protocol is unforgiving regarding timing and signal integrity. Unlike I2C or SPI, it relies on strict microsecond-level pulse widths. Using the wrong resistor or a breadboard with high contact resistance will result in CRC (Cyclic Redundancy Check) failures. Here is the exact bill of materials you need.

Component Specification / Variant Notes & Constraints
Microcontroller Raspberry Pi 4 Model B (4GB) Targeting Bookworm OS. Pi 5 uses the RP1 chip and requires different device tree overlays.
Sensor DS18B20 (TO-92 Package) Ensure it is a genuine Maxim/Analog Devices chip. Cheap clones often fail at extreme temperatures.
Pull-up Resistor 4.7kΩ (1/4W, 1% tolerance) Mandatory. Do not use 10kΩ; the RC rise time will violate 1-Wire timing windows.
Wiring 22 AWG solid core copper Keep data line runs under 3 meters for reliable 3.3V logic levels without a dedicated level shifter.
Power Supply Official 5.1V / 3.0A USB-C PSU Voltage sags on the 3.3V rail will corrupt 1-Wire bus readings.
Safety & Hardware Warning: Never wire the DS18B20 in "parasitic power mode" (tying VDD to GND) on a Raspberry Pi. Parasitic mode requires the master to source ~1.5mA directly from the GPIO pin during temperature conversion. The Pi's SoC GPIO pins are not rated to safely source this continuous current without risking silicon degradation. Always use external 3.3V power to the sensor's VDD pin.

Pin Mapping & Breadboard Wiring

Before writing code, verify your physical connections. The Raspberry Pi uses two numbering schemes: Broadcom (BCM) and Physical Board Pin. The w1thermsensor library and the Linux kernel overlay expect BCM numbering.

Sensor Pin (DS18B20) Pi Physical Pin Pi BCM GPIO Function
Pin 1 (GND) Pin 9 N/A Ground Reference
Pin 2 (Data) Pin 7 GPIO 4 1-Wire Data Bus (Requires 4.7kΩ pull-up to 3.3V)
Pin 3 (VDD) Pin 1 N/A 3.3V Power Input

Wiring Sequence:

  1. Place the DS18B20 on the breadboard. Identify Pin 1 by locating the flat edge of the TO-92 package; with the flat side facing you, the pins from left to right are GND, Data, VDD.
  2. Connect Pi Physical Pin 9 (GND) to the sensor's GND pin.
  3. Connect Pi Physical Pin 1 (3.3V) to the sensor's VDD pin.
  4. Connect Pi Physical Pin 7 (GPIO4) to the sensor's Data pin.
  5. Insert the 4.7kΩ resistor between the Data pin and the 3.3V rail. This acts as the open-drain pull-up.

Python Implementation with Error Handling

For Raspberry Pi OS Bookworm, the legacy RPi.GPIO library is deprecated and often fails due to the shift toward lgpio. For 1-Wire specifically, we bypass direct GPIO toggling and use the kernel's w1-gpio module via the w1thermsensor Python package. This is vastly more stable and handles the microsecond timing in C-space rather than Python-space.

First, enable the 1-Wire interface via the terminal:

sudo raspi-config nonint do_onewire 0
sudo reboot

Install the required library:

pip install w1thermsensor

Below is the complete, compilable Python script. It includes explicit hardware pin definitions, continuous polling, and graceful error handling.

#!/usr/bin/env python3
"""
Raspberry Pi GPIO4 1-Wire Temperature Poller
Target Hardware: Raspberry Pi 4 Model B (Bookworm)
Protocol: 1-Wire (Default Kernel Overlay on BCM 4)
"""

import sys
import time
from w1thermsensor import W1ThermSensor, Unit

# Explicit Hardware Pin Definitions & Configuration
# While the kernel overlay auto-routes BCM 4, we define it for documentation and validation.
HARDWARE_CONFIG = {
    "TARGET_PIN_BCM": 4,
    "TARGET_PIN_PHYSICAL": 7,
    "PROTOCOL": "1-Wire",
    "PULL_UP_RESISTOR": "4.7k Ohm",
    "POWER_MODE": "External 3.3V (Parasitic Disabled)"
}

def print_hardware_config():
    print("--- Hardware Configuration ---")
    for key, value in HARDWARE_CONFIG.items():
        print(f"{key.replace('_', ' ').title()}: {value}")
    print("------------------------------")

def main():
    print_hardware_config()
    
    try:
        # Initialize sensor. Auto-detects on the w1-gpio kernel bus (BCM 4)
        sensor = W1ThermSensor()
        print(f"[OK] Sensor found: {sensor.id} (Type: {sensor.type_name})")
        print("Starting temperature polling. Press Ctrl+C to stop.\n")
        
        while True:
            # Read temperature in Celsius and Fahrenheit
            temp_c = sensor.get_temperature(Unit.DEGREES_C)
            temp_f = sensor.get_temperature(Unit.DEGREES_F)
            
            # Basic sanity check: DS18B20 range is -55C to +125C
            if temp_c < -55.0 or temp_c > 125.0:
                print(f"[WARN] Out of range reading: {temp_c}°C. Check wiring.")
            else:
                print(f"[DATA] Temp: {temp_c:6.2f} °C | {temp_f:6.2f} °F")
                
            time.sleep(2.0) # 2-second polling interval
            
    except KeyboardInterrupt:
        print("\n[INFO] Polling interrupted by user. Exiting cleanly.")
        sys.exit(0)
        
    except Exception as e:
        # Catch and format specific w1thermsensor and OS errors
        error_type = type(e).__name__
        print(f"\n[FATAL] {error_type}: {e}")
        print("Check the debugging matrix below for resolution steps.")
        sys.exit(1)

if __name__ == "__main__":
    main()

Debugging: First Three Things to Check When It Fails

When working with GPIO4 and the 1-Wire bus, failures usually manifest as exact, repeatable Python exceptions. Here are the top three errors, ranked by frequency, and exactly how to fix them.

1. The "No Sensor Found" Sysfs Error

Exact Error String: w1thermsensor.errors.NoSensorFoundError: No sensor found on /sys/bus/w1/devices/

Root Cause: The Linux kernel module w1-gpio is loaded, but it cannot detect the sensor's 64-bit ROM serial number on the bus. This is almost always a physical layer issue.

The Fix:

  • Verify the Pull-up: Measure the resistance between Physical Pin 7 and Physical Pin 1 with the Pi powered off. You must read ~4.7kΩ. If you read infinite resistance, the resistor is unseated.
  • Check the Overlay: Run cat /boot/firmware/config.txt | grep dtoverlay=w1-gpio. If it returns nothing, the 1-Wire interface is disabled. Re-run sudo raspi-config and enable it under Interface Options.

2. The GPIO Memory Permission Error

Exact Error String: PermissionError: [Errno 13] Permission denied: '/dev/gpiomem'

Root Cause: You are attempting to use a legacy library (like RPi.GPIO) alongside the 1-Wire script, or your current user is not in the gpio group. While w1thermsensor reads from /sys/, other imported modules might try to access /dev/gpiomem directly.

The Fix: Add your user to the gpio group and reboot: sudo usermod -aG gpio $USER. Do not resort to running your script with sudo as a permanent crutch; it masks underlying permission architecture issues.

3. The CRC / Garbage Data Error

Exact Error String: w1thermsensor.errors.W1ThermSensorError: CRC validation failed (or random spikes reading exactly 85°C).

Root Cause: Signal integrity degradation. The 1-Wire protocol requires the master to read the bus within microsecond windows. If the capacitance on the line is too high, the voltage rise time slows down, and the Pi reads a '0' instead of a '1'.

The Fix: Shorten your breadboard jumper wires. If you are running a cable longer than 1 meter, you must drop the pull-up resistor to 2.2kΩ or 1kΩ to overcome the cable capacitance, or switch to a dedicated 1-Wire master IC like the DS2482-100 via I2C.

Extending and Simplifying the Build

Extending the Bus: The 1-Wire protocol is a true bus, not a point-to-point link. You can wire up to 20 DS18B20 sensors in parallel on the exact same GPIO4 pin. Each sensor has a factory-lasered 64-bit ROM. To read multiple sensors, simply modify the Python initialization to sensors = W1ThermSensor.get_available_sensors() and iterate through the list. You only need one 4.7kΩ pull-up resistor for the entire bus, provided the total trace length remains under 10 meters.

Simplifying the Build: If you are building a quick prototype and lack a 4.7kΩ resistor, you can enable the Raspberry Pi's internal pull-up resistor via device tree overlays. However, the internal pull-up is typically ~50kΩ, which is far too weak for reliable 1-Wire communication at standard speeds. To use it, you must force the 1-Wire bus into "standard speed" rather than "overdrive" and keep wires under 30cm. For any deployment outside a controlled lab bench, stick to the external 4.7kΩ physical resistor.

Pro-Tip for Multi-Sensor Buses: When wiring multiple DS18B20s on GPIO4, twist the Data and GND wires together in a twisted-pair configuration. This drastically reduces electromagnetic interference (EMI) from nearby AC mains wiring or switching power supplies, which is the #1 cause of phantom CRC errors in home automation racks.

Frequently Asked Questions

Can I use Raspberry Pi GPIO4 for standard PWM output instead of 1-Wire?

Yes, but with a major caveat. GPIO4 (BCM 4) is not one of the Pi's hardware PWM pins (which are typically BCM 12, 13, 18, and 19). If you use GPIO4 for PWM, the Pi must generate the signal via software PWM, which is prone to jitter and CPU-load interruptions. Furthermore, if you have the dtoverlay=w1-gpio line in your config.txt, the kernel reserves BCM 4 exclusively for the 1-Wire master driver. You must remove that overlay and reboot before BCM 4 can be used as a standard GPIO or software PWM pin.

Why does my DS18B20 read exactly 85°C or -127°C on GPIO4?

These are not random errors; they are hardcoded factory defaults. A reading of exactly 85°C means the sensor powered up but has not yet completed a temperature conversion (the conversion takes up to 750ms at 12-bit resolution). Your polling script is reading the scratchpad before the conversion finishes. A reading of -127°C (or sometimes 127°C) indicates a hard communication failure between the master and the sensor's internal ADC, usually caused by a missing pull-up resistor or a broken data wire.

Is physical pin 7 the same as BCM 4 on the Raspberry Pi 5?

Physically, yes. The 40-pin header layout remains identical on the Raspberry Pi 5. However, architecturally, no. The Pi 5 routes all GPIO through the external RP1 southbridge chip rather than the main BCM2712 SoC. This means legacy 1-Wire kernel overlays designed for the Pi 4 will not map correctly without updates. If you are targeting the Pi 5, ensure you are using the latest Bookworm kernel, which includes the updated RP1 device tree bindings for w1-gpio, and rely on gpiozero with the rpi-lgpio backend rather than older direct-memory-access libraries.