Connect sensors

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.

Setup

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.

BME280
BME280

A detailed description of adding sensors using the Qwiic cable can be found here.

I2C bus

First we're going to set up the I2C bus so we can connect the device:

import gpio
import 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 0x77:

  device := bus.device 0x77

The device returned is of type serial.Device.

Driver

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!

import bme280

// ...

driver := bme280.Driver device

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"

Test it on an ESP32

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"