We are using the BOSCH BME280 as an example of how to add 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.
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.
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, takes a
serial.Device as argument - perfect!
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