Reading Sensors over I2C with Raspberry Pi
raspberry pii2csensorsbme280electronics
I2C is a two-wire protocol letting you chain multiple sensors on two GPIO pins. BME280, SSD1306 displays, and RTC modules all use I2C.
Enable I2C
sudo raspi-config
# Interface Options > I2C > Enable
Wiring
| Pi Pin | I2C Function | Sensor Pin |
|---|---|---|
| 3.3V | Power | VCC |
| GPIO2 (Pin 3) | SDA | SDA |
| GPIO3 (Pin 5) | SCL | SCL |
| GND | Ground | GND |
Multiple I2C devices share the same SDA/SCL โ each has a unique address.
Detect Devices
sudo apt install i2c-tools -y
sudo i2cdetect -y 1
Shows addresses of all connected devices (e.g. 0x76 for BME280).
BME280 Temperature/Humidity/Pressure
pip install adafruit-circuitpython-bme280
import board
import adafruit_bme280.basic as adafruit_bme280
i2c = board.I2C()
bme280 = adafruit_bme280.Adafruit_BME280_I2C(i2c)
print(f"Temperature: {bme280.temperature:.1f} C")
print(f"Humidity: {bme280.humidity:.1f} %")
print(f"Pressure: {bme280.pressure:.1f} hPa")
SSD1306 OLED Display
pip install adafruit-circuitpython-ssd1306 pillow
import board, adafruit_ssd1306
from PIL import Image, ImageDraw
i2c = board.I2C()
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c)
img = Image.new("1", (128, 64))
draw = ImageDraw.Draw(img)
draw.text((0, 0), "Hello World", fill=255)
oled.image(img)
oled.show()
Multiple Devices
Each I2C device needs a unique address. If two devices share an address, use a TCA9548A I2C multiplexer.