This article will guide you on how to interface the BME688 environmental sensor with Raspberry Pi Pico using MicroPython. The BME688 is a low-power sensor that can measure temperature, humidity, pressure, and gas. The sensor is connected to the Raspberry Pi Pico via I2C Communication. We use MicroPython code to read the BME688 sensor data and display it on the Thonny Shell.
The sensor is ideal for applications such as weather stations, indoor climate control, and Precision Agriculture. Checkout BME280 With Raspberry Pi Pico W Using MicroPython
Thank You, NextPCB!
Our project reached successful completion thanks to the valuable help of NextPCB. If you’re working on a PCB project, we highly suggest you see their website to take benefit of some great discounts and coupons.
NextPCB offers high-quality, reliable PCB starting at $1.9, and multilayer starting at $6.9. Also, everyone can enjoy free PCB assembly for 5 boards!
Required Material
- BME688 Sensor
- Raspberry Pi Pico
- Jumper Wire
- Breadboard
BME688 Environmental Gas Sensor
BME688 sensor is an engineered environmental sensor developed by Bosch Sensortec. It is designed to not only measure things like temperature, humidity, pressure, and gas resistance very accurately, but it’s also the first of its kind to have Artificial Intelligence (AI) built-in. Even though it’s robust, it’s super tiny, only about 3.0 x 3.0 x 0.9 mm in size.
The most important thing is it can sniff out something like bad-smelling gases (Volatile Organic Compounds), smelly sulfur compounds, and even harmful gases like carbon monoxide and hydrogen in really small amounts (part per billion range). Check the previous post for more information BME688 Gas Sensor with Arduino
This sensor is the best choice for applications such as weather stations, indoor air quality monitors, and IoT devices.
BME688 Sensor Pinout
Power Supply Pins:
- VCC / Vin: Supply power (3.3V or 5V) to the sensor.
- GND: Connect to ground.
Alternative Power Supply Pin:
- 3Vo / 3V3: An alternative power source, connected to 3.3V.
SPI Logic Pins (for SPI Communication):
- SDO: Data sent from the sensor.
- CS: Chip Select pin for starting SPI communication.
- SDI: Data sent to the sensor.
- SCK: SPI Clock input.
Multiple Sensors (SPI):
- You can share SDI, SDO, and SCK for multiple sensors and assign each a unique CS pin.
I2C Logic Pins (for I2C Communication):
- SDA / SDI: Data pin for I2C (connect to SDA or Analog input A4).
- SCL / SCK: Clock pin for I2C (connect to SCL or Analog input A5).
- ADDR: Used to change the I2C address (0x76 to 0x77) for multiple sensors.
Features & Specifications
- Sensor Type:Â Temperature, Humidity, Pressure, and Gas Sensor
- Integrated Circuit:Â Bosch BME688
- Temperature Measurement Range: -40°C to 85°C
- Temperature Measurement Accuracy: ±1°C
- Humidity Measurement Range:Â 10% to 90% Relative Humidity (RH)
- Humidity Measurement Accuracy: ±3%
- Pressure Measurement Range:Â 300 hPa to 1100 hPa
- Pressure Measurement Accuracy: ±1 hPa
- VOC Gas Measurement Range:Â 0 to 500 IAQ (Indoor Air Quality)
- Communication Interface:Â I2C Bus
- I2C Interface Address:Â 0x77
- Supply Voltage:Â 3V to 5V
- Connectors:Â STEMMA QT / Qwiic / Solder Fields (2.54 mm pitch)
- Mounting Holes:Â 4 pieces
- Board Dimensions:Â 25.5 x 17.6 x 4.6 mm
- Weight:Â 1.7 grams
BME688 Applications
- Weather stations for climate monitoring.
- Indoor Air Quality Monitoring
- IoT Environmental Monitoring
- Wearable Devices
- Air Pollution Detection
- Environmental Research
- Environmental Research
- Consumer Electronics
- IoT Agriculture
Interfacing BME688 Environmental Gas Sensor with Raspberry Pi Pico Using MicroPython
The wiring between BME688 and Pi Pico Is very simple, you can follow below fritzing circuit below.
Connect the BME680 sensor to the Raspberry Pi Pico as follows:
BME680 sensor module | Raspberry Pi Pico |
Vin | 5V |
GND | GND |
SCK | SCL (27) |
SDI | SDA (26) |
Make sure your hardware connections are secure.
MicroPython Code & Libraries For BME680
First Install MicroPython on your Pico by following my previous instructions. Setup Raspberry Pi Pico With Thonny IDE.Â
The code for interfacing the BME688 Sensor with Raspberry Pi Pico is divided into two parts.
- bme280.py
- main.pyÂ
The bme280.py library can extract data from the sensor. It has all the required modules and register details to extract data from the sensor.
bme680.py
- Launch the Thonny IDE; select File>New to open an editor window then paste the following code text into the Thonny editor ( Ctrl+V or Edit>Paste)—> File>Save to save the code shown below in your Raspberry Pi Pico as bme280.py —> File>Close).
- 2. Click the Run button
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 |
# The MIT License (MIT) # # Copyright (c) 2017 ladyada for Adafruit Industries # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # We have a lot of attributes for this complex sensor. # pylint: disable=too-many-instance-attributes """ `bme680` - BME680 - Temperature, Humidity, Pressure & Gas Sensor ================================================================ MicroPython driver from BME680 air quality sensor, based on Adafruit_bme680 * Author(s): Limor 'Ladyada' Fried of Adafruit Jeff Raber (SPI support) and many more contributors """ import time import math from micropython import const from ubinascii import hexlify as hex try: import struct except ImportError: import ustruct as struct # I2C ADDRESS/BITS/SETTINGS # ----------------------------------------------------------------------- _BME680_CHIPID = const(0x61) _BME680_REG_CHIPID = const(0xD0) _BME680_BME680_COEFF_ADDR1 = const(0x89) _BME680_BME680_COEFF_ADDR2 = const(0xE1) _BME680_BME680_RES_HEAT_0 = const(0x5A) _BME680_BME680_GAS_WAIT_0 = const(0x64) _BME680_REG_SOFTRESET = const(0xE0) _BME680_REG_CTRL_GAS = const(0x71) _BME680_REG_CTRL_HUM = const(0x72) _BME280_REG_STATUS = const(0xF3) _BME680_REG_CTRL_MEAS = const(0x74) _BME680_REG_CONFIG = const(0x75) _BME680_REG_PAGE_SELECT = const(0x73) _BME680_REG_MEAS_STATUS = const(0x1D) _BME680_REG_PDATA = const(0x1F) _BME680_REG_TDATA = const(0x22) _BME680_REG_HDATA = const(0x25) _BME680_SAMPLERATES = (0, 1, 2, 4, 8, 16) _BME680_FILTERSIZES = (0, 1, 3, 7, 15, 31, 63, 127) _BME680_RUNGAS = const(0x10) _LOOKUP_TABLE_1 = (2147483647.0, 2147483647.0, 2147483647.0, 2147483647.0, 2147483647.0, 2126008810.0, 2147483647.0, 2130303777.0, 2147483647.0, 2147483647.0, 2143188679.0, 2136746228.0, 2147483647.0, 2126008810.0, 2147483647.0, 2147483647.0) _LOOKUP_TABLE_2 = (4096000000.0, 2048000000.0, 1024000000.0, 512000000.0, 255744255.0, 127110228.0, 64000000.0, 32258064.0, 16016016.0, 8000000.0, 4000000.0, 2000000.0, 1000000.0, 500000.0, 250000.0, 125000.0) def _read24(arr): """Parse an unsigned 24-bit value as a floating point and return it.""" ret = 0.0 #print([hex(i) for i in arr]) for b in arr: ret *= 256.0 ret += float(b & 0xFF) return ret class Adafruit_BME680: """Driver from BME680 air quality sensor :param int refresh_rate: Maximum number of readings per second. Faster property reads will be from the previous reading.""" def __init__(self, *, refresh_rate=10): """Check the BME680 was found, read the coefficients and enable the sensor for continuous reads.""" self._write(_BME680_REG_SOFTRESET, [0xB6]) time.sleep(0.005) # Check device ID. chip_id = self._read_byte(_BME680_REG_CHIPID) if chip_id != _BME680_CHIPID: raise RuntimeError('Failed to find BME680! Chip ID 0x%x' % chip_id) self._read_calibration() # set up heater self._write(_BME680_BME680_RES_HEAT_0, [0x73]) self._write(_BME680_BME680_GAS_WAIT_0, [0x65]) self.sea_level_pressure = 1013.25 """Pressure in hectoPascals at sea level. Used to calibrate ``altitude``.""" # Default oversampling and filter register values. self._pressure_oversample = 0b011 self._temp_oversample = 0b100 self._humidity_oversample = 0b010 self._filter = 0b010 self._adc_pres = None self._adc_temp = None self._adc_hum = None self._adc_gas = None self._gas_range = None self._t_fine = None self._last_reading = time.ticks_ms() self._min_refresh_time = 1000 // refresh_rate @property def pressure_oversample(self): """The oversampling for pressure sensor""" return _BME680_SAMPLERATES[self._pressure_oversample] @pressure_oversample.setter def pressure_oversample(self, sample_rate): if sample_rate in _BME680_SAMPLERATES: self._pressure_oversample = _BME680_SAMPLERATES.index(sample_rate) else: raise RuntimeError("Invalid oversample") @property def humidity_oversample(self): """The oversampling for humidity sensor""" return _BME680_SAMPLERATES[self._humidity_oversample] @humidity_oversample.setter def humidity_oversample(self, sample_rate): if sample_rate in _BME680_SAMPLERATES: self._humidity_oversample = _BME680_SAMPLERATES.index(sample_rate) else: raise RuntimeError("Invalid oversample") @property def temperature_oversample(self): """The oversampling for temperature sensor""" return _BME680_SAMPLERATES[self._temp_oversample] @temperature_oversample.setter def temperature_oversample(self, sample_rate): if sample_rate in _BME680_SAMPLERATES: self._temp_oversample = _BME680_SAMPLERATES.index(sample_rate) else: raise RuntimeError("Invalid oversample") @property def filter_size(self): """The filter size for the built in IIR filter""" return _BME680_FILTERSIZES[self._filter] @filter_size.setter def filter_size(self, size): if size in _BME680_FILTERSIZES: self._filter = _BME680_FILTERSIZES[size] else: raise RuntimeError("Invalid size") @property def temperature(self): """The compensated temperature in degrees celsius.""" self._perform_reading() calc_temp = (((self._t_fine * 5) + 128) / 256) return calc_temp / 100 @property def pressure(self): """The barometric pressure in hectoPascals""" self._perform_reading() var1 = (self._t_fine / 2) - 64000 var2 = ((var1 / 4) * (var1 / 4)) / 2048 var2 = (var2 * self._pressure_calibration[5]) / 4 var2 = var2 + (var1 * self._pressure_calibration[4] * 2) var2 = (var2 / 4) + (self._pressure_calibration[3] * 65536) var1 = (((((var1 / 4) * (var1 / 4)) / 8192) * (self._pressure_calibration[2] * 32) / 8) + ((self._pressure_calibration[1] * var1) / 2)) var1 = var1 / 262144 var1 = ((32768 + var1) * self._pressure_calibration[0]) / 32768 calc_pres = 1048576 - self._adc_pres calc_pres = (calc_pres - (var2 / 4096)) * 3125 calc_pres = (calc_pres / var1) * 2 var1 = (self._pressure_calibration[8] * (((calc_pres / 8) * (calc_pres / 8)) / 8192)) / 4096 var2 = ((calc_pres / 4) * self._pressure_calibration[7]) / 8192 var3 = (((calc_pres / 256) ** 3) * self._pressure_calibration[9]) / 131072 calc_pres += ((var1 + var2 + var3 + (self._pressure_calibration[6] * 128)) / 16) return calc_pres/100 @property def humidity(self): """The relative humidity in RH %""" self._perform_reading() temp_scaled = ((self._t_fine * 5) + 128) / 256 var1 = ((self._adc_hum - (self._humidity_calibration[0] * 16)) - ((temp_scaled * self._humidity_calibration[2]) / 200)) var2 = (self._humidity_calibration[1] * (((temp_scaled * self._humidity_calibration[3]) / 100) + (((temp_scaled * ((temp_scaled * self._humidity_calibration[4]) / 100)) / 64) / 100) + 16384)) / 1024 var3 = var1 * var2 var4 = self._humidity_calibration[5] * 128 var4 = (var4 + ((temp_scaled * self._humidity_calibration[6]) / 100)) / 16 var5 = ((var3 / 16384) * (var3 / 16384)) / 1024 var6 = (var4 * var5) / 2 calc_hum = (((var3 + var6) / 1024) * 1000) / 4096 calc_hum /= 1000 # get back to RH if calc_hum > 100: calc_hum = 100 if calc_hum < 0: calc_hum = 0 return calc_hum @property def altitude(self): """The altitude based on current ``pressure`` vs the sea level pressure (``sea_level_pressure``) - which you must enter ahead of time)""" pressure = self.pressure # in Si units for hPascal return 44330 * (1.0 - math.pow(pressure / self.sea_level_pressure, 0.1903)) @property def gas(self): """The gas resistance in ohms""" self._perform_reading() var1 = ((1340 + (5 * self._sw_err)) * (_LOOKUP_TABLE_1[self._gas_range])) / 65536 var2 = ((self._adc_gas * 32768) - 16777216) + var1 var3 = (_LOOKUP_TABLE_2[self._gas_range] * var1) / 512 calc_gas_res = (var3 + (var2 / 2)) / var2 return int(calc_gas_res) def _perform_reading(self): """Perform a single-shot reading from the sensor and fill internal data structure for calculations""" expired = time.ticks_diff(self._last_reading, time.ticks_ms()) * time.ticks_diff(0, 1) if 0 <= expired < self._min_refresh_time: time.sleep_ms(self._min_refresh_time - expired) # set filter self._write(_BME680_REG_CONFIG, [self._filter << 2]) # turn on temp oversample & pressure oversample self._write(_BME680_REG_CTRL_MEAS, [(self._temp_oversample << 5)|(self._pressure_oversample << 2)]) # turn on humidity oversample self._write(_BME680_REG_CTRL_HUM, [self._humidity_oversample]) # gas measurements enabled self._write(_BME680_REG_CTRL_GAS, [_BME680_RUNGAS]) ctrl = self._read_byte(_BME680_REG_CTRL_MEAS) ctrl = (ctrl & 0xFC) | 0x01 # enable single shot! self._write(_BME680_REG_CTRL_MEAS, [ctrl]) new_data = False while not new_data: data = self._read(_BME680_REG_MEAS_STATUS, 15) new_data = data[0] & 0x80 != 0 time.sleep(0.005) self._last_reading = time.ticks_ms() self._adc_pres = _read24(data[2:5]) / 16 self._adc_temp = _read24(data[5:8]) / 16 self._adc_hum = struct.unpack('>H', bytes(data[8:10]))[0] self._adc_gas = int(struct.unpack('>H', bytes(data[13:15]))[0] / 64) self._gas_range = data[14] & 0x0F var1 = (self._adc_temp / 8) - (self._temp_calibration[0] * 2) var2 = (var1 * self._temp_calibration[1]) / 2048 var3 = ((var1 / 2) * (var1 / 2)) / 4096 var3 = (var3 * self._temp_calibration[2] * 16) / 16384 self._t_fine = int(var2 + var3) def _read_calibration(self): """Read & save the calibration coefficients""" coeff = self._read(_BME680_BME680_COEFF_ADDR1, 25) coeff += self._read(_BME680_BME680_COEFF_ADDR2, 16) coeff = list(struct.unpack('<hbBHhbBhhbbHhhBBBHbbbBbHhbb', bytes(coeff[1:39]))) # print("\n\n",coeff) coeff = [float(i) for i in coeff] self._temp_calibration = [coeff[x] for x in [23, 0, 1]] self._pressure_calibration = [coeff[x] for x in [3, 4, 5, 7, 8, 10, 9, 12, 13, 14]] self._humidity_calibration = [coeff[x] for x in [17, 16, 18, 19, 20, 21, 22]] self._gas_calibration = [coeff[x] for x in [25, 24, 26]] # flip around H1 & H2 self._humidity_calibration[1] *= 16 self._humidity_calibration[1] += self._humidity_calibration[0] % 16 self._humidity_calibration[0] /= 16 self._heat_range = (self._read_byte(0x02) & 0x30) / 16 self._heat_val = self._read_byte(0x00) self._sw_err = (self._read_byte(0x04) & 0xF0) / 16 def _read_byte(self, register): """Read a byte register value and return it""" return self._read(register, 1)[0] def _read(self, register, length): raise NotImplementedError() def _write(self, register, values): raise NotImplementedError() class BME680_I2C(Adafruit_BME680): """Driver for I2C connected BME680. :param i2c: I2C device object :param int address: I2C device address :param bool debug: Print debug statements when True. :param int refresh_rate: Maximum number of readings per second. Faster property reads will be from the previous reading.""" def __init__(self, i2c, address=0x77, debug=False, *, refresh_rate=10): """Initialize the I2C device at the 'address' given""" self._i2c = i2c self._address = address self._debug = debug super().__init__(refresh_rate=refresh_rate) def _read(self, register, length): """Returns an array of 'length' bytes from the 'register'""" result = bytearray(length) self._i2c.readfrom_mem_into(self._address, register & 0xff, result) if self._debug: print("\t${:x} read ".format(register), " ".join(["{:02x}".format(i) for i in result])) return result def _write(self, register, values): """Writes an array of 'length' bytes to the 'register'""" if self._debug: print("\t${:x} write".format(register), " ".join(["{:02x}".format(i) for i in values])) for value in values: self._i2c.writeto_mem(self._address, register, bytearray([value & 0xFF])) register += 1 class BME680_SPI(Adafruit_BME680): """Driver for SPI connected BME680. :param spi: SPI device object, configured :param cs: Chip Select Pin object, configured to OUT mode :param bool debug: Print debug statements when True. :param int refresh_rate: Maximum number of readings per second. Faster property reads will be from the previous reading. """ def __init__(self, spi, cs, debug=False, *, refresh_rate=10): self._spi = spi self._cs = cs self._debug = debug self._cs(1) super().__init__(refresh_rate=refresh_rate) def _read(self, register, length): if register != _BME680_REG_PAGE_SELECT: # _BME680_REG_PAGE_SELECT exists in both SPI memory pages # For all other registers, we must set the correct memory page self._set_spi_mem_page(register) register = (register | 0x80) & 0xFF # Read single, bit 7 high. try: self._cs(0) self._spi.write(bytearray([register])) # pylint: disable=no-member result = bytearray(length) self._spi.readinto(result) # pylint: disable=no-member if self._debug: print("\t${:x} read ".format(register), " ".join(["{:02x}".format(i) for i in result])) except Exception as e: print (e) result = None finally: self._cs(1) return result def _write(self, register, values): if register != _BME680_REG_PAGE_SELECT: # _BME680_REG_PAGE_SELECT exists in both SPI memory pages # For all other registers, we must set the correct memory page self._set_spi_mem_page(register) register &= 0x7F # Write, bit 7 low. try: self._cs(0) buffer = bytearray(2 * len(values)) for i, value in enumerate(values): buffer[2 * i] = register + i buffer[2 * i + 1] = value & 0xFF self._spi.write(buffer) # pylint: disable=no-member if self._debug: print("\t${:x} write".format(register), " ".join(["{:02x}".format(i) for i in values])) except Exception as e: print (e) finally: self._cs(1) def _set_spi_mem_page(self, register): spi_mem_page = 0x00 if register < 0x80: spi_mem_page = 0x10 self._write(_BME680_REG_PAGE_SELECT, [spi_mem_page]) |
main.py
Open a new tab in Thonny IDE and paste this code. Save the file as main.py on Raspberry Pi Pico.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
from machine import Pin, SoftI2C from time import sleep from bme680 import BME680_I2C def initialize_bme680(): i2c = SoftI2C(scl=Pin(27), sda=Pin(26)) bme = BME680_I2C(i2c=i2c) return bme def read_bme680_sensor(bme): try: temperature_C = bme.temperature temperature_F = (temperature_C * 9/5) + 32 humidity = bme.humidity pressure = bme.pressure gas_KOhms = bme.gas / 1000 return temperature_C, temperature_F, humidity, pressure, gas_KOhms except OSError as e: print('Failed to read BME680 sensor.') return None def main(): bme = initialize_bme680() while True: sensor_data = read_bme680_sensor(bme) if sensor_data is not None: temperature_C, temperature_F, humidity, pressure, gas_KOhms = sensor_data print(f'Temperature: {temperature_C:.2f} C | {temperature_F:.2f} F') print(f'Humidity: {humidity:.2f} %') print(f'Pressure: {pressure:.2f} hPa') print(f'Gas: {gas_KOhms:.2f} KOhms') print('-------') sleep(1) if __name__ == "__main__": main() |
Run the main.py file now. If hardware connections are correct, the Shell will show the following result.
You can check the values of temperature, humidity, pressure, and gas. You can also read the Dew Point and Altitude Using Above Library.