What is an I²C Bus on an ESP32 and ESP8266?
The I²C (Inter-Integrated Circuit) is a communication protocol used to connect different electronic components, like sensors and microcontrollers, on the same circuit board. It was invented by Philips Semiconductor (now NXP Semiconductors) and is widely used for attaching lower-speed peripheral ICs to processors and microcontrollers. It's pronounced I-squared-C or I-two-C. Essentially, it enables easy and efficient communication between different parts of an electronic device.
How can you configure an I²C Bus on an ESP32 or ESP8266?
You can configure the I²C Bus quite easily using ESPHome for use with sensors. I'll spare you the technical details about this process, but you're more than welcome to have a look yourself at The I²C Bus in ESPHome.
Here's an example configuration you can use for your I²C Bus on a ESP32 device:
i2c:
sda: 21
scl: 22
scan: true
id: bus_a
And If you've got an ESP8266 device instead, you can use this configuration:
i2c:
sda: 4
scl: 5
scan: true
You might notice the missing id in the configuration for the ESP8266. This field is optional because this device only supports 1 I²C Bus. The ESP32 supports 2 buses, so by using the id, you can differentiate between the two configured buses.
If you're not looking to change any of the default values in your configuration, you can also specify just specify the i2c block without any additional information:
i2c:
The default values will now be used. You can find the default values here: Default configuration values.
How do you use the I²C Bus with a sensor?
We've found out that the ESP32 supports 2 buses, so its configuration will look a little different than the ESP8266. Let's have a look:
i2c:
- id: bus_a
sda: 13
scl: 16
scan: true
- id: bus_b
sda: 14
scl: 15
scan: true
sensor:
- platform: bme680
i2c_id: bus_b
address: 0x76
This configuration shows 2 buses being configured for an ESP32, each sensor has its own unique id, so we can easily reference it in the sensor configuration. As you can see in the sensor configuration for the "bme680" platform, we can add a reference to the I²C Bus we'd like to use for this sensor using the "i2c_id" property.
So what does this look like for an ESP8266 device that only supports a single I²C Bus? Let's have a look:
i2c:
- sda: 4
scl: 5
scan: true
sensor:
- platform: bme680
address: 0x76
Since the ESP8266 only supports 1 I²C Bus, you don't have to specify an id, as it'll be the only one and that's why you also won't have to specify it in the configuration of the sensor. It'll just pick the one configured bus.
Posted on: Aug 3, 2023 Last updated at: Aug 3, 2023