We are using the BOSCH BME280 as an example of how to connect a sensor to your ESP32. The BOSCH BME280 chip is an environmental sensor measuring temperature, humidity and pressure.
The sensor supports both I2C and SPI connection mode. This guide will focus on the SparkFun BME280 breakout board connected using a Qwiic cable.
If you connect a different BME280 sensor breakout board, you may have to place additional pull-up resistors on the I2C wires.
Connect the Qwiic cable to the BME280 breakout board and connect the red wire to 3.3V (
3V3) and the black wire to ground (GND).
The remaining two wires are I2C SDA (blue) and I2C SCL (yellow). While almost any GPIO pin of the ESP32 can facilitate an I2C setup we are going to pick pin 21 and pin 22, respectively, throughout this guide.
A detailed description of adding sensors using the Qwiic cable can be found here.
First we're going to set up the I2C bus so we can connect the device:
With the bus configured, we can specify how to address the BME280 device on the bus.
From the SparkFun BME280 breakout documentation we can see that the default configured address is
The device returned is of type
With the device configured we can take a look at the driver. The driver is available as a package from pkg.toit.io.
The driver takes a
serial.Device as argument - perfect!
Configuring an SPI Bus and Device will also provide a
serial.Device. The driver thus works seamlessly between I2C and SPI setups.
The driver will take care of all the communication with the BME280 sensor and provides a high-level API for reading out the relevant data:
print "Temperature: $driver.read_temperature C" print "Humidity: $driver.read_humidity %" print "Pressure: $driver.read_pressure Pa"
In the Weather Station tutorial, you can learn how to run this Toit program on the ESP32 or deploy it as a long-lived application, where a specification file determines the execution intervals.
The full code can be seen below:
/** Program measuring temperature, relative humidity, and atmospheric pressure with a BME280. */ import gpio import i2c import bme280 main: bus := i2c.Bus --sda=gpio.Pin 21 --scl=gpio.Pin 22 device := bus.device bme280.I2C_ADDRESS_ALT driver := bme280.Driver device print "Temperature: $driver.read_temperature C" print "Humidity: $driver.read_humidity %" print "Pressure: $driver.read_pressure Pa"