We are using the BOSCH BME280 as an example of how to connect a sensor to your ESP32. The BOSCH BME280 chip is an environment 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.
The remaining two wires are I2C SDA (
blue) and I2C SCL (
yellow). While any GPIO pin of the ESP32 can facilitate an I2C setup we're going to pick pin 21 and 22 respectively through 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:
import gpio import serial.protocols.i2c as i2c main: bus := i2c.Bus --sda=gpio.Pin 21 --scl=gpio.Pin 22
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 at
drivers.bme280 and as all other drivers available, 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:
bme.on print "Temperature: $bme.read_temperature C" print "Humidity: $bme.read_humidity %" print "Pressure: $bme.read_pressure Pa" bme.off
That will print out something along the lines of
$ toit run -d demo-device bme280.toit 2021-01-20T09:30:07.678192Z: <process initiated> Temperature: 22.350000000000001421 C Humidity: 45.2626953125 % Pressure: 98641.3359375 Pa 2021-01-20T09:30:07.858870Z: <process terminated - exit code: 0>
import gpio import serial.protocols.i2c as i2c import drivers.bme280 main: bus := i2c.Bus --sda=gpio.Pin 21 --scl=gpio.Pin 22 device := bus.device 0x77 bme := drivers.Bme280 device bme.on print "Temperature: $bme.read_temperature C" print "Humidity: $bme.read_humidity %" print "Pressure: $bme.read_pressure Pa" bme.off