In this tutorial, we’ll discuss Raspberry Pi I2C on the Raspberry Pi 5: how to enable I2C, the I2C pins and buses, how to run an I2C scan, and how to read and write the registers of an I2C device in Python and C++. You’ll learn how to enable I2C three ways (raspi-config, the command line, and config.txt), scan the bus with i2cdetect and with your own scanner in Python (smbus2) and C++ (Linux i2c-dev), and change the I2C bus speed.
We’ll answer the question: what’s different about I2C on the Raspberry Pi 5 compared to the Raspberry Pi 4 and older boards? You’ll see the Pi 5’s I2C bus map read from my board, my oscilloscope captures of decoded I2C transactions at 100kHz, 400kHz, and 1MHz speeds, with the measured SCL frequency and rise time, the time each scanner takes, and the error messages you’ll meet along the way. Without further ado, let’s get right into it!
Note: All examples in this tutorial are tested with: Raspberry Pi 5 (8GB) with Raspberry Pi OS (64-bit) Trixie, and a BMP280 (BME280-style) I2C module.
This tutorial assumes your Raspberry Pi is set up with Raspberry Pi OS and reachable over SSH. If it isn’t, follow the Raspberry Pi Setup Guide first. Every command below runs in an SSH session; my Raspberry Pi SSH tutorial shows how to connect from Windows, macOS, and Linux.
Raspberry Pi I2C (Raspberry Pi 5)
To use I2C on a Raspberry Pi, enable it with sudo raspi-config nonint do_i2c 0 (or the dtparam=i2c_arm=on line in /boot/firmware/config.txt), connect your device’s SDA to GPIO2 (pin 3) and SCL to GPIO3 (pin 5), power it from 3.3v (pin 1), and scan the bus with i2cdetect -y 1. The device’s address appears in the table. Then read a register:
Python Code example (Raspberry Pi I2C read with smbus2)
|
1 2 3 4 5 |
from smbus2 import SMBus with SMBus(1) as bus: # /dev/i2c-1 = GPIO2 (SDA), GPIO3 (SCL) chip_id = bus.read_byte_data(0x76, 0xD0) # device 0x76, register 0xD0 (chip ID) print(f"Chip ID: 0x{chip_id:02X}") |
C++ Code example (Raspberry Pi I2C read with Linux i2c-dev)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <cstdint> #include <cstdio> #include <fcntl.h> #include <unistd.h> #include <sys/ioctl.h> #include <linux/i2c-dev.h> int main() { int fd = open("/dev/i2c-1", O_RDWR); // GPIO2 (SDA), GPIO3 (SCL) if (fd < 0 || ioctl(fd, I2C_SLAVE, 0x76) < 0) { perror("i2c"); return 1; } uint8_t reg = 0xD0, chip_id = 0; // register 0xD0 (chip ID) if (write(fd, ®, 1) != 1 || read(fd, &chip_id, 1) != 1) { perror("i2c"); return 1; } std::printf("Chip ID: 0x%02X\n", chip_id); close(fd); } |
Both read register 0xD0 (the chip ID) of the BMP280 sensor at address 0x76 and print Chip ID: 0x58 on my Raspberry Pi 5. Build the C++ one with g++ -std=c++17 quick_i2c.cpp -o quick_i2c. Neither needs sudo, because the default user is in the i2c group. The rest of this tutorial explains each step, the Pi 5 I2C buses, complete scanners in both languages, and what the bus looks like on my oscilloscope.
Raspberry Pi I2C Explained
I2C (Inter-Integrated Circuit) is a two-wire serial bus: SDA carries the data, and SCL carries the clock. The Raspberry Pi is the controller (the older name is master): it generates the clock and starts every transfer. Sensors, displays, ADCs, and port expanders are targets (slaves), and each one answers to its own 7-bit address, so up to 112 usable addresses share the same two wires.
Both lines are open-drain: a device can only pull a line LOW, and a pull-up resistor returns it HIGH. That’s why every I2C bus needs pull-up resistors, and why the slow rising edges you’ll see on the oscilloscope later limit how fast the bus can run.

Every transfer has the same shape. The controller sends a START condition (SDA falls while SCL is HIGH), the 7-bit address, and one R/W bit (0 = write, 1 = read). The addressed device answers with an ACK (it pulls SDA LOW on the 9th clock); if no device has that address, SDA stays HIGH, which is a NACK. Data bytes follow, each with its own ACK, and a STOP condition (SDA rises while SCL is HIGH) ends the transfer. Here is one real frame from my Raspberry Pi 5, with each bit read from the capture:
CH1 (yellow) is SDA on GPIO2 and CH3 (cyan) is SCL on GPIO3. The address bits 1110110 are 0x76, the R/W bit is 0 (write), and the sensor pulls SDA LOW on the 9th clock: that’s its ACK. My oscilloscope’s I2C decoder shows the same result on the bottom bar: 0x76 (W).
Raspberry Pi 5 I2C Pins and Buses
The I2C bus for your devices is I2C1 on GPIO2 (SDA, pin 3) and GPIO3 (SCL, pin 5), and Linux calls it /dev/i2c-1. It’s the same pins and the same bus number as on the Raspberry Pi 2, 3, and 4, so old wiring diagrams still apply. The positions on the 40-pin header are in my Raspberry Pi 5 pinout guide.
| Header Pin | GPIO | Function | Notes |
|---|---|---|---|
| Pin 3 | GPIO2 | I2C1 SDA | 1.8kΩ pull-up to 3.3v on the board |
| Pin 5 | GPIO3 | I2C1 SCL | 1.8kΩ pull-up to 3.3v on the board |
| Pin 27 | GPIO0 | ID_SD (HAT EEPROM) | Reserved for HAT identification |
| Pin 28 | GPIO1 | ID_SC (HAT EEPROM) | Reserved for HAT identification |
| Pin 1 / 17 | – | 3.3v | Power for 3.3v I2C modules |
| Pin 6, 9, … | – | GND | Common ground |
The Raspberry Pi 5 I2C Pull-Up Resistors
GPIO2 and GPIO3 have fixed 1.8kΩ pull-up resistors to 3.3v on the board, per the Raspberry Pi hardware documentation. So a module without its own pull-ups works on I2C1 with nothing extra. Most breakout modules (mine included) also carry their own pull-ups, typically 4.7kΩ or 10kΩ, which sit in parallel with the Pi’s: 1.8kΩ ∥ 10kΩ ≈ 1.5kΩ. That’s fine for one or two modules. With many modules, the parallel resistance gets low enough that the devices struggle to pull the lines LOW; remove the extra pull-ups (usually a solder jumper) if you stack more than a few. These fixed pull-ups are also why GPIO2 and GPIO3 make poor general-purpose inputs.
Which I2C Buses Does the Raspberry Pi 5 Have?
On the Raspberry Pi 5, the header’s I2C controllers live in the RP1 I/O chip. With I2C enabled, this is what my board lists:
i2c-1 is the header bus (a Synopsys DesignWare I2C controller inside RP1). i2c-13 and i2c-14 exist even with I2C disabled: they belong to the BCM2712 itself ( 107d508200.i2c and 107d508280.i2c) and aren’t on the 40-pin header, so leave them alone. RP1 has more I2C controllers that you can route to other header pins with the i2cN-pi5 overlays from the overlay README:
| Overlay (Pi 5) | Default Pins | Other Pin Choices | Linux Device |
|---|---|---|---|
i2c0-pi5 | GPIO0, GPIO1 | GPIO8, GPIO9 | /dev/i2c-0 |
i2c1-pi5 | GPIO2, GPIO3 | GPIO10, GPIO11 | /dev/i2c-1 |
i2c2-pi5 | GPIO4, GPIO5 | GPIO12, GPIO13 | /dev/i2c-2 |
i2c3-pi5 | GPIO6, GPIO7 | GPIO14, GPIO15 or GPIO22, GPIO23 | /dev/i2c-3 |
I tested i2c2-pi5 on my Raspberry Pi 5: loading the overlay creates /dev/i2c-2 and switches GPIO4 and GPIO5 to SDA2 and SCL2. Add dtoverlay=i2c2-pi5 to config.txt to make it permanent.
Note: Only GPIO2 and GPIO3 have pull-up resistors on the board. On any other I2C bus, add your own pull-ups (4.7kΩ to 3.3v is a common choice) or use modules that have them. The Raspberry Pi 4 numbers these extra buses differently (for example i2c3 on GPIO4/5 and i2c4 on GPIO6/7, with dtoverlay=i2c3 style names), per the overlay README and pinout.xyz, so don’t copy Raspberry Pi 4 bus numbers to a Pi 5.
The ID EEPROM I2C Bus (GPIO0 and GPIO1)
GPIO0 and GPIO1 (pins 27 and 28) are reserved for the HAT ID EEPROM: at boot, the firmware reads a HAT’s EEPROM on these pins to configure it. The Raspberry Pi documentation says not to use them for anything else unless you know what you’re doing. Use I2C1 for your devices.
3.3v Logic and 5v I2C Modules
Note: The Raspberry Pi GPIO pins are 3.3v only and aren’t 5v tolerant. A 5v I2C module whose pull-ups go to 5v pulls GPIO2 and GPIO3 up to 5v and can damage the Raspberry Pi. Power such a module from 3.3v if it works there, remove its 5v pull-ups, or use an I2C level shifter (a BSS138-based board, for example) between the Pi and the module.
How to Enable I2C on Raspberry Pi
I2C is disabled on a fresh Raspberry Pi OS image: /dev/i2c-1 doesn’t exist, and every I2C program fails to open it:
There are three ways to enable it. All three set the same line in config.txt, and none of them needs a reboot on my Pi 5 except the manual edit.
Method 1: Enable I2C With raspi-config
#1
Run sudo raspi-config, select 3 Interface Options, and press Enter.

#2
Select I5 I2C and press Enter.

#3
Choose <Yes> when asked “Would you like the ARM I2C interface to be enabled?” (the cursor starts on <No>: press the Left arrow).

#4
raspi-config confirms “The ARM I2C interface is enabled”. Press Enter, then select <Finish>.

Method 2: Enable I2C From the Command Line (raspi-config nonint)
For scripts and headless setups, raspi-config has a non-interactive mode. do_i2c 0 enables I2C, do_i2c 1 disables it, and get_i2c prints 0 when it’s enabled:
|
1 |
sudo raspi-config nonint do_i2c 0 |
Both raspi-config methods write dtparam=i2c_arm=on (or off) to /boot/firmware/config.txt and apply it right away, so /dev/i2c-1 appears without a reboot.
Method 3: Enable I2C in config.txt (dtparam=i2c_arm=on)
On a fresh image, config.txt already contains the line, commented out: #dtparam=i2c_arm=on. Open the file with sudo nano /boot/firmware/config.txt, remove the #, save, and reboot:
|
1 |
dtparam=i2c_arm=on |
On current Raspberry Pi OS the file is /boot/firmware/config.txt; /boot/config.txt is the location from older releases. You don’t need to edit /etc/modules or a blacklist file anymore: the i2c-dev module loads by itself.
Check the I2C Group (No sudo Needed)
/dev/i2c-1 belongs to the i2c group, and the user created by Raspberry Pi Imager is already a member, so i2c-tools, Python, and C++ all work without sudo:
Raspberry Pi I2C Wiring (BMP280 / BME280 Module)
For the examples, I use a purple 6-pin BMP280 breakout module. These modules are often sold as “BME280”: mine was, and its chip ID register told me it’s a BMP280 (more on that below). The two chips share the address, the chip ID register location, and the control registers used here, so every example works on both. The sensor itself gets its own tutorial; here it’s simply a well-behaved I2C device.
| QTY. | Component Name | Amazon.com | AliExpress |
|---|---|---|---|
| 1 | Raspberry Pi 5 (4GB or 8GB) | Amazon | AliExpress |
| 1 | Raspberry Pi 27W USB-C Power Supply | Amazon | AliExpress |
| 1 | BMP280 or BME280 I2C Module (3.3v) | Amazon | AliExpress |
| 1 | Breadboard | Amazon | AliExpress |
| 1 | Jumper Wires (Female-Male) | Amazon | AliExpress |

Four wires: power, ground, and the two I2C lines. The module’s CSB pin selects SPI or I2C and its SDO pin selects the address; leave both unconnected and the module’s own resistors select I2C at address 0x76 (tie SDO to 3.3v for 0x77).
3.3v Module VCC (pin 1). Use 3.3v, not 5v, for a 3.3v module
GND Module GND (pin 9)
GPIO2 Module SDA (pin 3), I2C1 data
GPIO3 Module SCL (pin 5), I2C1 clock
Raspberry Pi I2C Scan With i2cdetect
i2c-tools (version 4.4 on Trixie) is pre-installed on Raspberry Pi OS. If i2cdetect is missing on another image, install it with sudo apt install i2c-tools. These are the versions on my Raspberry Pi 5:
Scan bus 1 with i2cdetect -y 1 ( -y skips the “are you sure” question). Don’t add sudo: it’s not needed when you’re in the i2c group.
Each cell is one 7-bit address. A number ( 76) means a device answered with an ACK. -- means nobody answered. UU means a kernel driver owns that address, so i2cdetect skips it (there’s an example in the troubleshooting section). Addresses 0x00 to 0x07 and 0x78 to 0x7F are reserved and not scanned.
Write Probe vs Read Probe (i2cdetect -q and -r)
i2cdetect probes each address with one of two short transfers. A quick write sends START, the address with the write bit, and STOP: no data at all. A read byte probe reads one byte instead. By default, i2cdetect uses the read probe for 0x30-0x37 and 0x50-0x5F (where EEPROMs live, because a quick write can corrupt some of them) and the quick write everywhere else, per the i2cdetect manual. -q forces quick writes and -r forces reads; -r matters for write-only devices that would otherwise lock up. For a normal sensor, both find it:
This is what the default quick-write probe looks like on my oscilloscope: first at 0x76, where the BMP280 answers, then at 0x77, where nothing does:
At 0x76, SDA goes LOW on the 9th clock (ACK). At 0x77, SDA stays HIGH on the 9th clock (NACK), which my oscilloscope’s decoder marks as ~A. That single bit is all an I2C scan looks at.
i2cget, i2cset, i2ctransfer, and i2cdump
The other i2c-tools read and write registers straight from the shell, which is the fastest way to check a device before writing any code:
| Command | What It Does |
|---|---|
i2cget -y 1 0x76 0xd0 | Reads one register (0xD0) of the device at 0x76 |
i2cset -y 1 0x76 0xf4 0x24 | Writes 0x24 to register 0xF4 |
i2ctransfer -y 1 w1@0x76 0xd0 r1 | Raw transfer: write 1 byte, repeated START, read 1 byte |
i2cdump -y -r 0xd0-0xff 1 0x76 | Dumps a register range as a table |
i2cdetect -F 1 | Lists what the bus driver supports |
i2ctransfer can read several bytes in one transfer: r6 after register 0x88 returns six calibration bytes. i2cdetect -F 1 shows that the Pi 5 driver supports plain I2C, the SMBus commands, and 10-bit addressing, but not target (slave) mode:
Raspberry Pi I2C Python (smbus2)
In Python, I use smbus2, the most popular I2C library for Linux (smbus2 on PyPI). It’s a pure-Python library that talks to /dev/i2c-* directly, and Raspberry Pi OS Trixie ships it as python3-smbus2 (0.4.3), already installed on my image. If it’s missing, install it with apt:
|
1 |
sudo apt install python3-smbus2 |
Note: Don’t use pip install smbus2 into the system Python: current Raspberry Pi OS blocks it with “externally-managed-environment” (PEP 668). Use the apt package, or a virtual environment if you need a newer version. The older python3-smbus module ( import smbus) is also on the image; smbus2 is a drop-in replacement that adds i2c_rdwr for any-length transfers.
Raspberry Pi I2C Scanner in Python
In the following example project, we’ll write an I2C scanner that prints the same table as i2cdetect, with the same probe rules: a quick write by default, a read byte for the EEPROM ranges, and -r / -q options.
Here is The Application Code For This Example Project (i2c_scan.py):
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
#!/usr/bin/env python3 # Raspberry Pi I2C Scanner (smbus2) - prints the same table as i2cdetect # Usage: python3 i2c_scan.py [bus] [-r | -q] # default : quick-write probe, except read-byte for 0x30-0x37 and 0x50-0x5F (like i2cdetect) # -r : read-byte probe for every address # -q : quick-write probe for every address import errno import sys from smbus2 import SMBus bus_number = 1 mode = "auto" for arg in sys.argv[1:]: if arg == "-r": mode = "read" elif arg == "-q": mode = "quick" else: bus_number = int(arg) def probe(bus, address): """Return 'found', 'busy' (a kernel driver owns it) or 'none'.""" use_read = mode == "read" or (mode == "auto" and (0x30 <= address <= 0x37 or 0x50 <= address <= 0x5F)) try: if use_read: bus.read_byte(address) # START, addr+R, ACK?, 1 byte, NACK, STOP else: bus.write_quick(address) # START, addr+W, ACK?, STOP (no data) return "found" except OSError as e: if e.errno == errno.EBUSY: # address claimed by a kernel driver return "busy" return "none" # NACK -> Remote I/O error (errno 121) with SMBus(bus_number) as bus: print(" 0 1 2 3 4 5 6 7 8 9 a b c d e f") for row in range(0x00, 0x80, 0x10): line = f"{row:02x}:" for col in range(16): address = row + col if address < 0x08 or address > 0x77: # reserved addresses, not probed line += " " continue result = probe(bus, address) line += {"found": f" {address:02x}", "busy": " UU", "none": " --"}[result] print(line) |
Raspberry Pi I2C Python Scanner Code Explanation
SMBus(1) opens /dev/i2c-1. For each address, write_quick() sends the quick-write probe (START, address + W, STOP) and read_byte() sends the read probe. A device that ACKs makes the call return normally. A NACK raises OSError with errno 121 (Remote I/O error), so it’s printed as --. errno 16 (EBUSY) means a kernel driver owns the address, so it’s printed as UU, exactly like i2cdetect.
Run it with python3 i2c_scan.py. This is the output on my Raspberry Pi 5:
Raspberry Pi I2C Read and Write Register in Python
Now let’s read and write registers. In the following example project, we’ll read the chip ID register (0xD0) three ways and then write the control register ctrl_meas (0xF4) and read it back:
- read_byte_data(): one combined transfer. It writes the register number, then sends a repeated START and reads, with no STOP in between.
- write_byte() + read_byte(): two separate transfers, each with its own START and STOP.
- i2c_rdwr(): raw messages of any length in one combined transfer, for devices that need more than SMBus allows.
Here is The Application Code For This Example Project (bme280_regs.py):
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
#!/usr/bin/env python3 # Raspberry Pi I2C register read/write with smbus2 (BME280 as the example device) # Reads the chip ID, writes one control register and reads it back. import sys from smbus2 import SMBus, i2c_msg BUS = 1 ADDRESS = int(sys.argv[1], 0) if len(sys.argv) > 1 else 0x76 # 0x77 if SDO is tied to 3.3v REG_CHIP_ID = 0xD0 # reads 0x60 on a BME280 (0x58 on a BMP280) REG_CTRL_MEAS = 0xF4 # osrs_t[7:5] osrs_p[4:2] mode[1:0] with SMBus(BUS) as bus: # 1) One combined transaction: write the register number, repeated START, read 1 byte chip_id = bus.read_byte_data(ADDRESS, REG_CHIP_ID) print(f"Chip ID (read_byte_data, repeated START): 0x{chip_id:02X}") # 2) The same read as two separate transactions (STOP between them) bus.write_byte(ADDRESS, REG_CHIP_ID) # START addr+W reg STOP chip_id = bus.read_byte(ADDRESS) # START addr+R data STOP print(f"Chip ID (write_byte + read_byte, STOP between): 0x{chip_id:02X}") # 3) Raw messages with i2c_rdwr: any length, one combined transfer write = i2c_msg.write(ADDRESS, [REG_CHIP_ID]) read = i2c_msg.read(ADDRESS, 1) bus.i2c_rdwr(write, read) print(f"Chip ID (i2c_rdwr): 0x{list(read)[0]:02X}") # 4) Write a register and read it back before = bus.read_byte_data(ADDRESS, REG_CTRL_MEAS) bus.write_byte_data(ADDRESS, REG_CTRL_MEAS, 0x24) # osrs_t x1, osrs_p x1, sleep mode after = bus.read_byte_data(ADDRESS, REG_CTRL_MEAS) print(f"ctrl_meas: 0x{before:02X} -> wrote 0x24 -> read back 0x{after:02X}") bus.write_byte_data(ADDRESS, REG_CTRL_MEAS, before) # restore the old value |
This is the output on my Raspberry Pi 5:
All three reads return 0x58, and ctrl_meas reads back the 0x24 we wrote. The script then restores the old value, so the sensor stays in sleep mode. The two transfer styles look like this on my oscilloscope:
In the first capture there’s no STOP between the register write and the read: the repeated START keeps control of the bus, so no other controller can take the bus in between. In the second, a STOP ends the register write and a new START begins the read. The BMP280 accepts both. Some devices don’t keep the register pointer after a STOP, so prefer the repeated START ( read_byte_data(), i2c_rdwr()) for register reads.
Raspberry Pi I2C C++ (Linux i2c-dev)
In C and C++, the standard way to use I2C on Linux is the kernel’s i2c-dev interface (kernel documentation), not a third-party library. Unlike GPIO, where libgpiod is the library, I2C needs only the kernel headers that come with the compiler: you open() /dev/i2c-1, select the target address with ioctl(fd, I2C_SLAVE, addr), and then read() / write() bytes or send combined transfers with ioctl(fd, I2C_RDWR, ...). The libi2c-dev package adds i2c_smbus_*() helper functions on top, but the examples below don’t need it.
Raspberry Pi I2C Scanner in C++
In the following example project, we’ll write the same i2cdetect-style scanner in C++.
Here is The Application Code For This Example Project (i2c_scan.cpp):
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
// Raspberry Pi I2C Scanner in C++ (Linux i2c-dev) - prints the same table as i2cdetect // Build: g++ -std=c++17 -O2 i2c_scan.cpp -o i2c_scan // Usage: ./i2c_scan [bus] [-r | -q] #include <cerrno> #include <cstdio> #include <cstring> #include <string> #include <fcntl.h> #include <unistd.h> #include <sys/ioctl.h> #include <linux/i2c.h> #include <linux/i2c-dev.h> // SMBus "quick write": START, address + W, ACK?, STOP (no data byte) static int quick_write(int fd) { i2c_smbus_ioctl_data args{}; args.read_write = I2C_SMBUS_WRITE; args.command = 0; args.size = I2C_SMBUS_QUICK; args.data = nullptr; return ioctl(fd, I2C_SMBUS, &args); } int main(int argc, char *argv[]) { int bus = 1; char mode = 'a'; // a = auto (like i2cdetect), r = read-byte probe, q = quick-write probe for (int i = 1; i < argc; i++) { if (!strcmp(argv[i], "-r")) mode = 'r'; else if (!strcmp(argv[i], "-q")) mode = 'q'; else bus = std::stoi(argv[i]); } std::string dev = "/dev/i2c-" + std::to_string(bus); int fd = open(dev.c_str(), O_RDWR); if (fd < 0) { std::fprintf(stderr, "Could not open %s: %s\n", dev.c_str(), std::strerror(errno)); return 1; } std::printf(" 0 1 2 3 4 5 6 7 8 9 a b c d e f\n"); for (int row = 0x00; row < 0x80; row += 0x10) { std::printf("%02x:", row); for (int col = 0; col < 16; col++) { int addr = row + col; if (addr < 0x08 || addr > 0x77) { std::printf(" "); continue; } // Select the target address; EBUSY means a kernel driver owns it if (ioctl(fd, I2C_SLAVE, addr) < 0) { std::printf(errno == EBUSY ? " UU" : " --"); continue; } bool use_read = mode == 'r' || (mode == 'a' && ((addr >= 0x30 && addr <= 0x37) || (addr >= 0x50 && addr <= 0x5F))); unsigned char byte; int res = use_read ? (int)read(fd, &byte, 1) : quick_write(fd); if (res < 0) std::printf(" --"); // NACK -> errno 121 (Remote I/O error) else std::printf(" %02x", addr); } std::printf("\n"); } close(fd); return 0; } |
Raspberry Pi I2C C++ Scanner Code Explanation
ioctl(fd, I2C_SLAVE, addr) sets the address for the following transfers. It fails with EBUSY if a kernel driver already owns that address, which we print as UU. The quick write is an SMBus command, so we send it through ioctl(fd, I2C_SMBUS, ...) with I2C_SMBUS_QUICK; the read probe is a plain one-byte read(). A NACK makes either call return -1 with errno 121.
Build and run both C++ examples:
Raspberry Pi I2C Read and Write Register in C++
In the following example project, we’ll do the same register work as the Python version: the chip ID read with a repeated START ( I2C_RDWR with two messages), the same read as two separate transfers, and the ctrl_meas write and read-back.
Here is The Application Code For This Example Project (bme280_regs.cpp):
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
// Raspberry Pi I2C register read/write in C++ (Linux i2c-dev), BME280 as the example device // Build: g++ -std=c++17 -O2 bme280_regs.cpp -o bme280_regs #include <cstdint> #include <cstdio> #include <cstdlib> #include <fcntl.h> #include <unistd.h> #include <sys/ioctl.h> #include <linux/i2c.h> #include <linux/i2c-dev.h> static uint16_t ADDRESS = 0x76; // 0x77 if SDO is tied to 3.3v (or pass it: ./bme280_regs 0x77) constexpr uint8_t REG_CHIP_ID = 0xD0; // 0x60 on a BME280 (0x58 on a BMP280) constexpr uint8_t REG_CTRL_MEAS = 0xF4; // Register read as ONE combined transaction: write reg, repeated START, read n bytes static int read_regs(int fd, uint8_t reg, uint8_t *buf, uint16_t len) { i2c_msg msgs[2] = { { ADDRESS, 0, 1, ® }, // address + W, register number { ADDRESS, I2C_M_RD, len, buf }, // repeated START, address + R, data }; i2c_rdwr_ioctl_data xfer{ msgs, 2 }; return ioctl(fd, I2C_RDWR, &xfer); } // Register write: address + W, register number, value, STOP static int write_reg(int fd, uint8_t reg, uint8_t value) { uint8_t out[2] = { reg, value }; return write(fd, out, 2) == 2 ? 0 : -1; } int main(int argc, char *argv[]) { if (argc > 1) ADDRESS = std::strtol(argv[1], nullptr, 0); int fd = open("/dev/i2c-1", O_RDWR); if (fd < 0) { std::perror("open /dev/i2c-1"); return 1; } if (ioctl(fd, I2C_SLAVE, ADDRESS) < 0) { std::perror("ioctl I2C_SLAVE"); return 1; } uint8_t id = 0; if (read_regs(fd, REG_CHIP_ID, &id, 1) < 0) { std::perror("I2C_RDWR"); return 1; } std::printf("Chip ID (I2C_RDWR, repeated START): 0x%02X\n", id); // The same read as two separate transactions (STOP between them) uint8_t reg = REG_CHIP_ID; if (write(fd, ®, 1) != 1 || read(fd, &id, 1) != 1) { std::perror("write/read"); return 1; } std::printf("Chip ID (write + read, STOP between): 0x%02X\n", id); uint8_t before = 0, after = 0; read_regs(fd, REG_CTRL_MEAS, &before, 1); write_reg(fd, REG_CTRL_MEAS, 0x24); // osrs_t x1, osrs_p x1, sleep mode read_regs(fd, REG_CTRL_MEAS, &after, 1); std::printf("ctrl_meas: 0x%02X -> wrote 0x24 -> read back 0x%02X\n", before, after); write_reg(fd, REG_CTRL_MEAS, before); // restore the old value close(fd); return 0; } |
read_regs() builds two i2c_msg entries, a 1-byte write of the register number and an I2C_M_RD read, and the kernel sends them as one transfer with a repeated START. write_reg() is a plain 2-byte write(): register number, then value. The output on my Raspberry Pi 5:
I2C Address: 7-Bit vs 8-Bit
Linux, i2cdetect, smbus2, and i2c-dev all use the 7-bit address. Some datasheets and libraries print the 8-bit form instead: the 7-bit address shifted left by one, with the R/W bit added. For the BMP280 at 0x76, per the BMP280 datasheet:
| Form | Write | Read | Use In Linux Code? |
|---|---|---|---|
| 7-bit address | 0x76 | 0x76 | Yes |
| 8-bit address byte | 0xEC (0x76 << 1) | 0xED ((0x76 << 1) | 1) | No |
If a datasheet gives you 0xEC, divide it by two (shift right by one) to get 0x76 for your code. Passing 0xEC to Linux fails, because it’s above the 7-bit range of 0x7F.
Raspberry Pi I2C Speed (i2c_arm_baudrate)
The default I2C clock on the Raspberry Pi is 100kHz (standard mode). Set a different speed with i2c_arm_baudrate in /boot/firmware/config.txt and reboot:
|
1 2 |
dtparam=i2c_arm=on dtparam=i2c_arm_baudrate=400000 |
Read the active speed back from the device tree with od -An -tu4 --endian=big /sys/bus/i2c/devices/i2c-1/of_node/clock-frequency. I set 100kHz, 400kHz, and 1MHz, ran the same chip ID read, and measured SCL on my oscilloscope. The BMP280 is rated for I2C up to 3.4MHz, so the sensor isn’t the limit here:
| i2c_arm_baudrate | SCL Measured | SCL Rise Time (10-90%) | Full Scan (i2cdetect / C++ / Python) | One Register Read (Python / C++) |
|---|---|---|---|---|
| 100000 (default) | 99.0kHz | 0.47µs | 15.3 / 15.9 / 40.9ms | 424 / 421µs |
| 400000 | 384.6kHz | 0.49µs | 7.0 / 8.5 / 33.5ms | 136 / 133µs |
| 1000000 | 917.4kHz | SCL never reaches 3.3v | 5.3 / 5.9 / 31.7ms | 76 / 72µs |
CH1 (yellow) is SDA and CH3 (cyan) is SCL, both with 1X probes. The falling edges are fast (about 35ns), because a transistor pulls the line LOW. The rising edges are slow, about 0.47µs, because only the pull-up resistors charge the line’s capacitance back to 3.3v. That rise time stays the same at every speed, so it takes a bigger share of each period as the clock goes up. At 1MHz, SCL never settles at 3.3v before the next falling edge, yet every read still returned the right value on my bench.
The measured clock is a little below each setting, and the gap grows with speed. Part of that is the slow rising edge: during clock synchronization, the controller times the HIGH phase from the moment it sees SCL HIGH, so a slow rise stretches each period (I2C specification, UM10204, section 3.1.7). The I2C specification allows at most 1000ns of rise time in standard mode, 300ns in fast mode (400kHz), and 120ns in fast mode plus (1MHz). My 1X probes add their own capacitance to each line, so the bus alone rises faster than these captures show. For a long bus or many devices at 400kHz or more, use stronger pull-ups on the modules (lower resistance, within what the devices can sink) or stay at 100kHz.
The scan and read times show where the time goes. A full scan probes 112 addresses: about 15ms at 100kHz and 5ms at 1MHz, with Python adding about 25ms of interpreter start-up. One register read takes about 420µs at 100kHz, almost all of it on the wire (29 clock cycles plus the gaps), and only about 3µs separates Python from C++. Pick the bus speed first; the language barely matters for I2C.
Raspberry Pi I2C Clock Stretching
Some I2C devices hold SCL LOW to make the controller wait (clock stretching). The I2C controller in the BCM2835/BCM2711 chips of the Raspberry Pi 4 and older has a known bug with short clock stretches, which is why older tutorials say “the Raspberry Pi can’t do clock stretching” (Adafruit’s clock stretching guide). The Raspberry Pi 5’s header I2C is a different controller, the Synopsys DesignWare core inside RP1, so that bug report doesn’t carry over. My BMP280 never stretches the clock, so I couldn’t test stretching on the Pi 5 here. If you use a device that stretches (some gas and humidity sensors do), test it at your bus speed before you rely on it.
Raspberry Pi I2C vs Arduino Wire
If you’re coming from microcontrollers, here is how the Arduino Wire calls map to the Raspberry Pi:
| Arduino (Wire) | Python (smbus2) | C++ (i2c-dev) |
|---|---|---|
Wire.begin() | bus = SMBus(1) | fd = open("/dev/i2c-1", O_RDWR) |
Wire.beginTransmission(0x76) | the address goes in each call | ioctl(fd, I2C_SLAVE, 0x76) |
Wire.write(reg); Wire.endTransmission(false) | read_byte_data(0x76, reg) | ioctl(fd, I2C_RDWR, ...) (2 messages) |
Wire.requestFrom(0x76, 1); Wire.read() | read_byte(0x76) | read(fd, &b, 1) |
Wire.setClock(400000) | config.txt i2c_arm_baudrate | config.txt i2c_arm_baudrate |
The big difference: on Linux, the kernel owns the bus, so you set the clock in config.txt and not in your program, and an error comes back as an errno instead of endTransmission()’s return code. For the microcontroller side, see my Arduino I2C tutorial, Arduino I2C scanner, ESP32 I2C tutorial, and the STM32 I2C tutorial.
Raspberry Pi I2C Troubleshooting
These are the real errors I hit on the Raspberry Pi 5, with their causes and fixes.
Could not open file /dev/i2c-1: No such file or directory
I2C is disabled. Enable it with any of the three methods above. In Python, the same problem is a FileNotFoundError:
Remote I/O error (errno 121) or Error: Read failed
The device didn’t ACK its address: the address is wrong, the device isn’t powered, or SDA and SCL are swapped or loose. Run i2cdetect -y 1 and use the address it shows.
UU in i2cdetect and Device or resource busy
UU means a kernel driver has claimed that address, usually because a dtoverlay line (for example i2c-sensor or i2c-rtc) loaded a driver for the device. Your program then gets “Device or resource busy” (errno 16). I bound the kernel’s bmp280 driver to the sensor to show it, then removed it:
Either use the kernel driver (the sensor appears under /sys/bus/iio/devices/), or remove the overlay line from config.txt so your program can talk to the device directly.
Could not open file /dev/i2c-1: Permission denied
The user isn’t in the i2c group. Add it with sudo usermod -aG i2c $USER and log in again. Don’t work around it with sudo in every command.
i2cdetect Shows No Devices
If the scan runs but shows only --, check the wiring first: SDA to GPIO2 (pin 3), SCL to GPIO3 (pin 5), power, and ground. On I2C1 a missing pull-up isn’t the cause, because the board has its own 1.8kΩ pull-ups; on the extra buses ( i2c2-pi5 and so on), no pull-ups means no devices.
A 5v Module Doesn’t Respond, or You’re Worried About 5v
Check the module’s VCC range and where its pull-ups go. If they pull to 5v, don’t connect SDA and SCL straight to the Pi: use a level shifter, as explained in the 3.3v logic section above.
BME280 Module Reports a BMP280 Chip ID (0x58)
The chip ID register (0xD0) reads 0x60 on a BME280 and 0x58 on a BMP280, per the BME280 and BMP280 datasheets. The two look alike and the purple modules are often mislabeled, so read 0xD0 before you trust the label. A BMP280 has no humidity sensor.
Raspberry Pi I2C FAQ
How many I2C buses does the Raspberry Pi 5 have?
One is enabled for your devices: I2C1 on GPIO2 and GPIO3 ( /dev/i2c-1). RP1 can route up to four I2C buses to the header with the i2c0-pi5 to i2c3-pi5 overlays, and the board uses a few more internally that aren’t on the header.
Do I need pull-up resistors for I2C on the Raspberry Pi?
Not on GPIO2 and GPIO3: they have 1.8kΩ pull-ups on the board. On any other pins used for I2C, yes.
Can I use any GPIO pins for I2C on the Raspberry Pi 5?
Not any pins: the hardware I2C controllers can use only the pin pairs listed in the overlay table above. The i2c-gpio overlay bit-bangs I2C on other pins, but it’s slower and uses CPU time.
Do I need sudo for i2cdetect?
No. On current Raspberry Pi OS, your user is in the i2c group, so i2cdetect -y 1 works without sudo.
What is the default I2C speed on the Raspberry Pi?
100kHz. Change it with dtparam=i2c_arm_baudrate=400000 (or another value) in config.txt and reboot.
Is it i2c-0 or i2c-1 on the Raspberry Pi?
i2c-1 on every Raspberry Pi since the Model B revision 2 (2012), including the Pi 5. Only the very first Model B used i2c-0 on the header.
Download Raspberry Pi I2C Examples
The download contains every example from this tutorial in Python and C++: the quick examples, the i2cdetect-style scanners, and the register read and write examples, plus the timing programs behind the measurements, with a README that lists each command.
Download Raspberry Pi I2C Examples (Python, C++)
Download all attachment files for this Article/Tutorial (project files, schematics, code, etc.) using the link below. Everything is tested and verified to work on real hardware, as you’ve seen in the demo videos & screenshots. Please consider supporting my work if it helped you.
Wrap Up
To conclude this tutorial, we’ve enabled Raspberry Pi I2C on the Raspberry Pi 5 three ways, found the device with i2cdetect and with our own scanners in Python (smbus2) and C++ (i2c-dev), and read and written its registers with and without a repeated START. The measurements show what to expect from the bus: the default 100kHz is slowest but has the most margin, 400kHz cuts a register read to about a third, and 1MHz works on a short bus even though SCL never fully rises.
For the GPIO basics, see my Raspberry Pi GPIO tutorial, and for the GPIO libraries, the Raspberry Pi GPIO library comparison. The next tutorials in this Raspberry Pi series cover SPI and UART, and full projects with I2C sensors and displays. For a first I2C project with a display, see my Raspberry Pi OLED display tutorial.
